repo_id stringclasses 875
values | size int64 974 38.9k | file_path stringlengths 10 308 | content stringlengths 974 38.9k |
|---|---|---|---|
oracle/coherence | 37,182 | prj/test/functional/filter/src/main/java/filter/IndexTests.java | /*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package filter;
import com.tangosol.net.NamedCache;
import com.tangosol.util.Base;
import com.tangosol.util.ClassFilter;
import com.tangosol.util.Filter;
import com.tangosol.util.InvocableMap.Entry;
import com.tangosol.util.ValueExtractor;
import com.tangosol.util.extractor.AbstractExtractor;
import com.tangosol.util.extractor.ConditionalExtractor;
import com.tangosol.util.extractor.ReflectionExtractor;
import com.tangosol.util.extractor.IdentityExtractor;
import com.tangosol.util.filter.AlwaysFilter;
import com.tangosol.util.filter.AndFilter;
import com.tangosol.util.filter.ContainsAllFilter;
import com.tangosol.util.filter.EqualsFilter;
import com.tangosol.util.filter.ExtractorFilter;
import com.tangosol.util.filter.GreaterEqualsFilter;
import com.tangosol.util.filter.GreaterFilter;
import com.tangosol.util.filter.LessEqualsFilter;
import com.tangosol.util.filter.NeverFilter;
import com.tangosol.util.filter.NotEqualsFilter;
import com.tangosol.util.processor.AbstractProcessor;
import com.oracle.coherence.testing.AbstractFunctionalTest;
import data.Person;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.*;
/**
* Index-related tests
*
* @author coh 2011.03.07
*/
@SuppressWarnings({"unchecked", "rawtypes"})
@RunWith(Parameterized.class)
public class IndexTests
extends AbstractFunctionalTest
{
@Parameterized.Parameters(name = "sCacheName={0}")
public static Collection<String[]> parameters()
{
return Arrays.asList(new String[][]
{
{"dist-test"},
{"part-test"},
});
}
/**
* Test's constructor.
*
* @param sCacheName the cache name
*/
public IndexTests(String sCacheName)
{
m_sCacheName = sCacheName;
}
private final String m_sCacheName;
/**
* Return the name of the cache.
*
* @return the name of the cache
*/
private String getCacheName()
{
return m_sCacheName;
}
// ----- test lifecycle -------------------------------------------------
/**
* Initialize the test class.
*/
@BeforeClass
public static void _startup()
{
// this test requires local storage to be enabled
System.setProperty("coherence.distributed.localstorage", "true");
System.setProperty("coherence.distributed.threads", "4");
s_cIterations = Integer.getInteger("test.iterations", 1);
s_cThreads = Integer.getInteger("test.threads", 4);
AbstractFunctionalTest._startup();
}
@Before
public void _reset()
{
getNamedCache().removeIndex(IdentityExtractor.INSTANCE);
}
// ----- test methods ---------------------------------------------------
/**
* COH-10259: conditional index does not update correctly when the original
* value was filtered out.
*/
@Test
public void testCOH10259()
{
NamedCache cache = getNamedCache();
try
{
cache.clear();
cache.addIndex(new ConditionalExtractor(new EqualsFilter("getLastName", "Green"),
new ReflectionExtractor("getFirstName"), true), false, null);
Person person = new Person("1111");
person.setFirstName("Mike");
person.setLastName("Walker");
cache.put("customer", person);
assertEquals(0, cache.entrySet(new EqualsFilter("getFirstName", "Mike")).size());
Person personNew = new Person("1112");
personNew.setFirstName("Mike");
personNew.setLastName("Green");
cache.put("customer", personNew);
assertEquals(1, cache.entrySet(new EqualsFilter("getFirstName", "Mike")).size());
}
finally
{
cache.destroy();
}
}
@Test
public void testConcurrentProcessors()
{
final NamedCache cache = getNamedCache();
cache.addIndex(IdentityExtractor.INSTANCE, true, null);
UpdateThread[] updateThreads = startUpdateThreads(cache, 0);
for (int i = 0; i < s_cIterations; i++)
{
testProcessor(cache, new GreaterEqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
}
stopUpdateThreads(updateThreads);
}
@Test
public void testConditionalIndexOnKey()
{
final NamedCache<Long, String> cache = getNamedCache();
cache.clear();
ValueExtractor<Long, Integer> extractor = new LastDigit().fromKey();
Filter<String> condition = new NotEqualsFilter<>(ValueExtractor.identity(), "");
ConditionalExtractor condExtractor = new ConditionalExtractor<>(condition, extractor, false);
try
{
cache.addIndex(condExtractor, false, null);
Filter<?> query = new EqualsFilter<>(extractor, 3);
cache.put(123L, ""); //fail condition
assertTrue(cache.entrySet(query).isEmpty());
cache.put(123L, "notEmpty"); //pass condition
assertTrue(cache.entrySet(query).contains(new AbstractMap.SimpleEntry<>(123L, "notEmpty")));
cache.put(123L, ""); //fail condition
assertTrue(cache.entrySet(query).isEmpty());
}
finally
{
cache.removeIndex(condExtractor);
}
}
@Test
public void testConcurrentUpdates()
{
final NamedCache cache = getNamedCache();
cache.addIndex(IdentityExtractor.INSTANCE, true, null);
// Insert/Update
UpdateThread[] updateThreads = startUpdateThreads(cache, 0);
for (int i = 0; i < s_cIterations; i++)
{
testFilter(cache, new GreaterEqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
testFilter(cache, new EqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
testFilter(cache, new LessEqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
}
stopUpdateThreads(updateThreads);
}
@Test
public void testConcurrentUpdatesPartialIndex()
{
final NamedCache cache = getNamedCache();
cache.addIndex(IdentityExtractor.INSTANCE, true, null);
// Insert/Update
UpdateThread[] updateThreads = startUpdateThreads(cache, 0);
for (int i = 0; i < s_cIterations; i++)
{
testFilter(cache, new AndFilter(
new GreaterEqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE),
new GreaterEqualsFilter("hashCode", QUERY_VALUE)));
}
stopUpdateThreads(updateThreads);
}
@Test
public void testConcurrentUpdatesNoIndex()
{
final NamedCache cache = getNamedCache();
UpdateThread[] updateThreads = startUpdateThreads(cache, 0);
for (int i = 0; i < s_cIterations; i++)
{
testFilter(cache, new GreaterEqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
testFilter(cache, new EqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
testFilter(cache, new LessEqualsFilter(IdentityExtractor.INSTANCE, QUERY_VALUE));
}
stopUpdateThreads(updateThreads);
}
/**
* Regression test for COH-5575
*/
@Test
public void testCoh5575()
{
final NamedCache cache = getNamedCache("Coh5575-test");
final AtomicBoolean atomicFlag = new AtomicBoolean();
final long ldtStop = System.currentTimeMillis() + 5000;
final Throwable[] aeHolder = new Throwable[1];
try
{
Runnable rTest = new Runnable()
{
public void run()
{
ValueExtractor extractor = IdentityExtractor.INSTANCE;
while (System.currentTimeMillis() < ldtStop &&
!atomicFlag.get())
{
try
{
cache.addIndex(extractor, true, null);
cache.removeIndex(extractor);
}
catch (Throwable e)
{
aeHolder[0] = e;
atomicFlag.set(true);
}
}
}
};
Thread[] aThread = new Thread[4];
for (int i = 0, c = aThread.length; i < c; i++)
{
aThread[i] = new Thread(rTest);
aThread[i].setDaemon(true);
aThread[i].start();
}
for (int i = 0, c = aThread.length; i < c; i++)
{
aThread[i].join();
}
assertNull(String.valueOf(aeHolder[0]), aeHolder[0]);
}
catch (InterruptedException e)
{
throw Base.ensureRuntimeException(e);
}
finally
{
cache.destroy();
}
}
// COH-6447: when we encounter a corrupted entry, we no longer drop the index
@Test
public void testCorruptedIndex()
{
final NamedCache cache = getNamedCache("dist-CorruptIdx");
int cCorrupted = 10;
cache.addIndex(StringIntegerExtractor.INSTANCE, true, null);
// start concurrent updates with Integer values
UpdateThread[] updateThreads = startUpdateThreads(cache, 0);
// add 2 * cCorrupted entries with String values, half of them are corrupted,
// should be excluded from index
populateWithCorrupted(cache, cCorrupted);
// extractor picks only string values and index should discard malformed ones
Filter filterStringGT = new GreaterFilter(StringIntegerExtractor.INSTANCE, -cCorrupted);
Set<Map.Entry<Integer, Integer>> setResult = cache.entrySet(filterStringGT);
stopUpdateThreads(updateThreads);
int cStringGT = setResult.size();
assertEquals("Wrong result size for StringGT filter", cCorrupted, cStringGT);
// cache should contain: equal number of correct and "wrong-" strings
// plus Integer values inserted by update threads
Filter filterInteger = new ClassFilter(Integer.class);
int cInteger = cache.entrySet(filterInteger).size();
assertEquals("Wrong cache size ", cache.size(), 2 * cStringGT + cInteger);
correctCorrupted(cache, cCorrupted);
// there should be no excluded index now
setResult = cache.entrySet(filterStringGT);
assertEquals("Wrong result size for StringGE filter", 2 * cCorrupted, setResult.size());
// test concurrent delete of corrupted entries
populateWithCorrupted(cache, cCorrupted);
DeleteThread d1 = new DeleteThread(cache, -19, 5);
DeleteThread d2 = new DeleteThread(cache, -9, 5);
d1.start();
d2.start();
try
{
d1.join();
d2.join();
}
catch (InterruptedException e)
{
}
assertEquals("Wrong cache size after delete corrupted ", cache.size(), cInteger + cStringGT);
cache.removeIndex(StringIntegerExtractor.INSTANCE);
//test an index based on a non-deterministic extractor
ValueExtractor extractorND = new EveryOtherTimeExtractor();
cache.addIndex(extractorND, false, null);
cache.put("NonDet-1", "value-1-1"); //extractor works OK
//extractor fails, value should be removed from index
cache.put("NonDet-1", "value-1-2");
Filter filterND = new EqualsFilter(new EveryOtherTimeExtractor(), "value-1");
// thus, the value should not be part of query result based on that index
assertTrue("Update with failed EveryOtherTimeExtractor should remove value from index",
cache.entrySet(filterND).isEmpty());
// extractor will work OK, value should be added to the index
cache.put("NonDet-1", "value-1-3");
Set<Map.Entry> setND = cache.entrySet(filterND);
assertTrue("This time the value should be in index", setND.size() == 1);
Map.Entry entry = setND.iterator().next();
assertEquals("Incorrect value in the index", "value-1-3", entry.getValue());
cache.remove("NonDet-1");
assertTrue("After delete result of indexed query should be null",
cache.entrySet(filterND).isEmpty());
cache.removeIndex(extractorND);
// test corrupted entries with index that has no forward map
// use ConditionalIndex w/o forward map
testConditionalIndex(cache, false);
// use ConditionalIndex with forward map
testConditionalIndex(cache, true);
cache.destroy();
}
@Test
public void testCorruptedCollections()
{
final NamedCache cache = getNamedCache("dist-CollectIdx");
cache.addIndex(StringIntegerExtractor.INSTANCE, true, null);
// test collection values
// define and populate the Collection values
Collection<String> collection0 = new LinkedList<>();
Collection<String> collection1 = new LinkedList<>();
Collection<String> collection2 = new LinkedList<>();
Collection<String> collection3 = new LinkedList<>();
Collection<String> collection4 = new LinkedList<>();
collection0.add("8");
collection1.add("1");
collection1.add("2");
collection1.add("3");
collection2.add("2");
collection2.add("3");
collection2.add("4");
collection3.add("5");
collection3.add("6");
collection3.add("7");
collection3.add("8");
collection3.add("9");
// insert bad
collection4.add("wrong-7");
collection4.add("8");
collection4.add("9");
cache.put("c0", collection0);
cache.put("c1", collection1);
cache.put("c2", collection2);
cache.put("c3", collection3);
cache.put("c4", collection4);
// even though c4 contains a bogus element, the index should remain
HashSet<Integer> set23 = new HashSet<>();
set23.add(2);
set23.add(3);
Filter filterContAll_23 = new ContainsAllFilter(StringIntegerExtractor.INSTANCE, set23);
Set<String> setKeysAll_23 = cache.keySet(filterContAll_23);
boolean fHasC1 = false, fHasC2 = false;
for (Object oKey : setKeysAll_23)
{
if (oKey.equals("c1"))
{
fHasC1 = true;
}
else if (oKey.equals("c2"))
{
fHasC2 = true;
}
else
{
fail("Unexpected key " + oKey + "in ContainsAll{2,3} query result.");
}
}
assertTrue("Both c1 and c2 keys were expected in query result.", fHasC1 && fHasC2);
HashSet<Integer> set8 = new HashSet<>();
set8.add(8);
Filter filterContAll_8 = new ContainsAllFilter(StringIntegerExtractor.INSTANCE, set8);
Set<String> setKeyAll_8 = cache.keySet(filterContAll_8);
assertEquals("Key c4 should not be in query result.", 2, setKeyAll_8.size());
// insert good
collection4.remove("wrong-7");
collection4.add("7");
cache.put("c4", collection4);
setKeyAll_8 = cache.keySet(filterContAll_8);
assertEquals("Incorrect size of ContainsAll {8} query result", 3, setKeyAll_8.size());
// insert bad
collection4.remove("9");
collection4.add("wrong-9");
cache.put("c4", collection4);
setKeyAll_8 = cache.keySet(filterContAll_8);
assertEquals("Key c4 should not be in query result with wrong-9", 2, setKeyAll_8.size());
// delete
cache.remove("c4");
setKeysAll_23 = cache.keySet(filterContAll_23);
assertEquals("Unexpected result size after deleting c4", 2, setKeysAll_23.size());
setKeyAll_8 = cache.keySet(filterContAll_8);
assertEquals("Key c4 was removed and should not be in query result", 2, setKeyAll_8.size());
// now test updates without forward map
testCollectionsCondIndex(cache, false);
}
/**
* Regression test for COH-100600.
*/
@Test
public void testCoh10600()
{
NamedCache cache = getNamedCache();
cache.put("key", "value");
cache.addIndex(IdentityExtractor.INSTANCE, false, null);
cache.entrySet(new BadFilter());
cache.remove("key");
// this will cause the index update fail and remove the index
BadFilter.s_fFail = true;
cache.put("key", new BadFilter());
BadFilter.s_fFail = false;
cache.addIndex(IdentityExtractor.INSTANCE, false, null);
cache.put("key", "value");
// before COH-100600 fix, the following line would throw
cache.entrySet(new BadFilter());
}
// ----- internal methods ------------------------------------------------
/**
* Test Conditional index in combination with failing value extractor.
*/
private void testConditionalIndex(NamedCache cache, boolean fFwdIdx)
{
ValueExtractor extractorCond = new ConditionalExtractor(
new EvenIntFilter(StringIntegerExtractor.INSTANCE),
StringIntegerExtractor.INSTANCE, fFwdIdx);
// use the same boolean to vary the ordered argument
cache.addIndex(extractorCond, fFwdIdx, null);
Set<Map.Entry> setCache = cache.entrySet();
// count the number of even integers by brute force
int cEvenInt = 0;
int cEvenStr = 0;
for (Map.Entry result : setCache)
{
Object oValue = result.getValue();
if (oValue instanceof Integer)
{
if (((Integer) oValue) % 2 == 0)
{
cEvenInt++;
}
}
else if(oValue instanceof String)
{
if (Integer.parseInt((String) oValue) % 2 == 0)
{
cEvenStr++;
}
}
}
cache.put(-6, "wrong--6");
Filter filterAll = new ExtractorFilter(StringIntegerExtractor.INSTANCE)
{
protected boolean evaluateExtracted(Object oExtracted)
{
return true;
}
};
// only entries in conditional index should be returned, i.e. only 'even' strings
assertEquals("Query result based on conditional index is wrong (forwardIndex=" +
fFwdIdx + ")", cEvenStr, cache.entrySet(filterAll).size());
cache.put(-6, "-6");
assertEquals("Query result size should have increased by 1 (forwardIndex=" +
fFwdIdx + ")", cEvenStr+1, cache.entrySet(filterAll).size());
cache.put(-6, "wrongagain--6");
assertEquals("Query result size should have gone back (forwardIndex=" +
fFwdIdx + ")", cEvenStr, cache.entrySet(filterAll).size());
cache.remove(-6);
assertEquals("Query result size should remain the same (forwardIndex=" +
fFwdIdx + ")", cEvenStr, cache.entrySet(filterAll).size());
cache.removeIndex(extractorCond);
}
/**
* Test a failing value extractor on collections with conditional index
* and no forward map.
*/
private void testCollectionsCondIndex(NamedCache cache, boolean fFwdIdx)
{
ValueExtractor extractorCond = new ConditionalExtractor(new AlwaysFilter(), new EveryOtherTimeExtractor(), fFwdIdx);
// test update with intersecting old and new values and non-deterministic extractor
cache.addIndex(extractorCond, fFwdIdx, null);
Collection<String> colValueStrings = new HashSet<>();
colValueStrings.add("value-1");
colValueStrings.add("value-2");
colValueStrings.add("value-3");
colValueStrings.add("value-4");
// insert: extractor works(1); colVal1->{1,2,3,4} in index
cache.put("colVal1", colValueStrings);
colValueStrings.remove("value-3");
colValueStrings.add("value-5");
// update: extractor doesn't work on new value(2), thus, colVal is not in the index.
// extractor works(3) for removing the old value (when no forward index);
// colVal1->{1,2,4,5} not in index
cache.put("colVal1", colValueStrings);
// extractor doesn't work for delete(4), full scan
cache.remove("colVal1");
// insert: extractor works(5); colVal1->{1,2,4,5} in index
cache.put("colVal1", colValueStrings);
// insert: extractor doesn't work(6) for colVal2->{1,2,4,5} not in index
cache.put("colVal2", colValueStrings);
// update: extractor works for new value(7), breaks for old value
// when forwardMap is not present(8), so we do full scan
// with remove of individual old values non-intersecting with new values
// colVal1->{1,2,5,6} in index
colValueStrings.remove("value-4");
colValueStrings.add("value-6");
cache.put("colVal1", colValueStrings);
HashSet<String> setAll = new HashSet<>();
setAll.add("value-1");
setAll.add("value-2");
setAll.add("value-5");
setAll.add("value-6");
Filter filterContAll = new ContainsAllFilter(new EveryOtherTimeExtractor(), setAll);
Set<String> setKeyAll = cache.keySet(filterContAll);
assertEquals("Query is expected to contain one key mapped to collection.",
1, setKeyAll.size());
assertEquals("Unexpected key returned by query on collections.",
"colVal1", setKeyAll.iterator().next());
// update: extractor works for new value(9), breaks on old value (10),
// full scan deletes nothing as colVal2 was not in index before
cache.put("colVal2", colValueStrings);
// this time there must be two entries in the index
setKeyAll = cache.keySet(filterContAll);
assertEquals("Now the query is expected to contain two keys mapped to collection",
2, setKeyAll.size());
assertTrue("Expected colVal1 key in query result", setKeyAll.contains("colVal1"));
assertTrue("Expected colVal2 key in query result", setKeyAll.contains("colVal2"));
}
private UpdateThread[] startUpdateThreads(final NamedCache cache, int sleep)
{
UpdateThread[] updateThreads = new UpdateThread[s_cThreads];
for (int i = 0; i < s_cThreads; i++)
{
UpdateThread updateThread = new UpdateThread(cache, sleep);
updateThread.setDaemon(true);
updateThread.start();
updateThreads[i] = updateThread;
}
return updateThreads;
}
private void stopUpdateThreads(UpdateThread[] updateThreads)
{
for (int i = 0; i < updateThreads.length; i++)
{
updateThreads[i].quit();
}
for (int i = 0; i < updateThreads.length; i++)
{
try
{
updateThreads[i].join();
}
catch (InterruptedException e) {}
}
}
private void testFilter(NamedCache cache, Filter filter)
{
long start = System.currentTimeMillis();
long totalResults = 0L;
Set<Map.Entry<Integer, Integer>> setResults;
for (int i = 0; i <= MAX_ATTEMPTS; i++)
{
setResults = cache.entrySet(filter);
totalResults += setResults.size();
// Verify that the result set is actually correct
for (Map.Entry<Integer, Integer> entry : setResults)
{
assertTrue("evaluation of " + entry.getKey() + " "
+ entry.getValue() + " by '" + filter + "' failed on attempt "
+ i, filter.evaluate(entry.getValue()));
}
}
trace("Total results for filter (" + filter + "): " + totalResults + " in " + (System.currentTimeMillis() - start) + "ms.");
}
private void testProcessor(NamedCache cache, Filter filter)
{
long start = System.currentTimeMillis();
long totalResults = 0L;
Map<Integer, Integer> mapResult;
UpdateAgent agent = new UpdateAgent(QUERY_VALUE);
for (int i = 0; i <= MAX_ATTEMPTS; i++)
{
mapResult = cache.invokeAll(filter, agent);
totalResults += mapResult.size();
for (Map.Entry<Integer, Integer> entry : mapResult.entrySet())
{
assertEquals(entry.getKey(), entry.getValue());
}
}
trace("Total processed results for filter (" + filter + "): " + totalResults + " in " + (System.currentTimeMillis() - start) + "ms.");
}
/**
* Return the cache used in all test methods.
*
* @return the test cache
*/
protected NamedCache getNamedCache()
{
return getNamedCache(getCacheName());
}
private static void populateWithCorrupted(NamedCache cache, int cValid)
{
String si;
// use only odd keys to avoid a clash with update threads insertions
for (int i = 1; i < cValid*2; i = i+2)
{
si = Integer.toString(i);
cache.put(i, si);
cache.put(-i, "wrong-" + si);
}
}
private static void correctCorrupted(NamedCache cache, int cValid)
{
for (int i = 1; i < cValid*2; i = i+2)
{
cache.put(-i, Integer.toString(i));
}
}
public static class UpdateAgent
extends AbstractProcessor
implements Serializable
{
public UpdateAgent(int queryValue)
{
this.queryValue = queryValue;
}
public Object process(Entry entry)
{
assertTrue("Value " + entry.getValue() + " is not greater or equal to " + queryValue,
((Integer) entry.getValue()) >= queryValue);
// Set back the value to something predictable: (key)
Object newValue = entry.getKey();
entry.setValue(newValue);
return newValue;
}
private int queryValue;
}
public static class UpdateThread
extends Thread
{
public UpdateThread(NamedCache cache, int sleep)
{
this.m_cache = cache;
this.m_cSleepMillis = sleep;
this.m_fRun = true;
}
public void quit()
{
m_fRun = false;
}
/**
* @{inheritDoc}
*/
public void run()
{
try
{
while (m_fRun)
{
// use only even keys, avoid overwriting the keys inserted in tests
int key = m_random.nextInt(MAX_OBJECTS / 2) * 2;
int val = m_random.nextInt(MAX_OBJECTS / 2) * 2;
m_cache.put(key, val);
if (m_cSleepMillis > 0)
{
sleep(m_cSleepMillis);
}
}
}
catch (InterruptedException e)
{}
}
private final NamedCache m_cache;
private final int m_cSleepMillis;
private volatile boolean m_fRun;
private Random m_random = new Random();
}
public static class StringIntegerExtractor extends AbstractExtractor
{
// ----- ValueExtractor interface ---------------------------------------
/**
* read string, or collection of strings as Integer, or collection of Integers
*/
public Object extract(Object oTarget)
{
if (oTarget instanceof Collection)
{
Collection colResult = new HashSet<Integer>();
for (Object obj : (Collection) oTarget)
{
colResult.add(extract(obj));
}
return colResult;
}
else if (oTarget instanceof Object[])
{
Object[] arrTarget = (Object[]) oTarget;
int cLength = arrTarget.length;
Integer[] arrResult = new Integer[cLength];
for (int i=0; i<cLength; i++)
{
arrResult[i] = (Integer)extract(arrTarget[i]);
}
return arrResult;
}
else if (!(oTarget instanceof String))
{
return null;
}
return Integer.parseInt(((String) oTarget));
}
public String toString()
{
return "StringIntegerExtractor";
}
// ---- constants -------------------------------------------------------
/**
* An instance of the StringIntegerExtractor.
*/
public static final StringIntegerExtractor INSTANCE = new StringIntegerExtractor();
}
/**
* This value extractor simulates non-deterministic behavior:
* it returns null for all values that are not strings which
* start with "value-". For "value-*" strings it returns a substring
* of first 7 characters, but it fails every other time it is called.
*/
public static class EveryOtherTimeExtractor extends AbstractExtractor
{
/**
* Default constructor
*/
public EveryOtherTimeExtractor()
{
cCalls = 0;
fFail = true;
}
// ----- ValueExtractor interface ---------------------------------------
/**
* @{inheritDoc}
*/
public Object extract(Object oTarget)
{
if (oTarget instanceof Collection)
{
// consider entire collection a single 'call'
if (++cCalls % 2 == 0)
{
throw new RuntimeException("EveryOtherTimeExtractor was called " +
cCalls + " times and threw an exception.");
}
fFail = false;
Collection colResult = new HashSet<Integer>();
for (Object obj : (Collection) oTarget)
{
colResult.add(extract(obj));
}
fFail = true;
return colResult;
}
else if (oTarget instanceof Object[])
{
// consider entire array a single 'call'
if (++cCalls % 2 == 0)
{
throw new RuntimeException("EveryOtherTimeExtractor was called " +
cCalls + " times and threw an exception.");
}
fFail = false;
Object[] arrTarget = (Object[]) oTarget;
int cLength = arrTarget.length;
Integer[] arrResult = new Integer[cLength];
for (int i = 0; i < cLength; i++)
{
arrResult[i] = (Integer) extract(arrTarget[i]);
}
fFail = true;
return arrResult;
}
else if (!(oTarget instanceof String) || !((String) oTarget).startsWith("value-"))
{
return null;
}
// evaluating collection, don't count and don't fail on individual values
if (!fFail)
{
return ((String) oTarget).substring(0, 7);
}
if (++cCalls % 2 == 1)
{
return ((String)oTarget).substring(0,7);
}
else
{
throw new RuntimeException("EveryOtherTimeExtractor was called " +
cCalls + " times and threw an exception.");
}
}
public String toString()
{
return "EveryOtherTimeExtractor";
}
// ----- Object methods -------------------------------------------------
/**
* Compare the EveryOtherTimeExtractor with another object to determine
* equality. All EveryOtherTimeExtractors are equal.
*
* @return true iff the passed object is an EveryOtherTimeExtractor
*/
public boolean equals(Object o)
{
return o instanceof EveryOtherTimeExtractor;
}
public int hashCode()
{
return 55;
}
// ---- Instance Members -------------------------------------------------------
/**
* A counter of sequential calls to the value extractor
*/
private int cCalls;
/**
* Controls the recursive behavior of extractor
*/
private boolean fFail;
}
public class EvenIntFilter extends ExtractorFilter
{
/**
* @{inheritDoc}
*/
public EvenIntFilter(ValueExtractor extractor)
{
super(extractor);
}
/**
* @{inheritDoc}
*/
public boolean evaluateExtracted(Object o)
{
// extractor should convert to integer
if (!(o instanceof Integer))
{
return false;
}
return ((Integer)o) % 2 == 0;
}
}
public static class DeleteThread extends Thread
{
public DeleteThread(NamedCache cache, int startKey, int count)
{
m_cache = cache;
m_startKey = startKey;
m_count = count;
}
/**
* @{inheritDoc}
*/
public void run()
{
for (int k = 0; k < m_count*2; k=k+2)
{
m_cache.remove(m_startKey + k);
try
{
sleep(200);
}
catch (InterruptedException e)
{
}
}
}
private final NamedCache m_cache;
private final int m_startKey;
private final int m_count;
}
public static class BadFilter
extends NeverFilter
{
public Filter applyIndex(Map mapIndexes, Set setKeys)
{
if (mapIndexes.isEmpty())
{
throw new RuntimeException("Index is missing");
}
return super.applyIndex(mapIndexes, setKeys);
}
public int hashCode()
{
if (s_fFail)
{
throw new RuntimeException("Intentional");
}
return super.hashCode();
}
public static boolean s_fFail;
}
public class LastDigit
implements ValueExtractor<Long, Integer>
{
@Override
public Integer extract(Long key)
{
String digits = key.toString();
Integer ret = Integer.parseInt(digits.substring(digits.length() - 1));
return ret;
}
@Override
public int hashCode()
{
return -89342518;
}
@Override
public boolean equals(Object that)
{
return that instanceof LastDigit;
}
}
// ----- constants and data members -------------------------------------
private static Integer s_cIterations;
private static Integer s_cThreads;
static final int QUERY_VALUE = 12;
static final int MAX_OBJECTS = 24;
static final int MAX_ATTEMPTS = 10000;
}
|
googleapis/google-cloud-java | 37,328 | java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/UsableSubnetworkSecondaryRange.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>
* Secondary IP range of a usable subnetwork.
* </pre>
*
* Protobuf type {@code google.container.v1beta1.UsableSubnetworkSecondaryRange}
*/
public final class UsableSubnetworkSecondaryRange extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.container.v1beta1.UsableSubnetworkSecondaryRange)
UsableSubnetworkSecondaryRangeOrBuilder {
private static final long serialVersionUID = 0L;
// Use UsableSubnetworkSecondaryRange.newBuilder() to construct.
private UsableSubnetworkSecondaryRange(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UsableSubnetworkSecondaryRange() {
rangeName_ = "";
ipCidrRange_ = "";
status_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UsableSubnetworkSecondaryRange();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_UsableSubnetworkSecondaryRange_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_UsableSubnetworkSecondaryRange_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.class,
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Builder.class);
}
/**
*
*
* <pre>
* Status shows the current usage of a secondary IP range.
* </pre>
*
* Protobuf enum {@code google.container.v1beta1.UsableSubnetworkSecondaryRange.Status}
*/
public enum Status implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* UNKNOWN is the zero value of the Status enum. It's not a valid status.
* </pre>
*
* <code>UNKNOWN = 0;</code>
*/
UNKNOWN(0),
/**
*
*
* <pre>
* UNUSED denotes that this range is unclaimed by any cluster.
* </pre>
*
* <code>UNUSED = 1;</code>
*/
UNUSED(1),
/**
*
*
* <pre>
* IN_USE_SERVICE denotes that this range is claimed by a cluster for
* services. It cannot be used for other clusters.
* </pre>
*
* <code>IN_USE_SERVICE = 2;</code>
*/
IN_USE_SERVICE(2),
/**
*
*
* <pre>
* IN_USE_SHAREABLE_POD denotes this range was created by the network admin
* and is currently claimed by a cluster for pods. It can only be used by
* other clusters as a pod range.
* </pre>
*
* <code>IN_USE_SHAREABLE_POD = 3;</code>
*/
IN_USE_SHAREABLE_POD(3),
/**
*
*
* <pre>
* IN_USE_MANAGED_POD denotes this range was created by GKE and is claimed
* for pods. It cannot be used for other clusters.
* </pre>
*
* <code>IN_USE_MANAGED_POD = 4;</code>
*/
IN_USE_MANAGED_POD(4),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* UNKNOWN is the zero value of the Status enum. It's not a valid status.
* </pre>
*
* <code>UNKNOWN = 0;</code>
*/
public static final int UNKNOWN_VALUE = 0;
/**
*
*
* <pre>
* UNUSED denotes that this range is unclaimed by any cluster.
* </pre>
*
* <code>UNUSED = 1;</code>
*/
public static final int UNUSED_VALUE = 1;
/**
*
*
* <pre>
* IN_USE_SERVICE denotes that this range is claimed by a cluster for
* services. It cannot be used for other clusters.
* </pre>
*
* <code>IN_USE_SERVICE = 2;</code>
*/
public static final int IN_USE_SERVICE_VALUE = 2;
/**
*
*
* <pre>
* IN_USE_SHAREABLE_POD denotes this range was created by the network admin
* and is currently claimed by a cluster for pods. It can only be used by
* other clusters as a pod range.
* </pre>
*
* <code>IN_USE_SHAREABLE_POD = 3;</code>
*/
public static final int IN_USE_SHAREABLE_POD_VALUE = 3;
/**
*
*
* <pre>
* IN_USE_MANAGED_POD denotes this range was created by GKE and is claimed
* for pods. It cannot be used for other clusters.
* </pre>
*
* <code>IN_USE_MANAGED_POD = 4;</code>
*/
public static final int IN_USE_MANAGED_POD_VALUE = 4;
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 Status 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 Status forNumber(int value) {
switch (value) {
case 0:
return UNKNOWN;
case 1:
return UNUSED;
case 2:
return IN_USE_SERVICE;
case 3:
return IN_USE_SHAREABLE_POD;
case 4:
return IN_USE_MANAGED_POD;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Status> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<Status> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Status>() {
public Status findValueByNumber(int number) {
return Status.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.UsableSubnetworkSecondaryRange.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final Status[] VALUES = values();
public static Status 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 Status(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.container.v1beta1.UsableSubnetworkSecondaryRange.Status)
}
public static final int RANGE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object rangeName_ = "";
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @return The rangeName.
*/
@java.lang.Override
public java.lang.String getRangeName() {
java.lang.Object ref = rangeName_;
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();
rangeName_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @return The bytes for rangeName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRangeNameBytes() {
java.lang.Object ref = rangeName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
rangeName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IP_CIDR_RANGE_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object ipCidrRange_ = "";
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @return The ipCidrRange.
*/
@java.lang.Override
public java.lang.String getIpCidrRange() {
java.lang.Object ref = ipCidrRange_;
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();
ipCidrRange_ = s;
return s;
}
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @return The bytes for ipCidrRange.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIpCidrRangeBytes() {
java.lang.Object ref = ipCidrRange_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipCidrRange_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int STATUS_FIELD_NUMBER = 3;
private int status_ = 0;
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override
public int getStatusValue() {
return status_;
}
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @return The status.
*/
@java.lang.Override
public com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status getStatus() {
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status result =
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status.forNumber(status_);
return result == null
? com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status.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(rangeName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, rangeName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(ipCidrRange_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, ipCidrRange_);
}
if (status_
!= com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status.UNKNOWN.getNumber()) {
output.writeEnum(3, status_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(rangeName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, rangeName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(ipCidrRange_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, ipCidrRange_);
}
if (status_
!= com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status.UNKNOWN.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, status_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.container.v1beta1.UsableSubnetworkSecondaryRange)) {
return super.equals(obj);
}
com.google.container.v1beta1.UsableSubnetworkSecondaryRange other =
(com.google.container.v1beta1.UsableSubnetworkSecondaryRange) obj;
if (!getRangeName().equals(other.getRangeName())) return false;
if (!getIpCidrRange().equals(other.getIpCidrRange())) return false;
if (status_ != other.status_) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RANGE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getRangeName().hashCode();
hash = (37 * hash) + IP_CIDR_RANGE_FIELD_NUMBER;
hash = (53 * hash) + getIpCidrRange().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange 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.UsableSubnetworkSecondaryRange parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange 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.UsableSubnetworkSecondaryRange parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange 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.UsableSubnetworkSecondaryRange parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange 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.UsableSubnetworkSecondaryRange parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange 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.UsableSubnetworkSecondaryRange 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>
* Secondary IP range of a usable subnetwork.
* </pre>
*
* Protobuf type {@code google.container.v1beta1.UsableSubnetworkSecondaryRange}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.container.v1beta1.UsableSubnetworkSecondaryRange)
com.google.container.v1beta1.UsableSubnetworkSecondaryRangeOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_UsableSubnetworkSecondaryRange_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_UsableSubnetworkSecondaryRange_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.class,
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Builder.class);
}
// Construct using com.google.container.v1beta1.UsableSubnetworkSecondaryRange.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
rangeName_ = "";
ipCidrRange_ = "";
status_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_UsableSubnetworkSecondaryRange_descriptor;
}
@java.lang.Override
public com.google.container.v1beta1.UsableSubnetworkSecondaryRange getDefaultInstanceForType() {
return com.google.container.v1beta1.UsableSubnetworkSecondaryRange.getDefaultInstance();
}
@java.lang.Override
public com.google.container.v1beta1.UsableSubnetworkSecondaryRange build() {
com.google.container.v1beta1.UsableSubnetworkSecondaryRange result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.container.v1beta1.UsableSubnetworkSecondaryRange buildPartial() {
com.google.container.v1beta1.UsableSubnetworkSecondaryRange result =
new com.google.container.v1beta1.UsableSubnetworkSecondaryRange(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.container.v1beta1.UsableSubnetworkSecondaryRange result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.rangeName_ = rangeName_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.ipCidrRange_ = ipCidrRange_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.status_ = status_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.container.v1beta1.UsableSubnetworkSecondaryRange) {
return mergeFrom((com.google.container.v1beta1.UsableSubnetworkSecondaryRange) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.container.v1beta1.UsableSubnetworkSecondaryRange other) {
if (other == com.google.container.v1beta1.UsableSubnetworkSecondaryRange.getDefaultInstance())
return this;
if (!other.getRangeName().isEmpty()) {
rangeName_ = other.rangeName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getIpCidrRange().isEmpty()) {
ipCidrRange_ = other.ipCidrRange_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
rangeName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
ipCidrRange_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
status_ = 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 rangeName_ = "";
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @return The rangeName.
*/
public java.lang.String getRangeName() {
java.lang.Object ref = rangeName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
rangeName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @return The bytes for rangeName.
*/
public com.google.protobuf.ByteString getRangeNameBytes() {
java.lang.Object ref = rangeName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
rangeName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @param value The rangeName to set.
* @return This builder for chaining.
*/
public Builder setRangeName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
rangeName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearRangeName() {
rangeName_ = getDefaultInstance().getRangeName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding
* an alias IP range to a VM instance.
* </pre>
*
* <code>string range_name = 1;</code>
*
* @param value The bytes for rangeName to set.
* @return This builder for chaining.
*/
public Builder setRangeNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
rangeName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object ipCidrRange_ = "";
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @return The ipCidrRange.
*/
public java.lang.String getIpCidrRange() {
java.lang.Object ref = ipCidrRange_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipCidrRange_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @return The bytes for ipCidrRange.
*/
public com.google.protobuf.ByteString getIpCidrRangeBytes() {
java.lang.Object ref = ipCidrRange_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipCidrRange_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @param value The ipCidrRange to set.
* @return This builder for chaining.
*/
public Builder setIpCidrRange(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ipCidrRange_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearIpCidrRange() {
ipCidrRange_ = getDefaultInstance().getIpCidrRange();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range.
* </pre>
*
* <code>string ip_cidr_range = 2;</code>
*
* @param value The bytes for ipCidrRange to set.
* @return This builder for chaining.
*/
public Builder setIpCidrRangeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ipCidrRange_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int status_ = 0;
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override
public int getStatusValue() {
return status_;
}
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @param value The enum numeric value on the wire for status to set.
* @return This builder for chaining.
*/
public Builder setStatusValue(int value) {
status_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @return The status.
*/
@java.lang.Override
public com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status getStatus() {
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status result =
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status.forNumber(status_);
return result == null
? com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @param value The status to set.
* @return This builder for chaining.
*/
public Builder setStatus(
com.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
status_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* This field is to determine the status of the secondary range programmably.
* </pre>
*
* <code>.google.container.v1beta1.UsableSubnetworkSecondaryRange.Status status = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearStatus() {
bitField0_ = (bitField0_ & ~0x00000004);
status_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.container.v1beta1.UsableSubnetworkSecondaryRange)
}
// @@protoc_insertion_point(class_scope:google.container.v1beta1.UsableSubnetworkSecondaryRange)
private static final com.google.container.v1beta1.UsableSubnetworkSecondaryRange DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.container.v1beta1.UsableSubnetworkSecondaryRange();
}
public static com.google.container.v1beta1.UsableSubnetworkSecondaryRange getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UsableSubnetworkSecondaryRange> PARSER =
new com.google.protobuf.AbstractParser<UsableSubnetworkSecondaryRange>() {
@java.lang.Override
public UsableSubnetworkSecondaryRange 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<UsableSubnetworkSecondaryRange> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UsableSubnetworkSecondaryRange> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.container.v1beta1.UsableSubnetworkSecondaryRange getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,373 | java-discoveryengine/proto-google-cloud-discoveryengine-v1/src/main/java/com/google/cloud/discoveryengine/v1/ListSchemasResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/discoveryengine/v1/schema_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1;
/**
*
*
* <pre>
* Response message for
* [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1.ListSchemasResponse}
*/
public final class ListSchemasResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1.ListSchemasResponse)
ListSchemasResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSchemasResponse.newBuilder() to construct.
private ListSchemasResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSchemasResponse() {
schemas_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSchemasResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1_ListSchemasResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1_ListSchemasResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1.ListSchemasResponse.class,
com.google.cloud.discoveryengine.v1.ListSchemasResponse.Builder.class);
}
public static final int SCHEMAS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.discoveryengine.v1.Schema> schemas_;
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.discoveryengine.v1.Schema> getSchemasList() {
return schemas_;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.discoveryengine.v1.SchemaOrBuilder>
getSchemasOrBuilderList() {
return schemas_;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
@java.lang.Override
public int getSchemasCount() {
return schemas_.size();
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1.Schema getSchemas(int index) {
return schemas_.get(index);
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1.SchemaOrBuilder getSchemasOrBuilder(int index) {
return schemas_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < schemas_.size(); i++) {
output.writeMessage(1, schemas_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < schemas_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, schemas_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1.ListSchemasResponse)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1.ListSchemasResponse other =
(com.google.cloud.discoveryengine.v1.ListSchemasResponse) obj;
if (!getSchemasList().equals(other.getSchemasList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getSchemasCount() > 0) {
hash = (37 * hash) + SCHEMAS_FIELD_NUMBER;
hash = (53 * hash) + getSchemasList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.discoveryengine.v1.ListSchemasResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for
* [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1.ListSchemasResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1.ListSchemasResponse)
com.google.cloud.discoveryengine.v1.ListSchemasResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1_ListSchemasResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1_ListSchemasResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1.ListSchemasResponse.class,
com.google.cloud.discoveryengine.v1.ListSchemasResponse.Builder.class);
}
// Construct using com.google.cloud.discoveryengine.v1.ListSchemasResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (schemasBuilder_ == null) {
schemas_ = java.util.Collections.emptyList();
} else {
schemas_ = null;
schemasBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.discoveryengine.v1.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1_ListSchemasResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1.ListSchemasResponse getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1.ListSchemasResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1.ListSchemasResponse build() {
com.google.cloud.discoveryengine.v1.ListSchemasResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1.ListSchemasResponse buildPartial() {
com.google.cloud.discoveryengine.v1.ListSchemasResponse result =
new com.google.cloud.discoveryengine.v1.ListSchemasResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.discoveryengine.v1.ListSchemasResponse result) {
if (schemasBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
schemas_ = java.util.Collections.unmodifiableList(schemas_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.schemas_ = schemas_;
} else {
result.schemas_ = schemasBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.discoveryengine.v1.ListSchemasResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.discoveryengine.v1.ListSchemasResponse) {
return mergeFrom((com.google.cloud.discoveryengine.v1.ListSchemasResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.discoveryengine.v1.ListSchemasResponse other) {
if (other == com.google.cloud.discoveryengine.v1.ListSchemasResponse.getDefaultInstance())
return this;
if (schemasBuilder_ == null) {
if (!other.schemas_.isEmpty()) {
if (schemas_.isEmpty()) {
schemas_ = other.schemas_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSchemasIsMutable();
schemas_.addAll(other.schemas_);
}
onChanged();
}
} else {
if (!other.schemas_.isEmpty()) {
if (schemasBuilder_.isEmpty()) {
schemasBuilder_.dispose();
schemasBuilder_ = null;
schemas_ = other.schemas_;
bitField0_ = (bitField0_ & ~0x00000001);
schemasBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSchemasFieldBuilder()
: null;
} else {
schemasBuilder_.addAllMessages(other.schemas_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.discoveryengine.v1.Schema m =
input.readMessage(
com.google.cloud.discoveryengine.v1.Schema.parser(), extensionRegistry);
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(m);
} else {
schemasBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.discoveryengine.v1.Schema> schemas_ =
java.util.Collections.emptyList();
private void ensureSchemasIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
schemas_ = new java.util.ArrayList<com.google.cloud.discoveryengine.v1.Schema>(schemas_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1.Schema,
com.google.cloud.discoveryengine.v1.Schema.Builder,
com.google.cloud.discoveryengine.v1.SchemaOrBuilder>
schemasBuilder_;
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public java.util.List<com.google.cloud.discoveryengine.v1.Schema> getSchemasList() {
if (schemasBuilder_ == null) {
return java.util.Collections.unmodifiableList(schemas_);
} else {
return schemasBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public int getSchemasCount() {
if (schemasBuilder_ == null) {
return schemas_.size();
} else {
return schemasBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1.Schema getSchemas(int index) {
if (schemasBuilder_ == null) {
return schemas_.get(index);
} else {
return schemasBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder setSchemas(int index, com.google.cloud.discoveryengine.v1.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.set(index, value);
onChanged();
} else {
schemasBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder setSchemas(
int index, com.google.cloud.discoveryengine.v1.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.set(index, builderForValue.build());
onChanged();
} else {
schemasBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder addSchemas(com.google.cloud.discoveryengine.v1.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.add(value);
onChanged();
} else {
schemasBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder addSchemas(int index, com.google.cloud.discoveryengine.v1.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.add(index, value);
onChanged();
} else {
schemasBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder addSchemas(com.google.cloud.discoveryengine.v1.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(builderForValue.build());
onChanged();
} else {
schemasBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder addSchemas(
int index, com.google.cloud.discoveryengine.v1.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(index, builderForValue.build());
onChanged();
} else {
schemasBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder addAllSchemas(
java.lang.Iterable<? extends com.google.cloud.discoveryengine.v1.Schema> values) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, schemas_);
onChanged();
} else {
schemasBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder clearSchemas() {
if (schemasBuilder_ == null) {
schemas_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
schemasBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public Builder removeSchemas(int index) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.remove(index);
onChanged();
} else {
schemasBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1.Schema.Builder getSchemasBuilder(int index) {
return getSchemasFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1.SchemaOrBuilder getSchemasOrBuilder(int index) {
if (schemasBuilder_ == null) {
return schemas_.get(index);
} else {
return schemasBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public java.util.List<? extends com.google.cloud.discoveryengine.v1.SchemaOrBuilder>
getSchemasOrBuilderList() {
if (schemasBuilder_ != null) {
return schemasBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(schemas_);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1.Schema.Builder addSchemasBuilder() {
return getSchemasFieldBuilder()
.addBuilder(com.google.cloud.discoveryengine.v1.Schema.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1.Schema.Builder addSchemasBuilder(int index) {
return getSchemasFieldBuilder()
.addBuilder(index, com.google.cloud.discoveryengine.v1.Schema.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1.Schema schemas = 1;</code>
*/
public java.util.List<com.google.cloud.discoveryengine.v1.Schema.Builder>
getSchemasBuilderList() {
return getSchemasFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1.Schema,
com.google.cloud.discoveryengine.v1.Schema.Builder,
com.google.cloud.discoveryengine.v1.SchemaOrBuilder>
getSchemasFieldBuilder() {
if (schemasBuilder_ == null) {
schemasBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1.Schema,
com.google.cloud.discoveryengine.v1.Schema.Builder,
com.google.cloud.discoveryengine.v1.SchemaOrBuilder>(
schemas_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
schemas_ = null;
}
return schemasBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1.ListSchemasResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1.ListSchemasResponse)
private static final com.google.cloud.discoveryengine.v1.ListSchemasResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1.ListSchemasResponse();
}
public static com.google.cloud.discoveryengine.v1.ListSchemasResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSchemasResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSchemasResponse>() {
@java.lang.Override
public ListSchemasResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListSchemasResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSchemasResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1.ListSchemasResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/felix-dev | 37,551 | ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.ipojo.handlers.configuration;
import org.apache.felix.ipojo.*;
import org.apache.felix.ipojo.architecture.ComponentTypeDescription;
import org.apache.felix.ipojo.architecture.HandlerDescription;
import org.apache.felix.ipojo.architecture.PropertyDescription;
import org.apache.felix.ipojo.handlers.providedservice.ProvidedServiceHandler;
import org.apache.felix.ipojo.metadata.Attribute;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.parser.FieldMetadata;
import org.apache.felix.ipojo.parser.MethodMetadata;
import org.apache.felix.ipojo.parser.PojoMetadata;
import org.apache.felix.ipojo.util.Callback;
import org.apache.felix.ipojo.util.Log;
import org.apache.felix.ipojo.util.Property;
import org.apache.felix.ipojo.util.SecurityHelper;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ManagedService;
import java.util.*;
/**
* Handler managing the Configuration Admin.
*
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class ConfigurationHandler extends PrimitiveHandler implements ManagedService {
public static final String MANAGED_SERVICE_PID = "managed.service.pid";
/**
* List of the configurable fields.
*/
private List<Property> m_configurableProperties = new ArrayList<Property>(1);
/**
* ProvidedServiceHandler of the component. It is useful to propagate
* properties to service registrations.
*/
private ProvidedServiceHandler m_providedServiceHandler;
/**
* Properties propagated during the last instance "update".
*/
private Dictionary m_propagatedFromInstance = new Properties();
/**
* Properties to propagate.
*/
private Dictionary<String, Object> m_toPropagate = new Hashtable<String, Object>();
/**
* Properties propagated from the configuration admin.
*/
private Dictionary m_propagatedFromCA;
/**
* Check if the instance was already reconfigured by the configuration admin.
*/
private boolean m_configurationAlreadyPushed;
/**
* should the component propagate configuration ?
*/
private boolean m_mustPropagate;
/**
* Service Registration to publish the service registration.
*/
private ServiceRegistration m_sr;
/**
* Managed Service PID.
* This PID must be different from the instance name if the instance was created
* with the Configuration Admin.
*/
private String m_managedServicePID;
/**
* the handler description.
*/
private ConfigurationHandlerDescription m_description;
/**
* Updated method.
* This method is called when a reconfiguration is completed.
*/
private Callback m_updated;
/**
* The configuration listeners.
*/
private final Set<ConfigurationListener> m_listeners = new LinkedHashSet<ConfigurationListener>();
/**
* The last configuration sent to listeners.
*/
private Map<String, Object> m_lastConfiguration;
/**
* Initialize the component type.
*
* @param desc : component type description to populate.
* @param metadata : component type metadata.
* @throws ConfigurationException : metadata are incorrect.
* @see org.apache.felix.ipojo.Handler#initializeComponentFactory(org.apache.felix.ipojo.architecture.ComponentTypeDescription, org.apache.felix.ipojo.metadata.Element)
*/
public void initializeComponentFactory(ComponentTypeDescription desc, Element metadata) throws ConfigurationException {
Element[] confs = metadata.getElements("Properties", "");
if (confs == null) {
return;
}
Element[] configurables = confs[0].getElements("Property");
for (int i = 0; configurables != null && i < configurables.length; i++) {
String fieldName = configurables[i].getAttribute("field");
String methodName = configurables[i].getAttribute("method");
String paramIndex = configurables[i].getAttribute("constructor-parameter");
if (fieldName == null && methodName == null && paramIndex == null) {
throw new ConfigurationException("Malformed property : The property needs to contain" +
" at least a field, a method or a constructor-parameter");
}
String name = configurables[i].getAttribute("name");
if (name == null) {
if (fieldName == null && methodName != null) {
name = methodName;
} else if (fieldName == null && paramIndex != null) {
// Extract the name from the arguments.
MethodMetadata[] constructors = getFactory().getPojoMetadata().getConstructors();
if (constructors.length != 1) {
throw new ConfigurationException("Cannot infer the property name injected in the constructor " +
"parameter #" + paramIndex + " - add the `name` attribute");
} else {
int idx = Integer.valueOf(paramIndex);
if (constructors[0].getMethodArgumentNames().length > idx) {
name = constructors[0].getMethodArgumentNames()[idx];
} else {
throw new ConfigurationException("Cannot infer the property name injected in the constructor " +
"parameter #" + paramIndex + " - not enough argument in the constructor :" +
constructors[0].getArguments());
}
}
} else {
name = fieldName;
}
configurables[i].addAttribute(new Attribute("name", name)); // Add the type to avoid configure checking
}
String value = configurables[i].getAttribute("value");
// Detect the type of the property
PojoMetadata manipulation = getFactory().getPojoMetadata();
String type = null;
if (methodName != null) {
MethodMetadata[] method = manipulation.getMethods(methodName);
if (method.length == 0) {
type = configurables[i].getAttribute("type");
if (type == null) {
throw new ConfigurationException("Malformed property : The type of the property cannot be discovered, add a 'type' attribute");
}
} else {
if (method[0].getMethodArguments().length != 1) {
throw new ConfigurationException("Malformed property : The method " + methodName + " does not have one argument");
}
type = method[0].getMethodArguments()[0];
configurables[i].addAttribute(new Attribute("type", type)); // Add the type to avoid configure checking
}
} else if (fieldName != null) {
FieldMetadata field = manipulation.getField(fieldName);
if (field == null) {
throw new ConfigurationException("Malformed property : The field " + fieldName + " does not exist in the implementation class");
}
type = field.getFieldType();
configurables[i].addAttribute(new Attribute("type", type)); // Add the type to avoid configure checking
} else if (paramIndex != null) {
int index = Integer.parseInt(paramIndex);
type = configurables[i].getAttribute("type");
MethodMetadata[] cts = manipulation.getConstructors();
// If we don't have a type, try to get the first constructor and get the type of the parameter
// we the index 'index'.
if (type == null && cts.length > 0 && cts[0].getMethodArguments().length > index) {
type = cts[0].getMethodArguments()[index];
} else if (type == null) { // Applied only if type was not determined.
throw new ConfigurationException("Cannot determine the type of the property " + index +
", please use the type attribute");
}
configurables[i].addAttribute(new Attribute("type", type));
}
// Is the property set to immutable
boolean immutable = false;
String imm = configurables[i].getAttribute("immutable");
immutable = imm != null && imm.equalsIgnoreCase("true");
boolean mandatory = false;
String man = configurables[i].getAttribute("mandatory");
mandatory = man != null && man.equalsIgnoreCase("true");
PropertyDescription pd;
if (value == null) {
pd = new PropertyDescription(name, type, null, false); // Cannot be immutable if we have no value.
} else {
pd = new PropertyDescription(name, type, value, immutable);
}
if (mandatory) {
pd.setMandatory();
}
desc.addProperty(pd);
}
}
/**
* Configures the handler.
* Access to field does not require synchronization as this method is executed
* before any thread access to this object.
*
* @param metadata the metadata of the component
* @param configuration the instance configuration
* @throws ConfigurationException one property metadata is not correct
* @see org.apache.felix.ipojo.Handler#configure(org.apache.felix.ipojo.metadata.Element, java.util.Dictionary)
*/
public void configure(Element metadata, Dictionary configuration) throws ConfigurationException {
// Build the map
Element[] confs = metadata.getElements("Properties", "");
Element[] configurables = confs[0].getElements("Property");
// Check if the component is dynamically configurable
// Propagation enabled by default.
m_mustPropagate = true;
// We must create a copy as the Config Admin dictionary has some limitations
m_toPropagate = new Hashtable<String, Object>();
if (configuration != null) {
Enumeration keys = configuration.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
// To conform with 'Property Propagation 104.4.4 (Config Admin spec)',
// we don't propagate properties starting with .
if (!excluded(key)) {
m_toPropagate.put(key, configuration.get(key));
}
}
}
String propa = confs[0].getAttribute("propagation");
if (propa != null && propa.equalsIgnoreCase("false")) {
m_mustPropagate = false;
m_toPropagate = null;
}
// Check if the component support ConfigurationADmin reconfiguration
m_managedServicePID = confs[0].getAttribute("pid"); // Look inside the component type description
String instanceMSPID = (String) configuration.get(MANAGED_SERVICE_PID); // Look inside the instance configuration.
if (instanceMSPID != null) {
m_managedServicePID = instanceMSPID;
}
// updated method
String upd = confs[0].getAttribute("updated");
if (upd != null) {
MethodMetadata method = getPojoMetadata().getMethod(upd);
if (method == null) {
throw new ConfigurationException("The updated method is not found in the class "
+ getInstanceManager().getClassName());
} else if (method.getMethodArguments().length == 0) {
m_updated = new Callback(upd, new Class[0], false, getInstanceManager());
} else if (method.getMethodArguments().length == 1
&& method.getMethodArguments()[0].equals(Dictionary.class.getName())) {
m_updated = new Callback(upd, new Class[]{Dictionary.class}, false, getInstanceManager());
} else {
throw new ConfigurationException("The updated method is found in the class "
+ getInstanceManager().getClassName() + " must have either no argument or a Dictionary");
}
}
for (int i = 0; configurables != null && i < configurables.length; i++) {
String fieldName = configurables[i].getAttribute("field");
String methodName = configurables[i].getAttribute("method");
String paramIndex = configurables[i].getAttribute("constructor-parameter");
int index = -1;
String name = configurables[i].getAttribute("name"); // The initialize method has fixed the property name.
String value = configurables[i].getAttribute("value");
String type = configurables[i].getAttribute("type"); // The initialize method has fixed the property name.
Property prop;
if (paramIndex == null) {
prop = new Property(name, fieldName, methodName, value, type, getInstanceManager(), this);
} else {
index = Integer.parseInt(paramIndex);
prop = new Property(name, fieldName, methodName, index,
value, type, getInstanceManager(), this);
}
addProperty(prop);
// Check if the instance configuration contains value for the current property :
if (configuration.get(name) == null) {
if (fieldName != null && configuration.get(fieldName) != null) {
prop.setValue(configuration.get(fieldName));
}
} else {
prop.setValue(configuration.get(name));
}
if (fieldName != null) {
FieldMetadata field = new FieldMetadata(fieldName, type);
getInstanceManager().register(field, prop);
}
if (index != -1) {
getInstanceManager().register(index, prop);
}
}
m_description = new ConfigurationHandlerDescription(this, m_configurableProperties, m_managedServicePID);
}
/**
* Stop method.
* This method is synchronized to avoid the configuration admin pushing a configuration during the un-registration.
* Do nothing.
*
* @see org.apache.felix.ipojo.Handler#stop()
*/
public synchronized void stop() {
if (m_sr != null) {
m_sr.unregister();
m_sr = null;
}
m_lastConfiguration = Collections.emptyMap();
}
/**
* Start method.
* This method is synchronized to avoid the config admin pushing a configuration before ending the method.
* Propagate properties if the propagation is activated.
*
* @see org.apache.felix.ipojo.Handler#start()
*/
public synchronized void start() {
// Get the provided service handler :
m_providedServiceHandler = (ProvidedServiceHandler) getHandler(HandlerFactory.IPOJO_NAMESPACE + ":provides");
// Propagation
if (m_mustPropagate) {
for (Property prop : m_configurableProperties) {
if (prop.getValue() != Property.NO_VALUE && prop.getValue() != null) { // No injected value, or null
m_toPropagate.put(prop.getName(), prop.getValue());
}
}
// We cannot use the reconfigure method directly, as there are no real changes.
Properties extra = reconfigureProperties(m_toPropagate);
propagate(extra, m_propagatedFromInstance);
m_propagatedFromInstance = extra;
if (getInstanceManager().getPojoObjects() != null) {
try {
notifyUpdated(null);
} catch (Throwable e) {
error("Cannot call the updated method : " + e.getMessage(), e);
}
}
}
// Give initial values and reset the 'invoked' flag.
for (Property prop : m_configurableProperties) {
prop.reset(); // Clear the invoked flag.
if (prop.hasField() && prop.getValue() != Property.NO_VALUE && prop.getValue() != null) {
getInstanceManager().onSet(null, prop.getField(), prop.getValue());
}
}
if (m_managedServicePID != null && m_sr == null) {
Hashtable<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, m_managedServicePID);
props.put(Factory.INSTANCE_NAME_PROPERTY, getInstanceManager().getInstanceName());
props.put("factory.name", getInstanceManager().getFactory().getFactoryName());
// Security Check
if (SecurityHelper.hasPermissionToRegisterService(ManagedService.class.getName(),
getInstanceManager().getContext()) && SecurityHelper.canRegisterService
(getInstanceManager().getContext())) {
m_sr = getInstanceManager().getContext().registerService(ManagedService.class.getName(), this, props);
} else {
error("Cannot register the ManagedService - The bundle "
+ getInstanceManager().getContext().getBundle().getBundleId()
+ " does not have the permission to register the service");
}
}
}
/**
* Adds the given property metadata to the property metadata list.
*
* @param prop : property metadata to add
*/
protected void addProperty(Property prop) {
m_configurableProperties.add(prop);
}
/**
* Reconfigure the component instance.
* Check if the new configuration modifies the current configuration.
* Invokes the updated method if needed.
*
* @param configuration : the new configuration
* @see org.apache.felix.ipojo.Handler#reconfigure(java.util.Dictionary)
*/
public void reconfigure(Dictionary configuration) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
boolean changed = false;
synchronized (this) {
info(getInstanceManager().getInstanceName() + " is reconfiguring the properties : " + configuration);
// Is there any changes ?
changed = detectConfigurationChanges(configuration);
if (changed) {
Properties extra = reconfigureProperties(configuration);
propagate(extra, m_propagatedFromInstance);
m_propagatedFromInstance = extra;
if (getInstanceManager().getPojoObjects() != null) {
try {
notifyUpdated(null);
} catch (Throwable e) {
error("Cannot call the updated method : " + e.getMessage(), e);
}
}
// Make a snapshot of the current configuration
for (Property p : m_configurableProperties) {
map.put(p.getName(), p.getValue());
}
}
}
if (changed) {
notifyListeners(map);
}
}
private boolean detectConfigurationChanges(Dictionary configuration) {
Enumeration keysEnumeration = configuration.keys();
while (keysEnumeration.hasMoreElements()) {
String name = (String) keysEnumeration.nextElement();
Object value = configuration.get(name);
// Some properties are skipped
if (name.equals(Factory.INSTANCE_NAME_PROPERTY)
|| name.equals(Constants.SERVICE_PID)
|| name.equals(MANAGED_SERVICE_PID)) {
continue;
}
// Do we have a property.
Property p = getPropertyByName(name);
if (p != null) {
// Change detection based on the value.
if (p.getValue() == null) {
return true;
} else if (! p.getValue().equals(value)) {
return true;
}
} else {
// Was it propagated ?
if (m_propagatedFromCA != null) {
Object v = m_propagatedFromCA.get(name);
if (v == null || ! v.equals(value)) {
return true;
}
}
if (m_propagatedFromInstance != null) {
Object v = m_propagatedFromInstance.get(name);
if (v == null || ! v.equals(value)) {
return true;
}
}
}
}
// A propagated property may have been removed.
if (m_propagatedFromCA != null) {
Enumeration enumeration = m_propagatedFromCA.keys();
while (enumeration.hasMoreElements()) {
String k = (String) enumeration.nextElement();
if (configuration.get(k) == null) {
return true;
}
}
}
if (m_propagatedFromInstance != null) {
Enumeration enumeration = m_propagatedFromInstance.keys();
while (enumeration.hasMoreElements()) {
String k = (String) enumeration.nextElement();
if (configuration.get(k) == null) {
return true;
}
}
}
return false;
}
private Property getPropertyByName(String name) {
for (Property p : m_configurableProperties) {
if (p.getName().equals(name)) {
return p;
}
}
return null;
}
/**
* Reconfigured configuration properties and returns non matching properties.
* When called, it must hold the monitor lock.
*
* @param configuration : new configuration
* @return the properties that does not match with configuration properties
*/
private Properties reconfigureProperties(Dictionary configuration) {
Properties toPropagate = new Properties();
Enumeration keysEnumeration = configuration.keys();
while (keysEnumeration.hasMoreElements()) {
String name = (String) keysEnumeration.nextElement();
Object value = configuration.get(name);
boolean found = false;
// Check if the name is a configurable property
for (Property prop : m_configurableProperties) {
if (prop.getName().equals(name)) {
Object v = reconfigureProperty(prop, value);
found = true;
if (m_mustPropagate && ! excluded(name)) {
toPropagate.put(name, v);
}
break; // Exit the search loop
}
}
if (!found && m_mustPropagate && ! excluded(name)) {
toPropagate.put(name, value);
}
}
// Every removed configurable property gets reset to its default value
for (Property prop : m_configurableProperties) {
if (configuration.get(prop.getName()) == null) {
reconfigureProperty(prop, prop.getDefaultValue());
}
}
return toPropagate;
}
/**
* Checks whether the property with this given name must not be propagated.
* @param name the name of the property
* @return {@code true} if the property must not be propagated
*/
private boolean excluded(String name) {
return name.startsWith(".")
|| Factory.INSTANCE_NAME_PROPERTY.equals(name)
|| Factory.FACTORY_VERSION_PROPERTY.equals(name)
|| "factory.name".equals(name);
}
/**
* Reconfigures the given property with the given value.
* This methods handles {@link org.apache.felix.ipojo.InstanceManager#onSet(Object, String, Object)}
* call and the callback invocation.
* The reconfiguration occurs only if the value changes.
*
* @param prop the property object to reconfigure
* @param value the new value.
* @return the new property value
*/
public Object reconfigureProperty(Property prop, Object value) {
if (prop.getValue() == null || !prop.getValue().equals(value)) {
prop.setValue(value);
if (prop.hasField()) {
getInstanceManager().onSet(null, prop.getField(), prop.getValue()); // Notify other handler of the field value change.
}
if (prop.hasMethod()) {
if (getInstanceManager().getPojoObjects() != null) {
prop.invoke(null); // Call on all created pojo objects.
}
}
}
return prop.getValue();
}
/**
* Removes the old properties from the provided services and propagate new properties.
*
* @param newProps : new properties to propagate
* @param oldProps : old properties to remove
*/
private void propagate(Dictionary newProps, Dictionary oldProps) {
if (m_mustPropagate && m_providedServiceHandler != null) {
if (oldProps != null) {
m_providedServiceHandler.removeProperties(oldProps);
}
if (newProps != null) {
// Remove the name, the pid and the managed service pid props
newProps.remove(Factory.INSTANCE_NAME_PROPERTY);
newProps.remove(MANAGED_SERVICE_PID);
newProps.remove(Constants.SERVICE_PID);
// Remove all properties starting with . (config admin specification)
Enumeration<String> keys = newProps.keys();
List<String> propertiesStartingWithDot = new ArrayList<String>();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (key.startsWith(".")) {
propertiesStartingWithDot.add(key);
}
}
for (String k : propertiesStartingWithDot) {
newProps.remove(k);
}
// Propagation of the properties to service registrations :
m_providedServiceHandler.addProperties(newProps);
}
}
}
/**
* Handler createInstance method.
* This method is override to allow delayed callback invocation.
* Invokes the updated method if needed.
*
* @param instance : the created object
* @see org.apache.felix.ipojo.PrimitiveHandler#onCreation(Object)
*/
public void onCreation(Object instance) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
for (Property prop : m_configurableProperties) {
if (prop.hasMethod()) {
prop.invoke(instance);
}
// Fill the snapshot copy while calling callbacks
map.put(prop.getName(), prop.getValue());
}
try {
notifyUpdated(instance);
} catch (Throwable e) {
error("Cannot call the updated method : " + e.getMessage(), e);
}
notifyListeners(map);
}
/**
* Invokes the updated method.
* This method build the dictionary containing all valued properties,
* as well as properties propagated to the provided service handler (
* only if the propagation is enabled).
*
* @param instance the instance on which the callback must be called.
* If <code>null</code> the callback is called on all the existing
* object.
*/
private void notifyUpdated(Object instance) {
if (m_updated == null) {
return;
}
if (m_updated.getArguments().length == 0) {
// We don't have to compute the properties,
// we just call the callback.
try {
if (instance == null) {
m_updated.call(new Object[0]);
} else {
m_updated.call(instance, new Object[0]);
}
} catch (Exception e) {
error("Cannot call the updated method " + m_updated.getMethod() + " : " + e.getMessage());
}
return;
}
// Else we must compute the properties.
Properties props = new Properties();
for (Property property : m_configurableProperties) {
String n = property.getName();
Object v = property.getValue();
if (v != Property.NO_VALUE) {
props.put(n, v);
}
}
// add propagated properties to the list if propagation is enabled
if (m_mustPropagate) {
// Start by properties from the configuration admin,
if (m_propagatedFromCA != null) {
Enumeration e = m_propagatedFromCA.keys();
while (e.hasMoreElements()) {
String k = (String) e.nextElement();
if (!k.equals(Factory.INSTANCE_NAME_PROPERTY)) {
props.put(k, m_propagatedFromCA.get(k));
}
}
}
// Do also the one from the instance configuration
if (m_propagatedFromInstance != null) {
Enumeration e = m_propagatedFromInstance.keys();
while (e.hasMoreElements()) {
String k = (String) e.nextElement();
if (!k.equals(Factory.INSTANCE_NAME_PROPERTY)) { // Skip instance.name
props.put(k, m_propagatedFromInstance.get(k));
}
}
}
}
try {
if (instance == null) {
m_updated.call(new Object[]{props});
} else {
m_updated.call(instance, new Object[]{props});
}
} catch (Exception e) {
error("Cannot call the updated method " + m_updated.getMethod() + " : " + e.getMessage());
}
}
/**
* Managed Service method.
* This method is called when the instance is reconfigured by the ConfigurationAdmin.
* When called, it must hold the monitor lock.
*
* @param conf : pushed configuration.
* @throws org.osgi.service.cm.ConfigurationException
* the reconfiguration failed.
* @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
*/
public void updated(Dictionary conf) throws org.osgi.service.cm.ConfigurationException {
Map<String, Object> map = new LinkedHashMap<String, Object>();
synchronized (this) {
if (conf == null && !m_configurationAlreadyPushed) {
return; // First call
} else if (conf != null) { // Configuration push
Properties props = reconfigureProperties(conf);
propagate(props, m_propagatedFromCA);
m_propagatedFromCA = props;
m_configurationAlreadyPushed = true;
} else if (m_configurationAlreadyPushed) { // Configuration deletion
propagate(null, m_propagatedFromCA);
m_propagatedFromCA = null;
m_configurationAlreadyPushed = false;
}
if (getInstanceManager().getPojoObjects() != null) {
try {
notifyUpdated(null);
} catch (Throwable e) {
error("Cannot call the updated method : " + e.getMessage(), e);
}
}
// Make a snapshot of the current configuration
for (Property p : m_configurableProperties) {
map.put(p.getName(), p.getValue());
}
}
notifyListeners(map);
}
/**
* Gets the configuration handler description.
*
* @return the configuration handler description.
* @see org.apache.felix.ipojo.Handler#getDescription()
*/
public HandlerDescription getDescription() {
return m_description;
}
/**
* Add the given listener to the configuration handler's list of listeners.
*
* @param listener the {@code ConfigurationListener} object to be added
* @throws NullPointerException if {@code listener} is {@code null}
*/
public void addListener(ConfigurationListener listener) {
if (listener == null) {
throw new NullPointerException("null listener");
}
synchronized (m_listeners) {
m_listeners.add(listener);
}
}
/**
* Remove the given listener from the configuration handler's list of listeners.
* If the listeners is not registered, this method does nothing.
*
* @param listener the {@code ConfigurationListener} object to be removed
* @throws NullPointerException if {@code listener} is {@code null}
*/
public void removeListener(ConfigurationListener listener) {
if (listener == null) {
throw new NullPointerException("The list of listener is null");
}
synchronized (m_listeners) {
// We definitely cannot rely on listener's equals method...
// ...so we need to manually search for the listener, using ==.
ConfigurationListener found = null;
for (ConfigurationListener l : m_listeners) {
if (l == listener) {
found = l;
break;
}
}
if (found != null) {
m_listeners.remove(found);
}
}
}
/**
* Notify all listeners that a reconfiguration has occurred.
*
* @param map the new configuration of the component instance.
*/
private void notifyListeners(Map<String, Object> map) {
// Get a snapshot of the listeners
// and check if we had a change in the map.
List<ConfigurationListener> tmp;
synchronized (m_listeners) {
tmp = new ArrayList<ConfigurationListener>(m_listeners);
if (map == null) {
if (m_lastConfiguration == null) {
// No change.
return;
}
// Else trigger the change.
} else {
if (m_lastConfiguration != null && m_lastConfiguration.size() == map.size()) {
// Must compare key by key
boolean diff = false;
for (String k : map.keySet()) {
if (! map.get(k).equals(m_lastConfiguration.get(k))) {
// Difference found, break;
diff = true;
break;
}
}
if (! diff) {
// no difference found, skip notification
return;
}
}
// Else difference found, triggers the change
}
if (map == null) {
m_lastConfiguration = Collections.emptyMap();
} else {
m_lastConfiguration = Collections.unmodifiableMap(map);
}
}
if (! tmp.isEmpty()) {
getLogger().log(Log.DEBUG, String.format(
"[%s] Notifying configuration listener: %s", getInstanceManager().getInstanceName(), tmp));
}
// Protect the map.
// Do notify, outside any lock
for (ConfigurationListener l : tmp) {
try {
l.configurationChanged(getInstanceManager(), m_lastConfiguration);
} catch (Throwable e) {
// Failure inside a listener: put a warning on the logger, and continue
warn(String.format(
"[%s] A ConfigurationListener has failed: %s",
getInstanceManager().getInstanceName(),
e.getMessage())
, e);
}
}
}
@Override
public void stateChanged(int state) {
if (state == ComponentInstance.DISPOSED) {
// Clean up the list of listeners
synchronized (m_listeners) {
m_listeners.clear();
}
}
super.stateChanged(state);
}
}
|
apache/hive | 37,636 | accumulo-handler/src/test/org/apache/hadoop/hive/accumulo/mr/TestHiveAccumuloTypes.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.accumulo.mr;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.time.LocalDateTime;
import java.util.Map.Entry;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.accumulo.AccumuloHiveConstants;
import org.apache.hadoop.hive.accumulo.AccumuloHiveRow;
import org.apache.hadoop.hive.accumulo.serde.AccumuloSerDeParameters;
import org.apache.hadoop.hive.common.type.Date;
import org.apache.hadoop.hive.common.type.HiveChar;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.common.type.HiveVarchar;
import org.apache.hadoop.hive.common.type.Timestamp;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.ByteStream;
import org.apache.hadoop.hive.serde2.io.DateWritableV2;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritableV2;
import org.apache.hadoop.hive.serde2.lazy.ByteArrayRef;
import org.apache.hadoop.hive.serde2.lazy.LazyBoolean;
import org.apache.hadoop.hive.serde2.lazy.LazyByte;
import org.apache.hadoop.hive.serde2.lazy.LazyDate;
import org.apache.hadoop.hive.serde2.lazy.LazyDouble;
import org.apache.hadoop.hive.serde2.lazy.LazyFactory;
import org.apache.hadoop.hive.serde2.lazy.LazyFloat;
import org.apache.hadoop.hive.serde2.lazy.LazyHiveChar;
import org.apache.hadoop.hive.serde2.lazy.LazyHiveDecimal;
import org.apache.hadoop.hive.serde2.lazy.LazyHiveVarchar;
import org.apache.hadoop.hive.serde2.lazy.LazyInteger;
import org.apache.hadoop.hive.serde2.lazy.LazyLong;
import org.apache.hadoop.hive.serde2.lazy.LazyShort;
import org.apache.hadoop.hive.serde2.lazy.LazyString;
import org.apache.hadoop.hive.serde2.lazy.LazyTimestamp;
import org.apache.hadoop.hive.serde2.lazy.LazyUtils;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyBooleanObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyByteObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyDateObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyDoubleObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyFloatObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyHiveCharObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyHiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyHiveVarcharObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyIntObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyLongObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyPrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyShortObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyStringObjectInspector;
import org.apache.hadoop.hive.serde2.lazy.objectinspector.primitive.LazyTimestampObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaBooleanObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaByteObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaDateObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaDoubleObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaFloatObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaHiveCharObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaHiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaHiveVarcharObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaIntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaLongObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaShortObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaStringObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaTimestampObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
/**
*
*/
public class TestHiveAccumuloTypes {
@Rule
public TestName test = new TestName();
@Test
public void testBinaryTypes() throws Exception {
final String tableName = test.getMethodName(), user = "root", pass = "";
MockInstance mockInstance = new MockInstance(test.getMethodName());
Connector conn = mockInstance.getConnector(user, new PasswordToken(pass));
HiveAccumuloTableInputFormat inputformat = new HiveAccumuloTableInputFormat();
JobConf conf = new JobConf();
conf.set(AccumuloSerDeParameters.TABLE_NAME, tableName);
conf.set(AccumuloSerDeParameters.USE_MOCK_INSTANCE, "true");
conf.set(AccumuloSerDeParameters.INSTANCE_NAME, test.getMethodName());
conf.set(AccumuloSerDeParameters.USER_NAME, user);
conf.set(AccumuloSerDeParameters.USER_PASS, pass);
conf.set(AccumuloSerDeParameters.ZOOKEEPERS, "localhost:2181"); // not used for mock, but
// required by input format.
conf.set(AccumuloSerDeParameters.COLUMN_MAPPINGS, AccumuloHiveConstants.ROWID
+ ",cf:string,cf:boolean,cf:tinyint,cf:smallint,cf:int,cf:bigint"
+ ",cf:float,cf:double,cf:decimal,cf:date,cf:timestamp,cf:char,cf:varchar");
conf.set(
serdeConstants.LIST_COLUMNS,
"string,string,boolean,tinyint,smallint,int,bigint,float,double,decimal,date,timestamp,char(4),varchar(7)");
conf.set(
serdeConstants.LIST_COLUMN_TYPES,
"string,string,boolean,tinyint,smallint,int,bigint,float,double,decimal,date,timestamp,char(4),varchar(7)");
conf.set(AccumuloSerDeParameters.DEFAULT_STORAGE_TYPE, "binary");
conn.tableOperations().create(tableName);
BatchWriterConfig writerConf = new BatchWriterConfig();
BatchWriter writer = conn.createBatchWriter(tableName, writerConf);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
String cf = "cf";
byte[] cfBytes = cf.getBytes();
Mutation m = new Mutation("row1");
// string
String stringValue = "string";
JavaStringObjectInspector stringOI = (JavaStringObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.STRING_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, stringOI.create(stringValue), stringOI, false, (byte) 0,
null);
m.put(cfBytes, "string".getBytes(), baos.toByteArray());
// boolean
boolean booleanValue = true;
baos.reset();
JavaBooleanObjectInspector booleanOI = (JavaBooleanObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BOOLEAN_TYPE_NAME));
LazyUtils.writePrimitive(baos, booleanOI.create(booleanValue), booleanOI);
m.put(cfBytes, "boolean".getBytes(), baos.toByteArray());
// tinyint
byte tinyintValue = -127;
baos.reset();
JavaByteObjectInspector byteOI = (JavaByteObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.TINYINT_TYPE_NAME));
LazyUtils.writePrimitive(baos, tinyintValue, byteOI);
m.put(cfBytes, "tinyint".getBytes(), baos.toByteArray());
// smallint
short smallintValue = Short.MAX_VALUE;
baos.reset();
JavaShortObjectInspector shortOI = (JavaShortObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.SMALLINT_TYPE_NAME));
LazyUtils.writePrimitive(baos, smallintValue, shortOI);
m.put(cfBytes, "smallint".getBytes(), baos.toByteArray());
// int
int intValue = Integer.MAX_VALUE;
baos.reset();
JavaIntObjectInspector intOI = (JavaIntObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.INT_TYPE_NAME));
LazyUtils.writePrimitive(baos, intValue, intOI);
m.put(cfBytes, "int".getBytes(), baos.toByteArray());
// bigint
long bigintValue = Long.MAX_VALUE;
baos.reset();
JavaLongObjectInspector longOI = (JavaLongObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BIGINT_TYPE_NAME));
LazyUtils.writePrimitive(baos, bigintValue, longOI);
m.put(cfBytes, "bigint".getBytes(), baos.toByteArray());
// float
float floatValue = Float.MAX_VALUE;
baos.reset();
JavaFloatObjectInspector floatOI = (JavaFloatObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.FLOAT_TYPE_NAME));
LazyUtils.writePrimitive(baos, floatValue, floatOI);
m.put(cfBytes, "float".getBytes(), baos.toByteArray());
// double
double doubleValue = Double.MAX_VALUE;
baos.reset();
JavaDoubleObjectInspector doubleOI = (JavaDoubleObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.DOUBLE_TYPE_NAME));
LazyUtils.writePrimitive(baos, doubleValue, doubleOI);
m.put(cfBytes, "double".getBytes(), baos.toByteArray());
// decimal
baos.reset();
HiveDecimal decimalValue = HiveDecimal.create(65536l);
HiveDecimalWritable decimalWritable = new HiveDecimalWritable(decimalValue);
decimalWritable.write(out);
m.put(cfBytes, "decimal".getBytes(), baos.toByteArray());
// date
baos.reset();
Date now = Date.ofEpochMilli(System.currentTimeMillis());
DateWritableV2 dateWritable = new DateWritableV2(now);
Date dateValue = dateWritable.get();
dateWritable.write(out);
m.put(cfBytes, "date".getBytes(), baos.toByteArray());
// tiemestamp
baos.reset();
Timestamp timestampValue = Timestamp.ofEpochMilli(System.currentTimeMillis());
ByteStream.Output output = new ByteStream.Output();
TimestampWritableV2 timestampWritable = new TimestampWritableV2(timestampValue);
timestampWritable.write(new DataOutputStream(output));
output.close();
m.put(cfBytes, "timestamp".getBytes(), output.toByteArray());
// char
baos.reset();
HiveChar charValue = new HiveChar("char", 4);
JavaHiveCharObjectInspector charOI = (JavaHiveCharObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(new CharTypeInfo(4));
LazyUtils.writePrimitiveUTF8(baos, charOI.create(charValue), charOI, false, (byte) 0, null);
m.put(cfBytes, "char".getBytes(), baos.toByteArray());
baos.reset();
HiveVarchar varcharValue = new HiveVarchar("varchar", 7);
JavaHiveVarcharObjectInspector varcharOI = (JavaHiveVarcharObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(new VarcharTypeInfo(7));
LazyUtils.writePrimitiveUTF8(baos, varcharOI.create(varcharValue), varcharOI, false, (byte) 0,
null);
m.put(cfBytes, "varchar".getBytes(), baos.toByteArray());
writer.addMutation(m);
writer.close();
for (Entry<Key,Value> e : conn.createScanner(tableName, new Authorizations())) {
System.out.println(e);
}
// Create the RecordReader
FileInputFormat.addInputPath(conf, new Path("unused"));
InputSplit[] splits = inputformat.getSplits(conf, 0);
assertEquals(splits.length, 1);
RecordReader<Text,AccumuloHiveRow> reader = inputformat.getRecordReader(splits[0], conf, null);
Text key = reader.createKey();
AccumuloHiveRow value = reader.createValue();
reader.next(key, value);
Assert.assertEquals(13, value.getTuples().size());
ByteArrayRef byteRef = new ByteArrayRef();
// string
Text cfText = new Text(cf), cqHolder = new Text();
cqHolder.set("string");
byte[] valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyStringObjectInspector lazyStringOI = LazyPrimitiveObjectInspectorFactory
.getLazyStringObjectInspector(false, (byte) 0);
LazyString lazyString = (LazyString) LazyFactory.createLazyObject(lazyStringOI);
lazyString.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(stringValue, lazyString.getWritableObject().toString());
// boolean
cqHolder.set("boolean");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyBooleanObjectInspector lazyBooleanOI = (LazyBooleanObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BOOLEAN_TYPE_NAME));
LazyBoolean lazyBoolean = (LazyBoolean) LazyFactory
.createLazyPrimitiveBinaryClass(lazyBooleanOI);
lazyBoolean.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(booleanValue, lazyBoolean.getWritableObject().get());
// tinyint
cqHolder.set("tinyint");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyByteObjectInspector lazyByteOI = (LazyByteObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.TINYINT_TYPE_NAME));
LazyByte lazyByte = (LazyByte) LazyFactory.createLazyPrimitiveBinaryClass(lazyByteOI);
lazyByte.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(tinyintValue, lazyByte.getWritableObject().get());
// smallint
cqHolder.set("smallint");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyShortObjectInspector lazyShortOI = (LazyShortObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.SMALLINT_TYPE_NAME));
LazyShort lazyShort = (LazyShort) LazyFactory.createLazyPrimitiveBinaryClass(lazyShortOI);
lazyShort.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(smallintValue, lazyShort.getWritableObject().get());
// int
cqHolder.set("int");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyIntObjectInspector lazyIntOI = (LazyIntObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory.getPrimitiveTypeInfo(serdeConstants.INT_TYPE_NAME));
LazyInteger lazyInt = (LazyInteger) LazyFactory.createLazyPrimitiveBinaryClass(lazyIntOI);
lazyInt.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(intValue, lazyInt.getWritableObject().get());
// bigint
cqHolder.set("bigint");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyLongObjectInspector lazyLongOI = (LazyLongObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BIGINT_TYPE_NAME));
LazyLong lazyLong = (LazyLong) LazyFactory.createLazyPrimitiveBinaryClass(lazyLongOI);
lazyLong.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(bigintValue, lazyLong.getWritableObject().get());
// float
cqHolder.set("float");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyFloatObjectInspector lazyFloatOI = (LazyFloatObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.FLOAT_TYPE_NAME));
LazyFloat lazyFloat = (LazyFloat) LazyFactory.createLazyPrimitiveBinaryClass(lazyFloatOI);
lazyFloat.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(floatValue, lazyFloat.getWritableObject().get(), 0);
// double
cqHolder.set("double");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyDoubleObjectInspector lazyDoubleOI = (LazyDoubleObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.DOUBLE_TYPE_NAME));
LazyDouble lazyDouble = (LazyDouble) LazyFactory.createLazyPrimitiveBinaryClass(lazyDoubleOI);
lazyDouble.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(doubleValue, lazyDouble.getWritableObject().get(), 0);
// decimal
cqHolder.set("decimal");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
ByteArrayInputStream bais = new ByteArrayInputStream(valueBytes);
DataInputStream in = new DataInputStream(bais);
decimalWritable.readFields(in);
Assert.assertEquals(decimalValue, decimalWritable.getHiveDecimal());
// date
cqHolder.set("date");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
bais = new ByteArrayInputStream(valueBytes);
in = new DataInputStream(bais);
dateWritable.readFields(in);
Assert.assertEquals(dateValue, dateWritable.get());
// timestamp
cqHolder.set("timestamp");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
bais = new ByteArrayInputStream(valueBytes);
in = new DataInputStream(bais);
timestampWritable.readFields(in);
Assert.assertEquals(timestampValue, timestampWritable.getTimestamp());
// char
cqHolder.set("char");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyHiveCharObjectInspector lazyCharOI = (LazyHiveCharObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(new CharTypeInfo(4));
LazyHiveChar lazyChar = (LazyHiveChar) LazyFactory.createLazyObject(lazyCharOI);
lazyChar.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(charValue, lazyChar.getWritableObject().getHiveChar());
// varchar
cqHolder.set("varchar");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyHiveVarcharObjectInspector lazyVarcharOI = (LazyHiveVarcharObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(new VarcharTypeInfo(7));
LazyHiveVarchar lazyVarchar = (LazyHiveVarchar) LazyFactory.createLazyObject(lazyVarcharOI);
lazyVarchar.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(varcharValue.toString(), lazyVarchar.getWritableObject().getHiveVarchar()
.toString());
}
@Test
public void testUtf8Types() throws Exception {
final String tableName = test.getMethodName(), user = "root", pass = "";
MockInstance mockInstance = new MockInstance(test.getMethodName());
Connector conn = mockInstance.getConnector(user, new PasswordToken(pass));
HiveAccumuloTableInputFormat inputformat = new HiveAccumuloTableInputFormat();
JobConf conf = new JobConf();
conf.set(AccumuloSerDeParameters.TABLE_NAME, tableName);
conf.set(AccumuloSerDeParameters.USE_MOCK_INSTANCE, "true");
conf.set(AccumuloSerDeParameters.INSTANCE_NAME, test.getMethodName());
conf.set(AccumuloSerDeParameters.USER_NAME, user);
conf.set(AccumuloSerDeParameters.USER_PASS, pass);
conf.set(AccumuloSerDeParameters.ZOOKEEPERS, "localhost:2181"); // not used for mock, but
// required by input format.
conf.set(AccumuloSerDeParameters.COLUMN_MAPPINGS, AccumuloHiveConstants.ROWID
+ ",cf:string,cf:boolean,cf:tinyint,cf:smallint,cf:int,cf:bigint"
+ ",cf:float,cf:double,cf:decimal,cf:date,cf:timestamp,cf:char,cf:varchar");
conf.set(
serdeConstants.LIST_COLUMNS,
"string,string,boolean,tinyint,smallint,int,bigint,float,double,decimal,date,timestamp,char(4),varchar(7)");
conf.set(
serdeConstants.LIST_COLUMN_TYPES,
"string,string,boolean,tinyint,smallint,int,bigint,float,double,decimal,date,timestamp,char(4),varchar(7)");
conn.tableOperations().create(tableName);
BatchWriterConfig writerConf = new BatchWriterConfig();
BatchWriter writer = conn.createBatchWriter(tableName, writerConf);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String cf = "cf";
byte[] cfBytes = cf.getBytes();
ByteArrayRef byteRef = new ByteArrayRef();
Mutation m = new Mutation("row1");
// string
String stringValue = "string";
baos.reset();
JavaStringObjectInspector stringOI = (JavaStringObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.STRING_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, stringOI.create(stringValue), stringOI, false, (byte) 0,
null);
m.put(cfBytes, "string".getBytes(), baos.toByteArray());
// boolean
boolean booleanValue = true;
baos.reset();
JavaBooleanObjectInspector booleanOI = (JavaBooleanObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BOOLEAN_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, booleanOI.create(booleanValue), booleanOI, false, (byte) 0,
null);
m.put(cfBytes, "boolean".getBytes(), baos.toByteArray());
// tinyint
byte tinyintValue = -127;
baos.reset();
JavaByteObjectInspector byteOI = (JavaByteObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.TINYINT_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, tinyintValue, byteOI, false, (byte) 0, null);
m.put(cfBytes, "tinyint".getBytes(), baos.toByteArray());
// smallint
short smallintValue = Short.MAX_VALUE;
baos.reset();
JavaShortObjectInspector shortOI = (JavaShortObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.SMALLINT_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, smallintValue, shortOI, false, (byte) 0, null);
m.put(cfBytes, "smallint".getBytes(), baos.toByteArray());
// int
int intValue = Integer.MAX_VALUE;
baos.reset();
JavaIntObjectInspector intOI = (JavaIntObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.INT_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, intValue, intOI, false, (byte) 0, null);
m.put(cfBytes, "int".getBytes(), baos.toByteArray());
// bigint
long bigintValue = Long.MAX_VALUE;
baos.reset();
JavaLongObjectInspector longOI = (JavaLongObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BIGINT_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, bigintValue, longOI, false, (byte) 0, null);
m.put(cfBytes, "bigint".getBytes(), baos.toByteArray());
// float
float floatValue = Float.MAX_VALUE;
baos.reset();
JavaFloatObjectInspector floatOI = (JavaFloatObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.FLOAT_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, floatValue, floatOI, false, (byte) 0, null);
m.put(cfBytes, "float".getBytes(), baos.toByteArray());
// double
double doubleValue = Double.MAX_VALUE;
baos.reset();
JavaDoubleObjectInspector doubleOI = (JavaDoubleObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.DOUBLE_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, doubleValue, doubleOI, false, (byte) 0, null);
m.put(cfBytes, "double".getBytes(), baos.toByteArray());
// decimal
HiveDecimal decimalValue = HiveDecimal.create("1.23");
baos.reset();
JavaHiveDecimalObjectInspector decimalOI = (JavaHiveDecimalObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(new DecimalTypeInfo(5, 2));
LazyUtils.writePrimitiveUTF8(baos, decimalOI.create(decimalValue), decimalOI, false, (byte) 0,
null);
m.put(cfBytes, "decimal".getBytes(), baos.toByteArray());
// date
Date now = Date.ofEpochMilli(System.currentTimeMillis());
DateWritableV2 dateWritable = new DateWritableV2(now);
Date dateValue = dateWritable.get();
baos.reset();
JavaDateObjectInspector dateOI = (JavaDateObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.DATE_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, dateOI.create(dateValue), dateOI, false, (byte) 0, null);
m.put(cfBytes, "date".getBytes(), baos.toByteArray());
// timestamp
Timestamp timestampValue = Timestamp.valueOf(LocalDateTime.now().toString());
baos.reset();
JavaTimestampObjectInspector timestampOI = (JavaTimestampObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.TIMESTAMP_TYPE_NAME));
LazyUtils.writePrimitiveUTF8(baos, timestampOI.create(timestampValue), timestampOI, false,
(byte) 0, null);
m.put(cfBytes, "timestamp".getBytes(), baos.toByteArray());
// char
baos.reset();
HiveChar charValue = new HiveChar("char", 4);
JavaHiveCharObjectInspector charOI = (JavaHiveCharObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(new CharTypeInfo(4));
LazyUtils.writePrimitiveUTF8(baos, charOI.create(charValue), charOI, false, (byte) 0, null);
m.put(cfBytes, "char".getBytes(), baos.toByteArray());
// varchar
baos.reset();
HiveVarchar varcharValue = new HiveVarchar("varchar", 7);
JavaHiveVarcharObjectInspector varcharOI = (JavaHiveVarcharObjectInspector) PrimitiveObjectInspectorFactory
.getPrimitiveJavaObjectInspector(new VarcharTypeInfo(7));
LazyUtils.writePrimitiveUTF8(baos, varcharOI.create(varcharValue), varcharOI, false, (byte) 0,
null);
m.put(cfBytes, "varchar".getBytes(), baos.toByteArray());
writer.addMutation(m);
writer.close();
for (Entry<Key,Value> e : conn.createScanner(tableName, new Authorizations())) {
System.out.println(e);
}
// Create the RecordReader
FileInputFormat.addInputPath(conf, new Path("unused"));
InputSplit[] splits = inputformat.getSplits(conf, 0);
assertEquals(splits.length, 1);
RecordReader<Text,AccumuloHiveRow> reader = inputformat.getRecordReader(splits[0], conf, null);
Text key = reader.createKey();
AccumuloHiveRow value = reader.createValue();
reader.next(key, value);
Assert.assertEquals(13, value.getTuples().size());
// string
Text cfText = new Text(cf), cqHolder = new Text();
cqHolder.set("string");
byte[] valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyStringObjectInspector lazyStringOI = LazyPrimitiveObjectInspectorFactory
.getLazyStringObjectInspector(false, (byte) 0);
LazyString lazyString = (LazyString) LazyFactory.createLazyObject(lazyStringOI);
lazyString.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(new Text(stringValue), lazyString.getWritableObject());
// boolean
cqHolder.set("boolean");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyBooleanObjectInspector lazyBooleanOI = (LazyBooleanObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BOOLEAN_TYPE_NAME));
LazyBoolean lazyBoolean = (LazyBoolean) LazyFactory.createLazyObject(lazyBooleanOI);
lazyBoolean.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(booleanValue, lazyBoolean.getWritableObject().get());
// tinyint
cqHolder.set("tinyint");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyByteObjectInspector lazyByteOI = (LazyByteObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.TINYINT_TYPE_NAME));
LazyByte lazyByte = (LazyByte) LazyFactory.createLazyObject(lazyByteOI);
lazyByte.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(tinyintValue, lazyByte.getWritableObject().get());
// smallint
cqHolder.set("smallint");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyShortObjectInspector lazyShortOI = (LazyShortObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.SMALLINT_TYPE_NAME));
LazyShort lazyShort = (LazyShort) LazyFactory.createLazyObject(lazyShortOI);
lazyShort.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(smallintValue, lazyShort.getWritableObject().get());
// int
cqHolder.set("int");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyIntObjectInspector lazyIntOI = (LazyIntObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory.getPrimitiveTypeInfo(serdeConstants.INT_TYPE_NAME));
LazyInteger lazyInt = (LazyInteger) LazyFactory.createLazyObject(lazyIntOI);
lazyInt.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(intValue, lazyInt.getWritableObject().get());
// bigint
cqHolder.set("bigint");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyLongObjectInspector lazyLongOI = (LazyLongObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.BIGINT_TYPE_NAME));
LazyLong lazyLong = (LazyLong) LazyFactory.createLazyObject(lazyLongOI);
lazyLong.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(bigintValue, lazyLong.getWritableObject().get());
// float
cqHolder.set("float");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyFloatObjectInspector lazyFloatOI = (LazyFloatObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.FLOAT_TYPE_NAME));
LazyFloat lazyFloat = (LazyFloat) LazyFactory.createLazyObject(lazyFloatOI);
lazyFloat.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(floatValue, lazyFloat.getWritableObject().get(), 0);
// double
cqHolder.set("double");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyDoubleObjectInspector lazyDoubleOI = (LazyDoubleObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.DOUBLE_TYPE_NAME));
LazyDouble lazyDouble = (LazyDouble) LazyFactory.createLazyObject(lazyDoubleOI);
lazyDouble.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(doubleValue, lazyDouble.getWritableObject().get(), 0);
// decimal
cqHolder.set("decimal");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyHiveDecimalObjectInspector lazyDecimalOI = (LazyHiveDecimalObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(new DecimalTypeInfo(5, 2));
LazyHiveDecimal lazyDecimal = (LazyHiveDecimal) LazyFactory.createLazyObject(lazyDecimalOI);
lazyDecimal.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(decimalValue, lazyDecimal.getWritableObject().getHiveDecimal());
// date
cqHolder.set("date");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyDateObjectInspector lazyDateOI = (LazyDateObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory.getPrimitiveTypeInfo(serdeConstants.DATE_TYPE_NAME));
LazyDate lazyDate = (LazyDate) LazyFactory.createLazyObject(lazyDateOI);
lazyDate.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(dateValue, lazyDate.getWritableObject().get());
// timestamp
cqHolder.set("timestamp");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyTimestampObjectInspector lazyTimestampOI = (LazyTimestampObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(TypeInfoFactory
.getPrimitiveTypeInfo(serdeConstants.TIMESTAMP_TYPE_NAME));
LazyTimestamp lazyTimestamp = (LazyTimestamp) LazyFactory.createLazyObject(lazyTimestampOI);
lazyTimestamp.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(timestampValue, lazyTimestamp.getWritableObject().getTimestamp());
// char
cqHolder.set("char");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyHiveCharObjectInspector lazyCharOI = (LazyHiveCharObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(new CharTypeInfo(4));
LazyHiveChar lazyChar = (LazyHiveChar) LazyFactory.createLazyObject(lazyCharOI);
lazyChar.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(charValue, lazyChar.getWritableObject().getHiveChar());
// varchar
cqHolder.set("varchar");
valueBytes = value.getValue(cfText, cqHolder);
Assert.assertNotNull(valueBytes);
byteRef.setData(valueBytes);
LazyHiveVarcharObjectInspector lazyVarcharOI = (LazyHiveVarcharObjectInspector) LazyPrimitiveObjectInspectorFactory
.getLazyObjectInspector(new VarcharTypeInfo(7));
LazyHiveVarchar lazyVarchar = (LazyHiveVarchar) LazyFactory.createLazyObject(lazyVarcharOI);
lazyVarchar.init(byteRef, 0, valueBytes.length);
Assert.assertEquals(varcharValue.toString(), lazyVarchar.getWritableObject().getHiveVarchar()
.toString());
}
}
|
apache/struts | 37,156 | core/src/test/java/org/apache/struts2/ognl/SecurityMemberAccessTest.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.struts2.ognl;
import ognl.MemberAccess;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.struts2.TestBean;
import org.apache.struts2.config.ConfigurationException;
import org.apache.struts2.test.TestBean2;
import org.apache.struts2.util.Foo;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SecurityMemberAccessTest {
private Map context;
private FooBar target;
protected SecurityMemberAccess sma;
protected ProviderAllowlist mockedProviderAllowlist;
protected ThreadAllowlist mockedThreadAllowlist;
@Before
public void setUp() throws Exception {
context = new HashMap<>();
target = new FooBar();
mockedProviderAllowlist = mock(ProviderAllowlist.class);
mockedThreadAllowlist = mock(ThreadAllowlist.class);
assignNewSma(true);
}
protected void assignNewSma(boolean allowStaticFieldAccess) {
when(mockedProviderAllowlist.getProviderAllowlist()).thenReturn(new HashSet<>());
when(mockedThreadAllowlist.getAllowlist()).thenReturn(new HashSet<>());
assignNewSmaHelper();
sma.useAllowStaticFieldAccess(String.valueOf(allowStaticFieldAccess));
}
protected void assignNewSmaHelper() {
sma = new SecurityMemberAccess(mockedProviderAllowlist, mockedThreadAllowlist);
}
private <T> T reflectField(String fieldName) throws IllegalAccessException {
return reflectField(sma, fieldName);
}
public static <T> T reflectField(Object instance, String fieldName) throws IllegalAccessException {
return (T) FieldUtils.readField(instance, fieldName, true);
}
@Test
public void defaultExclusionList() throws Exception {
Set<String> excludedClasses = reflectField("excludedClasses");
assertThat(excludedClasses).containsExactly(Object.class.getName());
assignNewSma(false);
excludedClasses = reflectField("excludedClasses");
assertThat(excludedClasses).containsExactlyInAnyOrder(Object.class.getName(), Class.class.getName());
}
@Test
public void configurationCollectionsImmutable() throws Exception {
List<String> fields = Arrays.asList(
"excludedClasses",
"excludedPackageNames",
"excludedPackageNamePatterns",
"excludedPackageExemptClasses",
"allowlistClasses",
"allowlistPackageNames",
"excludeProperties",
"acceptProperties");
for (String field : fields) {
Collection<String> fieldVal = reflectField(field);
assertThrows(UnsupportedOperationException.class, () -> fieldVal.add("foo"));
if (!fieldVal.isEmpty()) {
String firstVal = fieldVal.iterator().next();
assertThrows(UnsupportedOperationException.class, () -> fieldVal.remove(firstVal));
assertThrows(UnsupportedOperationException.class, fieldVal::clear);
}
}
}
@Test
public void exclusionListsAreAdditive_classes() throws Exception {
Collection<String> fieldVal = reflectField("excludedClasses");
Set<String> existing = new HashSet<>(fieldVal);
Collection<String> newExcludedClasses = Arrays.asList(FooBar.class.getName(), String.class.getName());
sma.useExcludedClasses(String.join(",", newExcludedClasses));
existing.addAll(newExcludedClasses);
fieldVal = reflectField("excludedClasses");
assertThat(fieldVal).containsExactlyInAnyOrderElementsOf(existing);
}
@Test
public void exclusionListsAreAdditive_packages() throws Exception {
sma.useExcludedPackageNames(Foo.class.getPackage().getName());
Collection<String> fieldVal = reflectField("excludedPackageNames");
Set<String> existing = new HashSet<>(fieldVal);
Collection<String> newExcludedPackages = Arrays.asList(FooBar.class.getPackage().getName(), String.class.getPackage().getName());
sma.useExcludedPackageNames(String.join(",", newExcludedPackages));
existing.addAll(newExcludedPackages);
fieldVal = reflectField("excludedPackageNames");
assertThat(fieldVal).containsExactlyInAnyOrderElementsOf(existing);
}
@Test
public void useExcludedPackageNames() {
assertThrows(ConfigurationException.class, () -> sma.useExcludedPackageNames("java.lang\njava.awt"));
assertThrows(ConfigurationException.class, () -> sma.useExcludedPackageNames("java.lang\tjava.awt"));
ConfigurationException e = assertThrows(ConfigurationException.class, () -> sma.useExcludedPackageNames("java.lang java.awt"));
assertTrue(e.getMessage().contains("erroneous whitespace characters"));
}
@Test
public void useExcludedPackagePatterns() {
ConfigurationException e = assertThrows(ConfigurationException.class, () -> sma.useExcludedPackageNamePatterns("["));
assertTrue(e.getMessage().contains("invalid regex"));
}
@Test
public void testWithoutClassExclusion() throws Exception {
// given
String propertyName = "stringField";
Member member = FooBar.class.getMethod(formGetterName(propertyName));
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue(accessible);
}
@Test
public void testClassExclusion() throws Exception {
// given
String propertyName = "stringField";
Member member = FooBar.class.getDeclaredMethod(formGetterName(propertyName));
sma.useExcludedClasses(FooBar.class.getName());
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse(accessible);
}
@Test
public void testObjectClassExclusion() throws Exception {
// given
String propertyName = "toString";
Member member = FooBar.class.getMethod(propertyName);
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse("toString() from Object is accessible!!!", accessible);
}
@Test
public void testObjectOverwrittenMethodsExclusion() throws Exception {
// given
String propertyName = "hashCode";
Member member = FooBar.class.getMethod(propertyName);
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue("hashCode() from FooBar isn't accessible!!!", accessible);
}
@Test
public void testInterfaceInheritanceExclusion() throws Exception {
// given
String propertyName = "barLogic";
Member member = BarInterface.class.getMethod(propertyName);
sma.useExcludedClasses(BarInterface.class.getName());
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse("barLogic() from BarInterface is accessible!!!", accessible);
}
@Test
public void testMiddleOfInheritanceExclusion1() throws Exception {
// given
String propertyName = "fooLogic";
Member member = FooBar.class.getMethod(propertyName);
sma.useExcludedClasses(BarInterface.class.getName());
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue("fooLogic() from FooInterface isn't accessible!!!", accessible);
}
@Test
public void testMiddleOfInheritanceExclusion2() throws Exception {
// given
String propertyName = "barLogic";
Member member = BarInterface.class.getMethod(propertyName);
sma.useExcludedClasses(BarInterface.class.getName());
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse("barLogic() from BarInterface is accessible!!!", accessible);
}
@Test
public void testMiddleOfInheritanceExclusion3() throws Exception {
// given
String propertyName = "barLogic";
Member member = BarInterface.class.getMethod(propertyName);
sma.useExcludedClasses(FooInterface.class.getName());
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue("barLogic() from BarInterface isn't accessible!!!", accessible);
}
@Test
public void testPackageExclusion() throws Exception {
// given
sma.useExcludedPackageNamePatterns("^" + FooBar.class.getPackage().getName().replaceAll("\\.", "\\\\.") + ".*");
String propertyName = "stringField";
Member member = FooBar.class.getMethod(formGetterName(propertyName));
// when
boolean actual = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse("stringField is accessible!", actual);
}
@Test
public void testPackageExclusionExemption() throws Exception {
// given
sma.useExcludedPackageNamePatterns("^" + FooBar.class.getPackage().getName().replaceAll("\\.", "\\\\.") + ".*");
sma.useExcludedPackageExemptClasses(FooBar.class.getName());
String propertyName = "stringField";
Member member = FooBar.class.getMethod(formGetterName(propertyName));
// when
boolean actual = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue("stringField isn't accessible!", actual);
}
@Test
public void testPackageNameExclusion() throws Exception {
// given
sma.useExcludedPackageNames(FooBar.class.getPackage().getName());
String propertyName = "stringField";
Member member = FooBar.class.getMethod(formGetterName(propertyName));
// when
boolean actual = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse("stringField is accessible!", actual);
}
@Test
public void testPackageNameExclusionExemption() throws Exception {
// given
sma.useExcludedPackageNames(FooBar.class.getPackage().getName());
sma.useExcludedPackageExemptClasses(FooBar.class.getName());
String propertyName = "stringField";
Member member = FooBar.class.getMethod(formGetterName(propertyName));
// when
boolean actual = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue("stringField isn't accessible!", actual);
}
@Test
public void testPackageNameExclusionExemption2() throws Exception {
// given
sma.useExcludedPackageNames(FooBar.class.getPackage().getName());
// Exemption must exist for both classes (target and member) if they both match a banned package
sma.useExcludedPackageExemptClasses(BarInterface.class.getName());
String propertyName = "barLogic";
Member member = BarInterface.class.getMethod(propertyName);
// when
boolean actual = sma.isAccessible(context, target, member, propertyName);
// then
assertFalse("barLogic is accessible!", actual);
}
@Test
public void testPackageNameExclusionExemption3() throws Exception {
// given
sma.useExcludedPackageNames(FooBar.class.getPackage().getName());
// Exemption must exist for both classes (target and member) if they both match a banned package
sma.useExcludedPackageExemptClasses(String.join(",", BarInterface.class.getName(), FooBar.class.getName()));
String propertyName = "barLogic";
Member member = BarInterface.class.getMethod(propertyName);
// when
boolean actual = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue("barLogic isn't accessible!", actual);
}
@Test
public void testDefaultPackageExclusion() throws Exception {
// given
sma.useExcludedPackageNamePatterns("^" + FooBar.class.getPackage().getName().replaceAll("\\.", "\\\\.") + ".*");
Class<?> clazz = Class.forName("PackagelessAction");
// when
boolean actual = sma.isPackageExcluded(clazz);
// then
assertFalse("default package is excluded!", actual);
}
@Test
public void testDefaultPackageExclusionSetting() throws Exception {
sma.useDisallowDefaultPackageAccess(Boolean.TRUE.toString());
Class<?> clazz = Class.forName("PackagelessAction");
boolean actual = sma.isAccessible(null, clazz.getConstructor().newInstance(), clazz.getMethod("execute"), null);
assertFalse("default package isn't excluded!", actual);
}
@Test
public void testDefaultPackageExclusion2() throws Exception {
// given
sma.useExcludedPackageNamePatterns("^$");
Class<?> clazz = Class.forName("PackagelessAction");
// when
boolean actual = sma.isPackageExcluded(clazz);
// then
assertTrue("default package isn't excluded!", actual);
}
@Test
public void testAccessEnum() throws Exception {
// when
Member values = MyValues.class.getMethod("values");
boolean actual = sma.isAccessible(context, MyValues.class, values, null);
// then
assertFalse("Access to enums is allowed!", actual);
}
@Test
public void testAccessEnum_alternateValues() throws Exception {
// when
Member alternateValues = MyValues.class.getMethod("values", String.class);
boolean actual = sma.isAccessible(context, MyValues.class, alternateValues, null);
// then
assertFalse("Access to unrelated #values method not blocked!", actual);
}
@Test
public void testAccessStaticMethod() throws Exception {
// given
sma.useExcludedClasses(Class.class.getName());
// when
Member method = StaticTester.class.getMethod("sayHello");
boolean actual = sma.isAccessible(context, StaticTester.class, method, null);
// then
assertFalse("Access to static method is not blocked!", actual);
}
@Test
public void testAccessStaticField() throws Exception {
// given
sma.useExcludedClasses(Class.class.getName());
// when
Member method = StaticTester.class.getField("MAX_VALUE");
boolean actual = sma.isAccessible(context, null, method, null);
// then
assertTrue("Access to static field is blocked!", actual);
}
@Test
public void testBlockedStaticFieldWhenFlagIsTrue() throws Exception {
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
Member method = StaticTester.class.getField("MAX_VALUE");
boolean actual = sma.isAccessible(context, null, method, null);
// then
assertTrue("Access to public static field is blocked?", actual);
// public static final test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.class.getField("MIN_VALUE");
actual = sma.isAccessible(context, null, method, null);
// then
assertTrue("Access to public final static field is blocked?", actual);
// package static test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.getFieldByName("PACKAGE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to package static field is allowed?", actual);
// package final static test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.getFieldByName("FINAL_PACKAGE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to package final static field is allowed?", actual);
// protected static test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.getFieldByName("PROTECTED_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to protected static field is allowed?", actual);
// protected final static test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.getFieldByName("FINAL_PROTECTED_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to protected final static field is allowed?", actual);
// private static test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.getFieldByName("PRIVATE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to private static field is allowed?", actual);
// private final static test
// given
assignNewSma(true);
sma.useExcludedClasses(Class.class.getName());
// when
method = StaticTester.getFieldByName("FINAL_PRIVATE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to private final static field is allowed?", actual);
}
@Test
public void testBlockedStaticFieldWhenFlagIsFalse() throws Exception {
// given
assignNewSma(false);
// when
Member method = StaticTester.class.getField("MAX_VALUE");
boolean actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to public static field is allowed when flag false?", actual);
// public static final test
// given
assignNewSma(false);
// when
method = StaticTester.class.getField("MIN_VALUE");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to public final static field is allowed when flag is false?", actual);
// package static test
// given
assignNewSma(false);
// when
method = StaticTester.getFieldByName("PACKAGE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to package static field is allowed?", actual);
// package final static test
// given
assignNewSma(false);
// when
method = StaticTester.getFieldByName("FINAL_PACKAGE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to package final static field is allowed?", actual);
// protected static test
// given
assignNewSma(false);
// when
method = StaticTester.getFieldByName("PROTECTED_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to protected static field is allowed?", actual);
// protected final static test
// given
assignNewSma(false);
// when
method = StaticTester.getFieldByName("FINAL_PROTECTED_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to protected final static field is allowed?", actual);
// private static test
// given
assignNewSma(false);
// when
method = StaticTester.getFieldByName("PRIVATE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to private static field is allowed?", actual);
// private final static test
// given
assignNewSma(false);
// when
method = StaticTester.getFieldByName("FINAL_PRIVATE_STRING");
actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to private final static field is allowed?", actual);
}
@Test
public void testBlockedStaticFieldWhenClassIsExcluded() throws Exception {
// given
sma.useExcludedClasses(String.join(",", Class.class.getName(), StaticTester.class.getName()));
// when
Member method = StaticTester.class.getField("MAX_VALUE");
boolean actual = sma.isAccessible(context, null, method, null);
// then
assertFalse("Access to static field isn't blocked!", actual);
}
@Test
public void testBlockStaticMethodAccess() throws Exception {
// given
sma.useExcludedClasses(Class.class.getName());
// when
Member method = StaticTester.class.getMethod("sayHello");
boolean actual = sma.isAccessible(context, StaticTester.class, method, null);
// then
assertFalse("Access to static isn't blocked!", actual);
}
@Test
public void testBlockAccessIfClassIsExcluded() throws Exception {
// given
sma.useExcludedClasses(Class.class.getName());
// when
Member method = Class.class.getMethod("getClassLoader");
boolean actual = sma.isAccessible(context, Class.class, method, null);
// then
assertFalse("Access to method of excluded class isn't blocked!", actual);
}
@Test
public void testBlockAccessIfClassIsExcluded_2() throws Exception {
// given
sma.useExcludedClasses(ClassLoader.class.getName());
// when
Member method = ClassLoader.class.getMethod("loadClass", String.class);
ClassLoader classLoaderTarget = this.getClass().getClassLoader();
boolean actual = sma.isAccessible(context, classLoaderTarget, method, null);
// then
assertFalse("Invalid test! Access to method of excluded class isn't blocked!", actual);
}
@Test
public void testAllowAccessIfClassIsNotExcluded() throws Exception {
// given
sma.useExcludedClasses(ClassLoader.class.getName());
// when
Member method = Class.class.getMethod("getClassLoader");
boolean actual = sma.isAccessible(context, Class.class, method, null);
// then
assertTrue("Invalid test! Access to method of non-excluded class is blocked!", actual);
}
@Test
public void testIllegalArgumentExceptionExpectedForTargetMemberMismatch() throws Exception {
// given
sma.useExcludedClasses(Class.class.getName());
// when
Member method = ClassLoader.class.getMethod("loadClass", String.class);
String mismatchTarget = "misMatchTargetObject";
try {
boolean actual = sma.isAccessible(context, mismatchTarget, method, null);
// then
assertFalse("Invalid test! Access to method of excluded class isn't blocked!", actual);
fail("Mismatch between target and member did not cause IllegalArgumentException?");
} catch (IllegalArgumentException iex) {
// Expected result is this exception
}
}
@Test
public void testAccessPrimitiveInt() throws Exception {
// given
sma.useExcludedPackageNames("java.lang.,ognl,javax");
String propertyName = "intField";
Member member = FooBar.class.getMethod(formGetterName(propertyName));
// when
boolean accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue(accessible);
}
@Test
public void testAccessPrimitiveDoubleWithNames() throws Exception {
// given
sma.useExcludedPackageNames("ognl.,javax.");
Set<String> excluded = new HashSet<>();
excluded.add(Object.class.getName());
excluded.add(Runtime.class.getName());
excluded.add(System.class.getName());
excluded.add(Class.class.getName());
excluded.add(ClassLoader.class.getName());
sma.useExcludedClasses(String.join(",", excluded));
String propertyName = "doubleValue";
double myDouble = 1;
Member member = Double.class.getMethod(propertyName);
// when
boolean accessible = sma.isAccessible(context, myDouble, member, propertyName);
// then
assertTrue(accessible);
// given
propertyName = "exit";
member = System.class.getMethod(propertyName, int.class);
// when
accessible = sma.isAccessible(context, System.class, member, propertyName);
// then
assertFalse(accessible);
// given
propertyName = "intField";
member = FooBar.class.getMethod(formGetterName(propertyName));
// when
accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue(accessible);
// given
propertyName = "doubleField";
member = FooBar.class.getMethod(formGetterName(propertyName));
// when
accessible = sma.isAccessible(context, target, member, propertyName);
// then
assertTrue(accessible);
}
@Test
public void testAccessPrimitiveDoubleWithPackageRegExs() throws Exception {
// given
sma.useExcludedPackageNamePatterns("^java\\.lang\\..*");
String propertyName = "doubleValue";
double myDouble = 1;
Member member = Double.class.getMethod(propertyName);
// when
boolean accessible = sma.isAccessible(context, myDouble, member, propertyName);
// then
assertTrue(accessible);
}
@Test
public void testAccessMemberAccessIsAccessible() throws Exception {
// given
sma.useExcludedClasses(MemberAccess.class.getName());
String propertyName = "excludedClasses";
String setter = "useExcludedClasses";
Member member = SecurityMemberAccess.class.getMethod(setter, String.class);
// when
boolean accessible = sma.isAccessible(context, sma, member, propertyName);
// then
assertTrue(accessible);
}
@Test
public void testAccessMemberAccessIsBlocked() throws Exception {
// given
sma.useExcludedClasses(SecurityMemberAccess.class.getName());
String propertyName = "excludedClasses";
String setter = "useExcludedClasses";
Member member = SecurityMemberAccess.class.getMethod(setter, String.class);
// when
boolean accessible = sma.isAccessible(context, sma, member, propertyName);
// then
assertFalse(accessible);
}
@Test
public void testPackageNameExclusionAsCommaDelimited() {
// given
sma.useExcludedPackageNames("java.lang");
// when
boolean actual = sma.isPackageExcluded(String.class);
// then
assertTrue("package java.lang. is accessible!", actual);
}
/**
* Test that the allowlist is enforced correctly for classes.
*/
@Test
public void classInclusion() throws Exception {
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
TestBean2 bean = new TestBean2();
Method method = TestBean2.class.getMethod("getData");
assertFalse(sma.checkAllowlist(bean, method));
sma.useAllowlistClasses(TestBean2.class.getName());
assertTrue(sma.checkAllowlist(bean, method));
}
/**
* Test that the allowlist is enforced correctly for packages.
*/
@Test
public void packageInclusion() throws Exception {
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
TestBean2 bean = new TestBean2();
Method method = TestBean2.class.getMethod("getData");
assertFalse(sma.checkAllowlist(bean, method));
sma.useAllowlistPackageNames(TestBean2.class.getPackage().getName());
assertTrue(sma.checkAllowlist(bean, method));
}
/**
* Test that the allowlist doesn't allow inherited methods unless the declaring class is also allowlisted.
*/
@Test
public void classInclusion_subclass() throws Exception {
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
sma.useAllowlistClasses(TestBean2.class.getName());
TestBean2 bean = new TestBean2();
Method method = TestBean2.class.getMethod("getName");
assertFalse(sma.checkAllowlist(bean, method));
}
/**
* Test that the allowlist allows inherited methods when both the target and declaring class are allowlisted.
*/
@Test
public void classInclusion_subclass_both() throws Exception {
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
sma.useAllowlistClasses(String.join(",", TestBean.class.getName(), TestBean2.class.getName()));
TestBean2 bean = new TestBean2();
Method method = TestBean2.class.getMethod("getName");
assertTrue(sma.checkAllowlist(bean, method));
}
/**
* Test that the allowlist doesn't allow inherited methods unless the package of the declaring class is also
* allowlisted.
*/
@Test
public void packageInclusion_subclass() throws Exception {
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
sma.useAllowlistPackageNames(TestBean2.class.getPackage().getName());
TestBean2 bean = new TestBean2();
Method method = TestBean2.class.getMethod("getName");
assertFalse(sma.checkAllowlist(bean, method));
}
/**
* When the allowlist is enabled and proxy object access is disallowed, Hibernate proxies should not be allowed.
*/
@Test
public void classInclusion_hibernateProxy_disallowProxyObjectAccess() throws Exception {
FooBarInterface proxyObject = mockHibernateProxy(new FooBar(), FooBarInterface.class);
Method proxyMethod = proxyObject.getClass().getMethod("fooLogic");
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
sma.useDisallowProxyObjectAccess(Boolean.TRUE.toString());
sma.useAllowlistClasses(FooBar.class.getName());
assertFalse(sma.checkAllowlist(proxyObject, proxyMethod));
}
/**
* When the allowlist is enabled and proxy object access is allowed, Hibernate proxies should be allowlisted based
* on their underlying target object. Class allowlisting should work as expected.
*/
@Test
public void classInclusion_hibernateProxy_allowProxyObjectAccess() throws Exception {
FooBarInterface proxyObject = mockHibernateProxy(new FooBar(), FooBarInterface.class);
Method proxyMethod = proxyObject.getClass().getMethod("fooLogic");
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
sma.useDisallowProxyObjectAccess(Boolean.FALSE.toString());
sma.useAllowlistClasses(FooBar.class.getName());
assertTrue(sma.checkAllowlist(proxyObject, proxyMethod));
}
@Test
public void packageInclusion_subclass_both() throws Exception {
sma.useEnforceAllowlistEnabled(Boolean.TRUE.toString());
sma.useAllowlistPackageNames(String.join(",",
TestBean.class.getPackage().getName(),
TestBean2.class.getPackage().getName()));
TestBean2 bean = new TestBean2();
Method method = TestBean2.class.getMethod("getName");
assertTrue(sma.checkAllowlist(bean, method));
}
private static String formGetterName(String propertyName) {
return "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
}
@SuppressWarnings("unchecked")
private static <T> T mockHibernateProxy(T originalObject, Class<T> proxyInterface) {
return (T) Proxy.newProxyInstance(
proxyInterface.getClassLoader(),
new Class<?>[]{proxyInterface, HibernateProxy.class},
new DummyHibernateProxyHandler(originalObject)
);
}
}
class FooBar implements FooBarInterface {
private String stringField;
private int intField;
private Double doubleField;
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
@Override
public String fooLogic() {
return "fooLogic";
}
@Override
public String barLogic() {
return "barLogic";
}
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final FooBar other = (FooBar) obj;
if (this.intField != other.intField) {
return false;
}
if (!Objects.equals(this.stringField, other.stringField)) {
return false;
}
return Objects.equals(this.doubleField, other.doubleField);
}
public int getIntField() {
return intField;
}
public void setIntField(int intField) {
this.intField = intField;
}
public Double getDoubleField() {
return doubleField;
}
public void setDoubleField(Double doubleField) {
this.doubleField = doubleField;
}
}
interface FooInterface {
String fooLogic();
}
interface BarInterface {
String barLogic();
}
interface FooBarInterface extends FooInterface, BarInterface {
}
enum MyValues {
ONE, TWO, THREE;
public static MyValues[] values(String notUsed) {
return new MyValues[] {ONE, TWO, THREE};
}
}
class StaticTester {
public static int MAX_VALUE = 0;
public static final int MIN_VALUE = 0;
static String PACKAGE_STRING = "package_string";
static final String FINAL_PACKAGE_STRING = "final_package_string";
static String PROTECTED_STRING = "protected_string";
static final String FINAL_PROTECTED_STRING = "final_protected_string";
static String PRIVATE_STRING = "private_string";
static final String FINAL_PRIVATE_STRING = "final_private_string";
public static String sayHello() {
return "Hello";
}
protected static Field getFieldByName(String fieldName) throws NoSuchFieldException {
if (fieldName != null && !fieldName.isEmpty()) {
return StaticTester.class.getDeclaredField(fieldName);
} else {
throw new NoSuchFieldException("field: " + fieldName + " does not exist");
}
}
}
class DummyHibernateProxyHandler implements InvocationHandler {
private final Object instance;
public DummyHibernateProxyHandler(Object instance) {
this.instance = instance;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (HibernateProxy.class.getMethod("getHibernateLazyInitializer").equals(method)) {
LazyInitializer initializer = mock(LazyInitializer.class);
when(initializer.getImplementation()).thenReturn(instance);
return initializer;
}
return method.invoke(instance, args);
}
}
|
googleads/googleads-java-lib | 37,566 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202411/LineItemCreativeAssociation.java | // Copyright 2024 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.
/**
* LineItemCreativeAssociation.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202411;
/**
* A {@code LineItemCreativeAssociation} associates a {@link Creative}
* or {@link CreativeSet} with a
* {@link LineItem} so that the creative can be served in
* ad units targeted by the line item.
*/
public class LineItemCreativeAssociation implements java.io.Serializable {
/* The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required. */
private java.lang.Long lineItemId;
/* The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}. */
private java.lang.Long creativeId;
/* The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set. */
private java.lang.Long creativeSetId;
/* The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10. */
private java.lang.Double manualCreativeRotationWeight;
/* The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1. */
private java.lang.Integer sequentialCreativeRotationIndex;
/* Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used. */
private com.google.api.ads.admanager.axis.v202411.DateTime startDateTime;
/* Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}. */
private com.google.api.ads.admanager.axis.v202411.StartDateTimeType startDateTimeType;
/* Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used. */
private com.google.api.ads.admanager.axis.v202411.DateTime endDateTime;
/* Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks. */
private java.lang.String destinationUrl;
/* Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional. */
private com.google.api.ads.admanager.axis.v202411.Size[] sizes;
/* The status of the association. This attribute is read-only. */
private com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStatus status;
/* Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet. */
private com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStats stats;
/* The date and time this association was last modified. */
private com.google.api.ads.admanager.axis.v202411.DateTime lastModifiedDateTime;
/* Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}. */
private java.lang.String targetingName;
public LineItemCreativeAssociation() {
}
public LineItemCreativeAssociation(
java.lang.Long lineItemId,
java.lang.Long creativeId,
java.lang.Long creativeSetId,
java.lang.Double manualCreativeRotationWeight,
java.lang.Integer sequentialCreativeRotationIndex,
com.google.api.ads.admanager.axis.v202411.DateTime startDateTime,
com.google.api.ads.admanager.axis.v202411.StartDateTimeType startDateTimeType,
com.google.api.ads.admanager.axis.v202411.DateTime endDateTime,
java.lang.String destinationUrl,
com.google.api.ads.admanager.axis.v202411.Size[] sizes,
com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStatus status,
com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStats stats,
com.google.api.ads.admanager.axis.v202411.DateTime lastModifiedDateTime,
java.lang.String targetingName) {
this.lineItemId = lineItemId;
this.creativeId = creativeId;
this.creativeSetId = creativeSetId;
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
this.startDateTime = startDateTime;
this.startDateTimeType = startDateTimeType;
this.endDateTime = endDateTime;
this.destinationUrl = destinationUrl;
this.sizes = sizes;
this.status = status;
this.stats = stats;
this.lastModifiedDateTime = lastModifiedDateTime;
this.targetingName = targetingName;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("creativeId", getCreativeId())
.add("creativeSetId", getCreativeSetId())
.add("destinationUrl", getDestinationUrl())
.add("endDateTime", getEndDateTime())
.add("lastModifiedDateTime", getLastModifiedDateTime())
.add("lineItemId", getLineItemId())
.add("manualCreativeRotationWeight", getManualCreativeRotationWeight())
.add("sequentialCreativeRotationIndex", getSequentialCreativeRotationIndex())
.add("sizes", getSizes())
.add("startDateTime", getStartDateTime())
.add("startDateTimeType", getStartDateTimeType())
.add("stats", getStats())
.add("status", getStatus())
.add("targetingName", getTargetingName())
.toString();
}
/**
* Gets the lineItemId value for this LineItemCreativeAssociation.
*
* @return lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public java.lang.Long getLineItemId() {
return lineItemId;
}
/**
* Sets the lineItemId value for this LineItemCreativeAssociation.
*
* @param lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public void setLineItemId(java.lang.Long lineItemId) {
this.lineItemId = lineItemId;
}
/**
* Gets the creativeId value for this LineItemCreativeAssociation.
*
* @return creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public java.lang.Long getCreativeId() {
return creativeId;
}
/**
* Sets the creativeId value for this LineItemCreativeAssociation.
*
* @param creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public void setCreativeId(java.lang.Long creativeId) {
this.creativeId = creativeId;
}
/**
* Gets the creativeSetId value for this LineItemCreativeAssociation.
*
* @return creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public java.lang.Long getCreativeSetId() {
return creativeSetId;
}
/**
* Sets the creativeSetId value for this LineItemCreativeAssociation.
*
* @param creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public void setCreativeSetId(java.lang.Long creativeSetId) {
this.creativeSetId = creativeSetId;
}
/**
* Gets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @return manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public java.lang.Double getManualCreativeRotationWeight() {
return manualCreativeRotationWeight;
}
/**
* Sets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @param manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public void setManualCreativeRotationWeight(java.lang.Double manualCreativeRotationWeight) {
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
}
/**
* Gets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @return sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public java.lang.Integer getSequentialCreativeRotationIndex() {
return sequentialCreativeRotationIndex;
}
/**
* Sets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @param sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public void setSequentialCreativeRotationIndex(java.lang.Integer sequentialCreativeRotationIndex) {
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
}
/**
* Gets the startDateTime value for this LineItemCreativeAssociation.
*
* @return startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public com.google.api.ads.admanager.axis.v202411.DateTime getStartDateTime() {
return startDateTime;
}
/**
* Sets the startDateTime value for this LineItemCreativeAssociation.
*
* @param startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public void setStartDateTime(com.google.api.ads.admanager.axis.v202411.DateTime startDateTime) {
this.startDateTime = startDateTime;
}
/**
* Gets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @return startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public com.google.api.ads.admanager.axis.v202411.StartDateTimeType getStartDateTimeType() {
return startDateTimeType;
}
/**
* Sets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @param startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public void setStartDateTimeType(com.google.api.ads.admanager.axis.v202411.StartDateTimeType startDateTimeType) {
this.startDateTimeType = startDateTimeType;
}
/**
* Gets the endDateTime value for this LineItemCreativeAssociation.
*
* @return endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public com.google.api.ads.admanager.axis.v202411.DateTime getEndDateTime() {
return endDateTime;
}
/**
* Sets the endDateTime value for this LineItemCreativeAssociation.
*
* @param endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public void setEndDateTime(com.google.api.ads.admanager.axis.v202411.DateTime endDateTime) {
this.endDateTime = endDateTime;
}
/**
* Gets the destinationUrl value for this LineItemCreativeAssociation.
*
* @return destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public java.lang.String getDestinationUrl() {
return destinationUrl;
}
/**
* Sets the destinationUrl value for this LineItemCreativeAssociation.
*
* @param destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public void setDestinationUrl(java.lang.String destinationUrl) {
this.destinationUrl = destinationUrl;
}
/**
* Gets the sizes value for this LineItemCreativeAssociation.
*
* @return sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public com.google.api.ads.admanager.axis.v202411.Size[] getSizes() {
return sizes;
}
/**
* Sets the sizes value for this LineItemCreativeAssociation.
*
* @param sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public void setSizes(com.google.api.ads.admanager.axis.v202411.Size[] sizes) {
this.sizes = sizes;
}
public com.google.api.ads.admanager.axis.v202411.Size getSizes(int i) {
return this.sizes[i];
}
public void setSizes(int i, com.google.api.ads.admanager.axis.v202411.Size _value) {
this.sizes[i] = _value;
}
/**
* Gets the status value for this LineItemCreativeAssociation.
*
* @return status * The status of the association. This attribute is read-only.
*/
public com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStatus getStatus() {
return status;
}
/**
* Sets the status value for this LineItemCreativeAssociation.
*
* @param status * The status of the association. This attribute is read-only.
*/
public void setStatus(com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStatus status) {
this.status = status;
}
/**
* Gets the stats value for this LineItemCreativeAssociation.
*
* @return stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStats getStats() {
return stats;
}
/**
* Sets the stats value for this LineItemCreativeAssociation.
*
* @param stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public void setStats(com.google.api.ads.admanager.axis.v202411.LineItemCreativeAssociationStats stats) {
this.stats = stats;
}
/**
* Gets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @return lastModifiedDateTime * The date and time this association was last modified.
*/
public com.google.api.ads.admanager.axis.v202411.DateTime getLastModifiedDateTime() {
return lastModifiedDateTime;
}
/**
* Sets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @param lastModifiedDateTime * The date and time this association was last modified.
*/
public void setLastModifiedDateTime(com.google.api.ads.admanager.axis.v202411.DateTime lastModifiedDateTime) {
this.lastModifiedDateTime = lastModifiedDateTime;
}
/**
* Gets the targetingName value for this LineItemCreativeAssociation.
*
* @return targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public java.lang.String getTargetingName() {
return targetingName;
}
/**
* Sets the targetingName value for this LineItemCreativeAssociation.
*
* @param targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public void setTargetingName(java.lang.String targetingName) {
this.targetingName = targetingName;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LineItemCreativeAssociation)) return false;
LineItemCreativeAssociation other = (LineItemCreativeAssociation) obj;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.lineItemId==null && other.getLineItemId()==null) ||
(this.lineItemId!=null &&
this.lineItemId.equals(other.getLineItemId()))) &&
((this.creativeId==null && other.getCreativeId()==null) ||
(this.creativeId!=null &&
this.creativeId.equals(other.getCreativeId()))) &&
((this.creativeSetId==null && other.getCreativeSetId()==null) ||
(this.creativeSetId!=null &&
this.creativeSetId.equals(other.getCreativeSetId()))) &&
((this.manualCreativeRotationWeight==null && other.getManualCreativeRotationWeight()==null) ||
(this.manualCreativeRotationWeight!=null &&
this.manualCreativeRotationWeight.equals(other.getManualCreativeRotationWeight()))) &&
((this.sequentialCreativeRotationIndex==null && other.getSequentialCreativeRotationIndex()==null) ||
(this.sequentialCreativeRotationIndex!=null &&
this.sequentialCreativeRotationIndex.equals(other.getSequentialCreativeRotationIndex()))) &&
((this.startDateTime==null && other.getStartDateTime()==null) ||
(this.startDateTime!=null &&
this.startDateTime.equals(other.getStartDateTime()))) &&
((this.startDateTimeType==null && other.getStartDateTimeType()==null) ||
(this.startDateTimeType!=null &&
this.startDateTimeType.equals(other.getStartDateTimeType()))) &&
((this.endDateTime==null && other.getEndDateTime()==null) ||
(this.endDateTime!=null &&
this.endDateTime.equals(other.getEndDateTime()))) &&
((this.destinationUrl==null && other.getDestinationUrl()==null) ||
(this.destinationUrl!=null &&
this.destinationUrl.equals(other.getDestinationUrl()))) &&
((this.sizes==null && other.getSizes()==null) ||
(this.sizes!=null &&
java.util.Arrays.equals(this.sizes, other.getSizes()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus()))) &&
((this.stats==null && other.getStats()==null) ||
(this.stats!=null &&
this.stats.equals(other.getStats()))) &&
((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) ||
(this.lastModifiedDateTime!=null &&
this.lastModifiedDateTime.equals(other.getLastModifiedDateTime()))) &&
((this.targetingName==null && other.getTargetingName()==null) ||
(this.targetingName!=null &&
this.targetingName.equals(other.getTargetingName())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getLineItemId() != null) {
_hashCode += getLineItemId().hashCode();
}
if (getCreativeId() != null) {
_hashCode += getCreativeId().hashCode();
}
if (getCreativeSetId() != null) {
_hashCode += getCreativeSetId().hashCode();
}
if (getManualCreativeRotationWeight() != null) {
_hashCode += getManualCreativeRotationWeight().hashCode();
}
if (getSequentialCreativeRotationIndex() != null) {
_hashCode += getSequentialCreativeRotationIndex().hashCode();
}
if (getStartDateTime() != null) {
_hashCode += getStartDateTime().hashCode();
}
if (getStartDateTimeType() != null) {
_hashCode += getStartDateTimeType().hashCode();
}
if (getEndDateTime() != null) {
_hashCode += getEndDateTime().hashCode();
}
if (getDestinationUrl() != null) {
_hashCode += getDestinationUrl().hashCode();
}
if (getSizes() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getSizes());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getSizes(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
if (getStats() != null) {
_hashCode += getStats().hashCode();
}
if (getLastModifiedDateTime() != null) {
_hashCode += getLastModifiedDateTime().hashCode();
}
if (getTargetingName() != null) {
_hashCode += getTargetingName().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemCreativeAssociation.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "LineItemCreativeAssociation"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lineItemId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "lineItemId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "creativeId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeSetId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "creativeSetId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("manualCreativeRotationWeight");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "manualCreativeRotationWeight"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "double"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sequentialCreativeRotationIndex");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "sequentialCreativeRotationIndex"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "startDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTimeType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "startDateTimeType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "StartDateTimeType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("endDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "endDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("destinationUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "destinationUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sizes");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "sizes"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "LineItemCreativeAssociation.Status"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("stats");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "stats"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "LineItemCreativeAssociationStats"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lastModifiedDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "lastModifiedDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("targetingName");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202411", "targetingName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
googleads/googleads-java-lib | 37,566 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202502/LineItemCreativeAssociation.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
//
// 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.
/**
* LineItemCreativeAssociation.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202502;
/**
* A {@code LineItemCreativeAssociation} associates a {@link Creative}
* or {@link CreativeSet} with a
* {@link LineItem} so that the creative can be served in
* ad units targeted by the line item.
*/
public class LineItemCreativeAssociation implements java.io.Serializable {
/* The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required. */
private java.lang.Long lineItemId;
/* The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}. */
private java.lang.Long creativeId;
/* The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set. */
private java.lang.Long creativeSetId;
/* The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10. */
private java.lang.Double manualCreativeRotationWeight;
/* The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1. */
private java.lang.Integer sequentialCreativeRotationIndex;
/* Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used. */
private com.google.api.ads.admanager.axis.v202502.DateTime startDateTime;
/* Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}. */
private com.google.api.ads.admanager.axis.v202502.StartDateTimeType startDateTimeType;
/* Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used. */
private com.google.api.ads.admanager.axis.v202502.DateTime endDateTime;
/* Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks. */
private java.lang.String destinationUrl;
/* Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional. */
private com.google.api.ads.admanager.axis.v202502.Size[] sizes;
/* The status of the association. This attribute is read-only. */
private com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStatus status;
/* Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet. */
private com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStats stats;
/* The date and time this association was last modified. */
private com.google.api.ads.admanager.axis.v202502.DateTime lastModifiedDateTime;
/* Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}. */
private java.lang.String targetingName;
public LineItemCreativeAssociation() {
}
public LineItemCreativeAssociation(
java.lang.Long lineItemId,
java.lang.Long creativeId,
java.lang.Long creativeSetId,
java.lang.Double manualCreativeRotationWeight,
java.lang.Integer sequentialCreativeRotationIndex,
com.google.api.ads.admanager.axis.v202502.DateTime startDateTime,
com.google.api.ads.admanager.axis.v202502.StartDateTimeType startDateTimeType,
com.google.api.ads.admanager.axis.v202502.DateTime endDateTime,
java.lang.String destinationUrl,
com.google.api.ads.admanager.axis.v202502.Size[] sizes,
com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStatus status,
com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStats stats,
com.google.api.ads.admanager.axis.v202502.DateTime lastModifiedDateTime,
java.lang.String targetingName) {
this.lineItemId = lineItemId;
this.creativeId = creativeId;
this.creativeSetId = creativeSetId;
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
this.startDateTime = startDateTime;
this.startDateTimeType = startDateTimeType;
this.endDateTime = endDateTime;
this.destinationUrl = destinationUrl;
this.sizes = sizes;
this.status = status;
this.stats = stats;
this.lastModifiedDateTime = lastModifiedDateTime;
this.targetingName = targetingName;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("creativeId", getCreativeId())
.add("creativeSetId", getCreativeSetId())
.add("destinationUrl", getDestinationUrl())
.add("endDateTime", getEndDateTime())
.add("lastModifiedDateTime", getLastModifiedDateTime())
.add("lineItemId", getLineItemId())
.add("manualCreativeRotationWeight", getManualCreativeRotationWeight())
.add("sequentialCreativeRotationIndex", getSequentialCreativeRotationIndex())
.add("sizes", getSizes())
.add("startDateTime", getStartDateTime())
.add("startDateTimeType", getStartDateTimeType())
.add("stats", getStats())
.add("status", getStatus())
.add("targetingName", getTargetingName())
.toString();
}
/**
* Gets the lineItemId value for this LineItemCreativeAssociation.
*
* @return lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public java.lang.Long getLineItemId() {
return lineItemId;
}
/**
* Sets the lineItemId value for this LineItemCreativeAssociation.
*
* @param lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public void setLineItemId(java.lang.Long lineItemId) {
this.lineItemId = lineItemId;
}
/**
* Gets the creativeId value for this LineItemCreativeAssociation.
*
* @return creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public java.lang.Long getCreativeId() {
return creativeId;
}
/**
* Sets the creativeId value for this LineItemCreativeAssociation.
*
* @param creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public void setCreativeId(java.lang.Long creativeId) {
this.creativeId = creativeId;
}
/**
* Gets the creativeSetId value for this LineItemCreativeAssociation.
*
* @return creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public java.lang.Long getCreativeSetId() {
return creativeSetId;
}
/**
* Sets the creativeSetId value for this LineItemCreativeAssociation.
*
* @param creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public void setCreativeSetId(java.lang.Long creativeSetId) {
this.creativeSetId = creativeSetId;
}
/**
* Gets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @return manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public java.lang.Double getManualCreativeRotationWeight() {
return manualCreativeRotationWeight;
}
/**
* Sets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @param manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public void setManualCreativeRotationWeight(java.lang.Double manualCreativeRotationWeight) {
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
}
/**
* Gets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @return sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public java.lang.Integer getSequentialCreativeRotationIndex() {
return sequentialCreativeRotationIndex;
}
/**
* Sets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @param sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public void setSequentialCreativeRotationIndex(java.lang.Integer sequentialCreativeRotationIndex) {
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
}
/**
* Gets the startDateTime value for this LineItemCreativeAssociation.
*
* @return startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public com.google.api.ads.admanager.axis.v202502.DateTime getStartDateTime() {
return startDateTime;
}
/**
* Sets the startDateTime value for this LineItemCreativeAssociation.
*
* @param startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public void setStartDateTime(com.google.api.ads.admanager.axis.v202502.DateTime startDateTime) {
this.startDateTime = startDateTime;
}
/**
* Gets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @return startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public com.google.api.ads.admanager.axis.v202502.StartDateTimeType getStartDateTimeType() {
return startDateTimeType;
}
/**
* Sets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @param startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public void setStartDateTimeType(com.google.api.ads.admanager.axis.v202502.StartDateTimeType startDateTimeType) {
this.startDateTimeType = startDateTimeType;
}
/**
* Gets the endDateTime value for this LineItemCreativeAssociation.
*
* @return endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public com.google.api.ads.admanager.axis.v202502.DateTime getEndDateTime() {
return endDateTime;
}
/**
* Sets the endDateTime value for this LineItemCreativeAssociation.
*
* @param endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public void setEndDateTime(com.google.api.ads.admanager.axis.v202502.DateTime endDateTime) {
this.endDateTime = endDateTime;
}
/**
* Gets the destinationUrl value for this LineItemCreativeAssociation.
*
* @return destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public java.lang.String getDestinationUrl() {
return destinationUrl;
}
/**
* Sets the destinationUrl value for this LineItemCreativeAssociation.
*
* @param destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public void setDestinationUrl(java.lang.String destinationUrl) {
this.destinationUrl = destinationUrl;
}
/**
* Gets the sizes value for this LineItemCreativeAssociation.
*
* @return sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public com.google.api.ads.admanager.axis.v202502.Size[] getSizes() {
return sizes;
}
/**
* Sets the sizes value for this LineItemCreativeAssociation.
*
* @param sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public void setSizes(com.google.api.ads.admanager.axis.v202502.Size[] sizes) {
this.sizes = sizes;
}
public com.google.api.ads.admanager.axis.v202502.Size getSizes(int i) {
return this.sizes[i];
}
public void setSizes(int i, com.google.api.ads.admanager.axis.v202502.Size _value) {
this.sizes[i] = _value;
}
/**
* Gets the status value for this LineItemCreativeAssociation.
*
* @return status * The status of the association. This attribute is read-only.
*/
public com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStatus getStatus() {
return status;
}
/**
* Sets the status value for this LineItemCreativeAssociation.
*
* @param status * The status of the association. This attribute is read-only.
*/
public void setStatus(com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStatus status) {
this.status = status;
}
/**
* Gets the stats value for this LineItemCreativeAssociation.
*
* @return stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStats getStats() {
return stats;
}
/**
* Sets the stats value for this LineItemCreativeAssociation.
*
* @param stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public void setStats(com.google.api.ads.admanager.axis.v202502.LineItemCreativeAssociationStats stats) {
this.stats = stats;
}
/**
* Gets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @return lastModifiedDateTime * The date and time this association was last modified.
*/
public com.google.api.ads.admanager.axis.v202502.DateTime getLastModifiedDateTime() {
return lastModifiedDateTime;
}
/**
* Sets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @param lastModifiedDateTime * The date and time this association was last modified.
*/
public void setLastModifiedDateTime(com.google.api.ads.admanager.axis.v202502.DateTime lastModifiedDateTime) {
this.lastModifiedDateTime = lastModifiedDateTime;
}
/**
* Gets the targetingName value for this LineItemCreativeAssociation.
*
* @return targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public java.lang.String getTargetingName() {
return targetingName;
}
/**
* Sets the targetingName value for this LineItemCreativeAssociation.
*
* @param targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public void setTargetingName(java.lang.String targetingName) {
this.targetingName = targetingName;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LineItemCreativeAssociation)) return false;
LineItemCreativeAssociation other = (LineItemCreativeAssociation) obj;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.lineItemId==null && other.getLineItemId()==null) ||
(this.lineItemId!=null &&
this.lineItemId.equals(other.getLineItemId()))) &&
((this.creativeId==null && other.getCreativeId()==null) ||
(this.creativeId!=null &&
this.creativeId.equals(other.getCreativeId()))) &&
((this.creativeSetId==null && other.getCreativeSetId()==null) ||
(this.creativeSetId!=null &&
this.creativeSetId.equals(other.getCreativeSetId()))) &&
((this.manualCreativeRotationWeight==null && other.getManualCreativeRotationWeight()==null) ||
(this.manualCreativeRotationWeight!=null &&
this.manualCreativeRotationWeight.equals(other.getManualCreativeRotationWeight()))) &&
((this.sequentialCreativeRotationIndex==null && other.getSequentialCreativeRotationIndex()==null) ||
(this.sequentialCreativeRotationIndex!=null &&
this.sequentialCreativeRotationIndex.equals(other.getSequentialCreativeRotationIndex()))) &&
((this.startDateTime==null && other.getStartDateTime()==null) ||
(this.startDateTime!=null &&
this.startDateTime.equals(other.getStartDateTime()))) &&
((this.startDateTimeType==null && other.getStartDateTimeType()==null) ||
(this.startDateTimeType!=null &&
this.startDateTimeType.equals(other.getStartDateTimeType()))) &&
((this.endDateTime==null && other.getEndDateTime()==null) ||
(this.endDateTime!=null &&
this.endDateTime.equals(other.getEndDateTime()))) &&
((this.destinationUrl==null && other.getDestinationUrl()==null) ||
(this.destinationUrl!=null &&
this.destinationUrl.equals(other.getDestinationUrl()))) &&
((this.sizes==null && other.getSizes()==null) ||
(this.sizes!=null &&
java.util.Arrays.equals(this.sizes, other.getSizes()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus()))) &&
((this.stats==null && other.getStats()==null) ||
(this.stats!=null &&
this.stats.equals(other.getStats()))) &&
((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) ||
(this.lastModifiedDateTime!=null &&
this.lastModifiedDateTime.equals(other.getLastModifiedDateTime()))) &&
((this.targetingName==null && other.getTargetingName()==null) ||
(this.targetingName!=null &&
this.targetingName.equals(other.getTargetingName())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getLineItemId() != null) {
_hashCode += getLineItemId().hashCode();
}
if (getCreativeId() != null) {
_hashCode += getCreativeId().hashCode();
}
if (getCreativeSetId() != null) {
_hashCode += getCreativeSetId().hashCode();
}
if (getManualCreativeRotationWeight() != null) {
_hashCode += getManualCreativeRotationWeight().hashCode();
}
if (getSequentialCreativeRotationIndex() != null) {
_hashCode += getSequentialCreativeRotationIndex().hashCode();
}
if (getStartDateTime() != null) {
_hashCode += getStartDateTime().hashCode();
}
if (getStartDateTimeType() != null) {
_hashCode += getStartDateTimeType().hashCode();
}
if (getEndDateTime() != null) {
_hashCode += getEndDateTime().hashCode();
}
if (getDestinationUrl() != null) {
_hashCode += getDestinationUrl().hashCode();
}
if (getSizes() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getSizes());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getSizes(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
if (getStats() != null) {
_hashCode += getStats().hashCode();
}
if (getLastModifiedDateTime() != null) {
_hashCode += getLastModifiedDateTime().hashCode();
}
if (getTargetingName() != null) {
_hashCode += getTargetingName().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemCreativeAssociation.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "LineItemCreativeAssociation"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lineItemId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "lineItemId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "creativeId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeSetId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "creativeSetId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("manualCreativeRotationWeight");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "manualCreativeRotationWeight"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "double"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sequentialCreativeRotationIndex");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "sequentialCreativeRotationIndex"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "startDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTimeType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "startDateTimeType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "StartDateTimeType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("endDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "endDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("destinationUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "destinationUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sizes");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "sizes"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "LineItemCreativeAssociation.Status"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("stats");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "stats"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "LineItemCreativeAssociationStats"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lastModifiedDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "lastModifiedDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("targetingName");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202502", "targetingName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
googleads/googleads-java-lib | 37,566 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202505/LineItemCreativeAssociation.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
//
// 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.
/**
* LineItemCreativeAssociation.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202505;
/**
* A {@code LineItemCreativeAssociation} associates a {@link Creative}
* or {@link CreativeSet} with a
* {@link LineItem} so that the creative can be served in
* ad units targeted by the line item.
*/
public class LineItemCreativeAssociation implements java.io.Serializable {
/* The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required. */
private java.lang.Long lineItemId;
/* The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}. */
private java.lang.Long creativeId;
/* The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set. */
private java.lang.Long creativeSetId;
/* The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10. */
private java.lang.Double manualCreativeRotationWeight;
/* The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1. */
private java.lang.Integer sequentialCreativeRotationIndex;
/* Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used. */
private com.google.api.ads.admanager.axis.v202505.DateTime startDateTime;
/* Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}. */
private com.google.api.ads.admanager.axis.v202505.StartDateTimeType startDateTimeType;
/* Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used. */
private com.google.api.ads.admanager.axis.v202505.DateTime endDateTime;
/* Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks. */
private java.lang.String destinationUrl;
/* Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional. */
private com.google.api.ads.admanager.axis.v202505.Size[] sizes;
/* The status of the association. This attribute is read-only. */
private com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStatus status;
/* Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet. */
private com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStats stats;
/* The date and time this association was last modified. */
private com.google.api.ads.admanager.axis.v202505.DateTime lastModifiedDateTime;
/* Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}. */
private java.lang.String targetingName;
public LineItemCreativeAssociation() {
}
public LineItemCreativeAssociation(
java.lang.Long lineItemId,
java.lang.Long creativeId,
java.lang.Long creativeSetId,
java.lang.Double manualCreativeRotationWeight,
java.lang.Integer sequentialCreativeRotationIndex,
com.google.api.ads.admanager.axis.v202505.DateTime startDateTime,
com.google.api.ads.admanager.axis.v202505.StartDateTimeType startDateTimeType,
com.google.api.ads.admanager.axis.v202505.DateTime endDateTime,
java.lang.String destinationUrl,
com.google.api.ads.admanager.axis.v202505.Size[] sizes,
com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStatus status,
com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStats stats,
com.google.api.ads.admanager.axis.v202505.DateTime lastModifiedDateTime,
java.lang.String targetingName) {
this.lineItemId = lineItemId;
this.creativeId = creativeId;
this.creativeSetId = creativeSetId;
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
this.startDateTime = startDateTime;
this.startDateTimeType = startDateTimeType;
this.endDateTime = endDateTime;
this.destinationUrl = destinationUrl;
this.sizes = sizes;
this.status = status;
this.stats = stats;
this.lastModifiedDateTime = lastModifiedDateTime;
this.targetingName = targetingName;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("creativeId", getCreativeId())
.add("creativeSetId", getCreativeSetId())
.add("destinationUrl", getDestinationUrl())
.add("endDateTime", getEndDateTime())
.add("lastModifiedDateTime", getLastModifiedDateTime())
.add("lineItemId", getLineItemId())
.add("manualCreativeRotationWeight", getManualCreativeRotationWeight())
.add("sequentialCreativeRotationIndex", getSequentialCreativeRotationIndex())
.add("sizes", getSizes())
.add("startDateTime", getStartDateTime())
.add("startDateTimeType", getStartDateTimeType())
.add("stats", getStats())
.add("status", getStatus())
.add("targetingName", getTargetingName())
.toString();
}
/**
* Gets the lineItemId value for this LineItemCreativeAssociation.
*
* @return lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public java.lang.Long getLineItemId() {
return lineItemId;
}
/**
* Sets the lineItemId value for this LineItemCreativeAssociation.
*
* @param lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public void setLineItemId(java.lang.Long lineItemId) {
this.lineItemId = lineItemId;
}
/**
* Gets the creativeId value for this LineItemCreativeAssociation.
*
* @return creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public java.lang.Long getCreativeId() {
return creativeId;
}
/**
* Sets the creativeId value for this LineItemCreativeAssociation.
*
* @param creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public void setCreativeId(java.lang.Long creativeId) {
this.creativeId = creativeId;
}
/**
* Gets the creativeSetId value for this LineItemCreativeAssociation.
*
* @return creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public java.lang.Long getCreativeSetId() {
return creativeSetId;
}
/**
* Sets the creativeSetId value for this LineItemCreativeAssociation.
*
* @param creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public void setCreativeSetId(java.lang.Long creativeSetId) {
this.creativeSetId = creativeSetId;
}
/**
* Gets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @return manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public java.lang.Double getManualCreativeRotationWeight() {
return manualCreativeRotationWeight;
}
/**
* Sets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @param manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public void setManualCreativeRotationWeight(java.lang.Double manualCreativeRotationWeight) {
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
}
/**
* Gets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @return sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public java.lang.Integer getSequentialCreativeRotationIndex() {
return sequentialCreativeRotationIndex;
}
/**
* Sets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @param sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public void setSequentialCreativeRotationIndex(java.lang.Integer sequentialCreativeRotationIndex) {
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
}
/**
* Gets the startDateTime value for this LineItemCreativeAssociation.
*
* @return startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public com.google.api.ads.admanager.axis.v202505.DateTime getStartDateTime() {
return startDateTime;
}
/**
* Sets the startDateTime value for this LineItemCreativeAssociation.
*
* @param startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public void setStartDateTime(com.google.api.ads.admanager.axis.v202505.DateTime startDateTime) {
this.startDateTime = startDateTime;
}
/**
* Gets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @return startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public com.google.api.ads.admanager.axis.v202505.StartDateTimeType getStartDateTimeType() {
return startDateTimeType;
}
/**
* Sets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @param startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public void setStartDateTimeType(com.google.api.ads.admanager.axis.v202505.StartDateTimeType startDateTimeType) {
this.startDateTimeType = startDateTimeType;
}
/**
* Gets the endDateTime value for this LineItemCreativeAssociation.
*
* @return endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public com.google.api.ads.admanager.axis.v202505.DateTime getEndDateTime() {
return endDateTime;
}
/**
* Sets the endDateTime value for this LineItemCreativeAssociation.
*
* @param endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public void setEndDateTime(com.google.api.ads.admanager.axis.v202505.DateTime endDateTime) {
this.endDateTime = endDateTime;
}
/**
* Gets the destinationUrl value for this LineItemCreativeAssociation.
*
* @return destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public java.lang.String getDestinationUrl() {
return destinationUrl;
}
/**
* Sets the destinationUrl value for this LineItemCreativeAssociation.
*
* @param destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public void setDestinationUrl(java.lang.String destinationUrl) {
this.destinationUrl = destinationUrl;
}
/**
* Gets the sizes value for this LineItemCreativeAssociation.
*
* @return sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public com.google.api.ads.admanager.axis.v202505.Size[] getSizes() {
return sizes;
}
/**
* Sets the sizes value for this LineItemCreativeAssociation.
*
* @param sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public void setSizes(com.google.api.ads.admanager.axis.v202505.Size[] sizes) {
this.sizes = sizes;
}
public com.google.api.ads.admanager.axis.v202505.Size getSizes(int i) {
return this.sizes[i];
}
public void setSizes(int i, com.google.api.ads.admanager.axis.v202505.Size _value) {
this.sizes[i] = _value;
}
/**
* Gets the status value for this LineItemCreativeAssociation.
*
* @return status * The status of the association. This attribute is read-only.
*/
public com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStatus getStatus() {
return status;
}
/**
* Sets the status value for this LineItemCreativeAssociation.
*
* @param status * The status of the association. This attribute is read-only.
*/
public void setStatus(com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStatus status) {
this.status = status;
}
/**
* Gets the stats value for this LineItemCreativeAssociation.
*
* @return stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStats getStats() {
return stats;
}
/**
* Sets the stats value for this LineItemCreativeAssociation.
*
* @param stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public void setStats(com.google.api.ads.admanager.axis.v202505.LineItemCreativeAssociationStats stats) {
this.stats = stats;
}
/**
* Gets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @return lastModifiedDateTime * The date and time this association was last modified.
*/
public com.google.api.ads.admanager.axis.v202505.DateTime getLastModifiedDateTime() {
return lastModifiedDateTime;
}
/**
* Sets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @param lastModifiedDateTime * The date and time this association was last modified.
*/
public void setLastModifiedDateTime(com.google.api.ads.admanager.axis.v202505.DateTime lastModifiedDateTime) {
this.lastModifiedDateTime = lastModifiedDateTime;
}
/**
* Gets the targetingName value for this LineItemCreativeAssociation.
*
* @return targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public java.lang.String getTargetingName() {
return targetingName;
}
/**
* Sets the targetingName value for this LineItemCreativeAssociation.
*
* @param targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public void setTargetingName(java.lang.String targetingName) {
this.targetingName = targetingName;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LineItemCreativeAssociation)) return false;
LineItemCreativeAssociation other = (LineItemCreativeAssociation) obj;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.lineItemId==null && other.getLineItemId()==null) ||
(this.lineItemId!=null &&
this.lineItemId.equals(other.getLineItemId()))) &&
((this.creativeId==null && other.getCreativeId()==null) ||
(this.creativeId!=null &&
this.creativeId.equals(other.getCreativeId()))) &&
((this.creativeSetId==null && other.getCreativeSetId()==null) ||
(this.creativeSetId!=null &&
this.creativeSetId.equals(other.getCreativeSetId()))) &&
((this.manualCreativeRotationWeight==null && other.getManualCreativeRotationWeight()==null) ||
(this.manualCreativeRotationWeight!=null &&
this.manualCreativeRotationWeight.equals(other.getManualCreativeRotationWeight()))) &&
((this.sequentialCreativeRotationIndex==null && other.getSequentialCreativeRotationIndex()==null) ||
(this.sequentialCreativeRotationIndex!=null &&
this.sequentialCreativeRotationIndex.equals(other.getSequentialCreativeRotationIndex()))) &&
((this.startDateTime==null && other.getStartDateTime()==null) ||
(this.startDateTime!=null &&
this.startDateTime.equals(other.getStartDateTime()))) &&
((this.startDateTimeType==null && other.getStartDateTimeType()==null) ||
(this.startDateTimeType!=null &&
this.startDateTimeType.equals(other.getStartDateTimeType()))) &&
((this.endDateTime==null && other.getEndDateTime()==null) ||
(this.endDateTime!=null &&
this.endDateTime.equals(other.getEndDateTime()))) &&
((this.destinationUrl==null && other.getDestinationUrl()==null) ||
(this.destinationUrl!=null &&
this.destinationUrl.equals(other.getDestinationUrl()))) &&
((this.sizes==null && other.getSizes()==null) ||
(this.sizes!=null &&
java.util.Arrays.equals(this.sizes, other.getSizes()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus()))) &&
((this.stats==null && other.getStats()==null) ||
(this.stats!=null &&
this.stats.equals(other.getStats()))) &&
((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) ||
(this.lastModifiedDateTime!=null &&
this.lastModifiedDateTime.equals(other.getLastModifiedDateTime()))) &&
((this.targetingName==null && other.getTargetingName()==null) ||
(this.targetingName!=null &&
this.targetingName.equals(other.getTargetingName())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getLineItemId() != null) {
_hashCode += getLineItemId().hashCode();
}
if (getCreativeId() != null) {
_hashCode += getCreativeId().hashCode();
}
if (getCreativeSetId() != null) {
_hashCode += getCreativeSetId().hashCode();
}
if (getManualCreativeRotationWeight() != null) {
_hashCode += getManualCreativeRotationWeight().hashCode();
}
if (getSequentialCreativeRotationIndex() != null) {
_hashCode += getSequentialCreativeRotationIndex().hashCode();
}
if (getStartDateTime() != null) {
_hashCode += getStartDateTime().hashCode();
}
if (getStartDateTimeType() != null) {
_hashCode += getStartDateTimeType().hashCode();
}
if (getEndDateTime() != null) {
_hashCode += getEndDateTime().hashCode();
}
if (getDestinationUrl() != null) {
_hashCode += getDestinationUrl().hashCode();
}
if (getSizes() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getSizes());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getSizes(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
if (getStats() != null) {
_hashCode += getStats().hashCode();
}
if (getLastModifiedDateTime() != null) {
_hashCode += getLastModifiedDateTime().hashCode();
}
if (getTargetingName() != null) {
_hashCode += getTargetingName().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemCreativeAssociation.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "LineItemCreativeAssociation"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lineItemId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "lineItemId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "creativeId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeSetId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "creativeSetId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("manualCreativeRotationWeight");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "manualCreativeRotationWeight"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "double"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sequentialCreativeRotationIndex");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "sequentialCreativeRotationIndex"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "startDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTimeType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "startDateTimeType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "StartDateTimeType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("endDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "endDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("destinationUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "destinationUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sizes");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "sizes"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "LineItemCreativeAssociation.Status"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("stats");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "stats"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "LineItemCreativeAssociationStats"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lastModifiedDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "lastModifiedDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("targetingName");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202505", "targetingName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
googleads/googleads-java-lib | 37,566 | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202508/LineItemCreativeAssociation.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
//
// 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.
/**
* LineItemCreativeAssociation.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4.1-SNAPSHOT Mar 20, 2024 (11:59:10 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202508;
/**
* A {@code LineItemCreativeAssociation} associates a {@link Creative}
* or {@link CreativeSet} with a
* {@link LineItem} so that the creative can be served in
* ad units targeted by the line item.
*/
public class LineItemCreativeAssociation implements java.io.Serializable {
/* The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required. */
private java.lang.Long lineItemId;
/* The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}. */
private java.lang.Long creativeId;
/* The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set. */
private java.lang.Long creativeSetId;
/* The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10. */
private java.lang.Double manualCreativeRotationWeight;
/* The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1. */
private java.lang.Integer sequentialCreativeRotationIndex;
/* Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used. */
private com.google.api.ads.admanager.axis.v202508.DateTime startDateTime;
/* Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}. */
private com.google.api.ads.admanager.axis.v202508.StartDateTimeType startDateTimeType;
/* Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used. */
private com.google.api.ads.admanager.axis.v202508.DateTime endDateTime;
/* Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks. */
private java.lang.String destinationUrl;
/* Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional. */
private com.google.api.ads.admanager.axis.v202508.Size[] sizes;
/* The status of the association. This attribute is read-only. */
private com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStatus status;
/* Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet. */
private com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStats stats;
/* The date and time this association was last modified. */
private com.google.api.ads.admanager.axis.v202508.DateTime lastModifiedDateTime;
/* Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}. */
private java.lang.String targetingName;
public LineItemCreativeAssociation() {
}
public LineItemCreativeAssociation(
java.lang.Long lineItemId,
java.lang.Long creativeId,
java.lang.Long creativeSetId,
java.lang.Double manualCreativeRotationWeight,
java.lang.Integer sequentialCreativeRotationIndex,
com.google.api.ads.admanager.axis.v202508.DateTime startDateTime,
com.google.api.ads.admanager.axis.v202508.StartDateTimeType startDateTimeType,
com.google.api.ads.admanager.axis.v202508.DateTime endDateTime,
java.lang.String destinationUrl,
com.google.api.ads.admanager.axis.v202508.Size[] sizes,
com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStatus status,
com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStats stats,
com.google.api.ads.admanager.axis.v202508.DateTime lastModifiedDateTime,
java.lang.String targetingName) {
this.lineItemId = lineItemId;
this.creativeId = creativeId;
this.creativeSetId = creativeSetId;
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
this.startDateTime = startDateTime;
this.startDateTimeType = startDateTimeType;
this.endDateTime = endDateTime;
this.destinationUrl = destinationUrl;
this.sizes = sizes;
this.status = status;
this.stats = stats;
this.lastModifiedDateTime = lastModifiedDateTime;
this.targetingName = targetingName;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("creativeId", getCreativeId())
.add("creativeSetId", getCreativeSetId())
.add("destinationUrl", getDestinationUrl())
.add("endDateTime", getEndDateTime())
.add("lastModifiedDateTime", getLastModifiedDateTime())
.add("lineItemId", getLineItemId())
.add("manualCreativeRotationWeight", getManualCreativeRotationWeight())
.add("sequentialCreativeRotationIndex", getSequentialCreativeRotationIndex())
.add("sizes", getSizes())
.add("startDateTime", getStartDateTime())
.add("startDateTimeType", getStartDateTimeType())
.add("stats", getStats())
.add("status", getStatus())
.add("targetingName", getTargetingName())
.toString();
}
/**
* Gets the lineItemId value for this LineItemCreativeAssociation.
*
* @return lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public java.lang.Long getLineItemId() {
return lineItemId;
}
/**
* Sets the lineItemId value for this LineItemCreativeAssociation.
*
* @param lineItemId * The ID of the {@link LineItem} to which the {@link Creative}
* should be associated. This
* attribute is required.
*/
public void setLineItemId(java.lang.Long lineItemId) {
this.lineItemId = lineItemId;
}
/**
* Gets the creativeId value for this LineItemCreativeAssociation.
*
* @return creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public java.lang.Long getCreativeId() {
return creativeId;
}
/**
* Sets the creativeId value for this LineItemCreativeAssociation.
*
* @param creativeId * The ID of the {@link Creative} being associated with a {@link
* LineItem}.
*
* <p>This attribute is required if this is an association
* between a line item and a creative.
* <br>
* This attribute is ignored if this is an association
* between a line item and a creative set.
*
* <p>If this is an association between a line item and
* a creative, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the creative's ID. <br>
* If this is an association between a line item and
* a creative set, when retrieving the line item
* creative association, the {@link #creativeId} will
* be the ID of the {@link
* CreativeSet#masterCreativeId master creative}.
*/
public void setCreativeId(java.lang.Long creativeId) {
this.creativeId = creativeId;
}
/**
* Gets the creativeSetId value for this LineItemCreativeAssociation.
*
* @return creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public java.lang.Long getCreativeSetId() {
return creativeSetId;
}
/**
* Sets the creativeSetId value for this LineItemCreativeAssociation.
*
* @param creativeSetId * The ID of the {@link CreativeSet} being associated with a {@link
* LineItem}. This attribute is
* required if this is an association between a line
* item and a creative set.
*
* <p>This field will be {@code null} when retrieving
* associations between line items and
* creatives not belonging to a set.
*/
public void setCreativeSetId(java.lang.Long creativeSetId) {
this.creativeSetId = creativeSetId;
}
/**
* Gets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @return manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public java.lang.Double getManualCreativeRotationWeight() {
return manualCreativeRotationWeight;
}
/**
* Sets the manualCreativeRotationWeight value for this LineItemCreativeAssociation.
*
* @param manualCreativeRotationWeight * The weight of the {@link Creative}. This value is only used
* if the line item's {@code
* creativeRotationType} is set to {@link CreativeRotationType#MANUAL}.
* This attribute is optional
* and defaults to 10.
*/
public void setManualCreativeRotationWeight(java.lang.Double manualCreativeRotationWeight) {
this.manualCreativeRotationWeight = manualCreativeRotationWeight;
}
/**
* Gets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @return sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public java.lang.Integer getSequentialCreativeRotationIndex() {
return sequentialCreativeRotationIndex;
}
/**
* Sets the sequentialCreativeRotationIndex value for this LineItemCreativeAssociation.
*
* @param sequentialCreativeRotationIndex * The sequential rotation index of the {@link Creative}. This
* value is used only if the
* associated line item's {@link LineItem#creativeRotationType}
* is set to {@link
* CreativeRotationType#SEQUENTIAL}. This attribute is
* optional and defaults to 1.
*/
public void setSequentialCreativeRotationIndex(java.lang.Integer sequentialCreativeRotationIndex) {
this.sequentialCreativeRotationIndex = sequentialCreativeRotationIndex;
}
/**
* Gets the startDateTime value for this LineItemCreativeAssociation.
*
* @return startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public com.google.api.ads.admanager.axis.v202508.DateTime getStartDateTime() {
return startDateTime;
}
/**
* Sets the startDateTime value for this LineItemCreativeAssociation.
*
* @param startDateTime * Overrides the value set for {@link LineItem#startDateTime}.
* This value is optional and is only
* valid for Ad Manager 360 networks. If unset, the {@link
* LineItem#startDateTime} will be used.
*/
public void setStartDateTime(com.google.api.ads.admanager.axis.v202508.DateTime startDateTime) {
this.startDateTime = startDateTime;
}
/**
* Gets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @return startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public com.google.api.ads.admanager.axis.v202508.StartDateTimeType getStartDateTimeType() {
return startDateTimeType;
}
/**
* Sets the startDateTimeType value for this LineItemCreativeAssociation.
*
* @param startDateTimeType * Specifies whether to start serving to the {@code LineItemCreativeAssociation}
* right away, in an
* hour, etc. This attribute is optional and defaults
* to {@link
* StartDateTimeType#USE_START_DATE_TIME}.
*/
public void setStartDateTimeType(com.google.api.ads.admanager.axis.v202508.StartDateTimeType startDateTimeType) {
this.startDateTimeType = startDateTimeType;
}
/**
* Gets the endDateTime value for this LineItemCreativeAssociation.
*
* @return endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public com.google.api.ads.admanager.axis.v202508.DateTime getEndDateTime() {
return endDateTime;
}
/**
* Sets the endDateTime value for this LineItemCreativeAssociation.
*
* @param endDateTime * Overrides {@link LineItem#endDateTime}. This value is optional
* and is only valid for Ad Manager
* 360 networks. If unset, the {@link LineItem#endDateTime}
* will be used.
*/
public void setEndDateTime(com.google.api.ads.admanager.axis.v202508.DateTime endDateTime) {
this.endDateTime = endDateTime;
}
/**
* Gets the destinationUrl value for this LineItemCreativeAssociation.
*
* @return destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public java.lang.String getDestinationUrl() {
return destinationUrl;
}
/**
* Sets the destinationUrl value for this LineItemCreativeAssociation.
*
* @param destinationUrl * Overrides the value set for {@link HasDestinationUrlCreative#destinationUrl}.
* This value is
* optional and is only valid for Ad Manager 360 networks.
*/
public void setDestinationUrl(java.lang.String destinationUrl) {
this.destinationUrl = destinationUrl;
}
/**
* Gets the sizes value for this LineItemCreativeAssociation.
*
* @return sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public com.google.api.ads.admanager.axis.v202508.Size[] getSizes() {
return sizes;
}
/**
* Sets the sizes value for this LineItemCreativeAssociation.
*
* @param sizes * Overrides the value set for {@link Creative#size}, which allows
* the creative to be served to ad
* units that would otherwise not be compatible for its
* actual size. This value is optional.
*/
public void setSizes(com.google.api.ads.admanager.axis.v202508.Size[] sizes) {
this.sizes = sizes;
}
public com.google.api.ads.admanager.axis.v202508.Size getSizes(int i) {
return this.sizes[i];
}
public void setSizes(int i, com.google.api.ads.admanager.axis.v202508.Size _value) {
this.sizes[i] = _value;
}
/**
* Gets the status value for this LineItemCreativeAssociation.
*
* @return status * The status of the association. This attribute is read-only.
*/
public com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStatus getStatus() {
return status;
}
/**
* Sets the status value for this LineItemCreativeAssociation.
*
* @param status * The status of the association. This attribute is read-only.
*/
public void setStatus(com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStatus status) {
this.status = status;
}
/**
* Gets the stats value for this LineItemCreativeAssociation.
*
* @return stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStats getStats() {
return stats;
}
/**
* Sets the stats value for this LineItemCreativeAssociation.
*
* @param stats * Contains trafficking statistics for the association. This attribute
* is readonly and is
* populated by Google. This will be {@code null} in
* case there are no statistics for the
* association yet.
*/
public void setStats(com.google.api.ads.admanager.axis.v202508.LineItemCreativeAssociationStats stats) {
this.stats = stats;
}
/**
* Gets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @return lastModifiedDateTime * The date and time this association was last modified.
*/
public com.google.api.ads.admanager.axis.v202508.DateTime getLastModifiedDateTime() {
return lastModifiedDateTime;
}
/**
* Sets the lastModifiedDateTime value for this LineItemCreativeAssociation.
*
* @param lastModifiedDateTime * The date and time this association was last modified.
*/
public void setLastModifiedDateTime(com.google.api.ads.admanager.axis.v202508.DateTime lastModifiedDateTime) {
this.lastModifiedDateTime = lastModifiedDateTime;
}
/**
* Gets the targetingName value for this LineItemCreativeAssociation.
*
* @return targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public java.lang.String getTargetingName() {
return targetingName;
}
/**
* Sets the targetingName value for this LineItemCreativeAssociation.
*
* @param targetingName * Specifies {@link CreativeTargeting} for this line item creative
* association.
*
* <p>This attribute is optional. It should match the
* creative targeting specified on the
* corresponding {@link CreativePlaceholder} in the {@link
* LineItem} that is being associated with
* the {@link Creative}.
*/
public void setTargetingName(java.lang.String targetingName) {
this.targetingName = targetingName;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LineItemCreativeAssociation)) return false;
LineItemCreativeAssociation other = (LineItemCreativeAssociation) obj;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.lineItemId==null && other.getLineItemId()==null) ||
(this.lineItemId!=null &&
this.lineItemId.equals(other.getLineItemId()))) &&
((this.creativeId==null && other.getCreativeId()==null) ||
(this.creativeId!=null &&
this.creativeId.equals(other.getCreativeId()))) &&
((this.creativeSetId==null && other.getCreativeSetId()==null) ||
(this.creativeSetId!=null &&
this.creativeSetId.equals(other.getCreativeSetId()))) &&
((this.manualCreativeRotationWeight==null && other.getManualCreativeRotationWeight()==null) ||
(this.manualCreativeRotationWeight!=null &&
this.manualCreativeRotationWeight.equals(other.getManualCreativeRotationWeight()))) &&
((this.sequentialCreativeRotationIndex==null && other.getSequentialCreativeRotationIndex()==null) ||
(this.sequentialCreativeRotationIndex!=null &&
this.sequentialCreativeRotationIndex.equals(other.getSequentialCreativeRotationIndex()))) &&
((this.startDateTime==null && other.getStartDateTime()==null) ||
(this.startDateTime!=null &&
this.startDateTime.equals(other.getStartDateTime()))) &&
((this.startDateTimeType==null && other.getStartDateTimeType()==null) ||
(this.startDateTimeType!=null &&
this.startDateTimeType.equals(other.getStartDateTimeType()))) &&
((this.endDateTime==null && other.getEndDateTime()==null) ||
(this.endDateTime!=null &&
this.endDateTime.equals(other.getEndDateTime()))) &&
((this.destinationUrl==null && other.getDestinationUrl()==null) ||
(this.destinationUrl!=null &&
this.destinationUrl.equals(other.getDestinationUrl()))) &&
((this.sizes==null && other.getSizes()==null) ||
(this.sizes!=null &&
java.util.Arrays.equals(this.sizes, other.getSizes()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus()))) &&
((this.stats==null && other.getStats()==null) ||
(this.stats!=null &&
this.stats.equals(other.getStats()))) &&
((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) ||
(this.lastModifiedDateTime!=null &&
this.lastModifiedDateTime.equals(other.getLastModifiedDateTime()))) &&
((this.targetingName==null && other.getTargetingName()==null) ||
(this.targetingName!=null &&
this.targetingName.equals(other.getTargetingName())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getLineItemId() != null) {
_hashCode += getLineItemId().hashCode();
}
if (getCreativeId() != null) {
_hashCode += getCreativeId().hashCode();
}
if (getCreativeSetId() != null) {
_hashCode += getCreativeSetId().hashCode();
}
if (getManualCreativeRotationWeight() != null) {
_hashCode += getManualCreativeRotationWeight().hashCode();
}
if (getSequentialCreativeRotationIndex() != null) {
_hashCode += getSequentialCreativeRotationIndex().hashCode();
}
if (getStartDateTime() != null) {
_hashCode += getStartDateTime().hashCode();
}
if (getStartDateTimeType() != null) {
_hashCode += getStartDateTimeType().hashCode();
}
if (getEndDateTime() != null) {
_hashCode += getEndDateTime().hashCode();
}
if (getDestinationUrl() != null) {
_hashCode += getDestinationUrl().hashCode();
}
if (getSizes() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getSizes());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getSizes(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
if (getStats() != null) {
_hashCode += getStats().hashCode();
}
if (getLastModifiedDateTime() != null) {
_hashCode += getLastModifiedDateTime().hashCode();
}
if (getTargetingName() != null) {
_hashCode += getTargetingName().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemCreativeAssociation.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "LineItemCreativeAssociation"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lineItemId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "lineItemId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "creativeId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeSetId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "creativeSetId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("manualCreativeRotationWeight");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "manualCreativeRotationWeight"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "double"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sequentialCreativeRotationIndex");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "sequentialCreativeRotationIndex"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "startDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("startDateTimeType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "startDateTimeType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "StartDateTimeType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("endDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "endDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("destinationUrl");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "destinationUrl"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("sizes");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "sizes"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "LineItemCreativeAssociation.Status"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("stats");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "stats"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "LineItemCreativeAssociationStats"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lastModifiedDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "lastModifiedDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("targetingName");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202508", "targetingName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
apache/poi | 37,596 | poi-scratchpad/src/main/java/org/apache/poi/hwpf/HWPFDocument.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.poi.hwpf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hwpf.model.BookmarksTables;
import org.apache.poi.hwpf.model.CHPBinTable;
import org.apache.poi.hwpf.model.ComplexFileTable;
import org.apache.poi.hwpf.model.DocumentProperties;
import org.apache.poi.hwpf.model.FSPADocumentPart;
import org.apache.poi.hwpf.model.FSPATable;
import org.apache.poi.hwpf.model.FieldsTables;
import org.apache.poi.hwpf.model.FontTable;
import org.apache.poi.hwpf.model.ListTables;
import org.apache.poi.hwpf.model.NoteType;
import org.apache.poi.hwpf.model.NotesTables;
import org.apache.poi.hwpf.model.OfficeArtContent;
import org.apache.poi.hwpf.model.PAPBinTable;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.model.RevisionMarkAuthorTable;
import org.apache.poi.hwpf.model.SavedByTable;
import org.apache.poi.hwpf.model.SectionTable;
import org.apache.poi.hwpf.model.SinglentonTextPiece;
import org.apache.poi.hwpf.model.StyleSheet;
import org.apache.poi.hwpf.model.SubdocumentType;
import org.apache.poi.hwpf.model.TextPiece;
import org.apache.poi.hwpf.model.TextPieceTable;
import org.apache.poi.hwpf.model.io.HWPFFileSystem;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.BookmarksImpl;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.FieldsImpl;
import org.apache.poi.hwpf.usermodel.HWPFList;
import org.apache.poi.hwpf.usermodel.Notes;
import org.apache.poi.hwpf.usermodel.NotesImpl;
import org.apache.poi.hwpf.usermodel.OfficeDrawings;
import org.apache.poi.hwpf.usermodel.OfficeDrawingsImpl;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.poifs.crypt.ChunkedCipherOutputStream;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.crypt.standard.EncryptionRecord;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.EntryUtils;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Internal;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
/**
* This class acts as the bucket that we throw all of the Word data structures
* into.
*/
public final class HWPFDocument extends HWPFDocumentCore {
/*package*/ static final String PROPERTY_PRESERVE_BIN_TABLES = "org.apache.poi.hwpf.preserveBinTables";
private static final String PROPERTY_PRESERVE_TEXT_TABLE = "org.apache.poi.hwpf.preserveTextTable";
//arbitrarily selected; may need to increase
private static final int DEFAULT_MAX_RECORD_LENGTH = 100_000;
private static int MAX_RECORD_LENGTH = DEFAULT_MAX_RECORD_LENGTH;
private static final String STREAM_DATA = "Data";
/**
* table stream buffer
*/
private byte[] _tableStream;
/**
* data stream buffer
*/
private byte[] _dataStream;
/**
* Document wide Properties
*/
private DocumentProperties _dop;
/**
* Contains text of the document wrapped in an obfuscated Word data
* structure
*/
private ComplexFileTable _cft;
/**
* Contains text buffer linked directly to single-piece document text piece
*/
private StringBuilder _text;
/**
* Holds the save history for this document.
*/
private SavedByTable _sbt;
/**
* Holds the revision mark authors for this document.
*/
private RevisionMarkAuthorTable _rmat;
/**
* Holds FSBA (shape) information
*/
private FSPATable _fspaHeaders;
/**
* Holds FSBA (shape) information
*/
private FSPATable _fspaMain;
/**
* Office Art (Escher records) information
*/
private final OfficeArtContent officeArtContent;
/**
* Holds pictures table
*/
private PicturesTable _pictures;
/**
* Holds Office Art objects
*/
private OfficeDrawingsImpl _officeDrawingsHeaders;
/**
* Holds Office Art objects
*/
private OfficeDrawingsImpl _officeDrawingsMain;
/**
* Holds the bookmarks tables
*/
private BookmarksTables _bookmarksTables;
/**
* Holds the bookmarks
*/
private Bookmarks _bookmarks;
/**
* Holds the ending notes tables
*/
private NotesTables _endnotesTables = new NotesTables(NoteType.ENDNOTE);
/**
* Holds the footnotes
*/
private Notes _endnotes = new NotesImpl(_endnotesTables);
/**
* Holds the footnotes tables
*/
private NotesTables _footnotesTables = new NotesTables(NoteType.FOOTNOTE);
/**
* Holds the footnotes
*/
private Notes _footnotes = new NotesImpl(_footnotesTables);
/**
* Holds the fields PLCFs
*/
private FieldsTables _fieldsTables;
/**
* Holds the fields
*/
private Fields _fields;
/**
* @param length the max record length allowed for HWPFDocument
*/
public static void setMaxRecordLength(int length) {
MAX_RECORD_LENGTH = length;
}
/**
* @return the max record length allowed for HWPFDocument
*/
public static int getMaxRecordLength() {
return MAX_RECORD_LENGTH;
}
/**
* This constructor loads a Word document from an InputStream.
*
* @param istream The InputStream that contains the Word document.
* @throws IOException If there is an unexpected IOException from the passed
* in InputStream.
* @throws org.apache.poi.EmptyFileException If the given stream is empty
* @throws IllegalStateException a number of other runtime exceptions can be thrown, especially if there are problems with the
* input format
*/
public HWPFDocument(InputStream istream) throws IOException {
//do Ole stuff
this(verifyAndBuildPOIFS(istream));
}
/**
* This constructor loads a Word document from a POIFSFileSystem
*
* @param pfilesystem The POIFSFileSystem that contains the Word document.
* @throws IOException If there is an unexpected IOException from the passed
* in POIFSFileSystem.
* @throws IllegalStateException a number of runtime exceptions can be thrown, especially if there are problems with the
* input format
*/
public HWPFDocument(POIFSFileSystem pfilesystem) throws IOException {
this(pfilesystem.getRoot());
}
/**
* This constructor loads a Word document from a specific point
* in a POIFSFileSystem, probably not the default.
* Used typically to open embedded documents.
*
* @param directory The DirectoryNode that contains the Word document.
* @throws IOException If there is an unexpected IOException from the passed
* in POIFSFileSystem.
* @throws IllegalStateException a number of runtime exceptions can be thrown, especially if there are problems with the
* input format
*/
public HWPFDocument(DirectoryNode directory) throws IOException {
// Load the main stream and FIB
// Also handles HPSF bits
super(directory);
// Is this document too old for us?
if (_fib.getFibBase().getNFib() < 106) {
throw new OldWordFileFormatException("The document is too old - Word 95 or older. Try HWPFOldDocument instead?");
}
// use the fib to determine the name of the table stream.
String name = (_fib.getFibBase().isFWhichTblStm()) ? STREAM_TABLE_1 : STREAM_TABLE_0;
// Grab the table stream.
if (!directory.hasEntryCaseInsensitive(name)) {
throw new IllegalStateException("Table Stream '" + name + "' wasn't found - Either the document is corrupt, or is Word95 (or earlier)");
}
// read in the table stream.
_tableStream = getDocumentEntryBytes(name, _fib.getFibBase().getLKey(), Integer.MAX_VALUE);
_fib.fillVariableFields(_mainStream, _tableStream);
// read in the data stream.
_dataStream = directory.hasEntryCaseInsensitive(STREAM_DATA) ? getDocumentEntryBytes(STREAM_DATA, 0, Integer.MAX_VALUE) : new byte[0];
// Get the cp of the start of text in the main stream
// The latest spec doc says this is always zero!
int fcMin = 0;
//fcMin = _fib.getFcMin()
// Start to load up our standard structures.
_dop = new DocumentProperties(_tableStream, _fib.getFcDop(), _fib.getLcbDop());
_cft = new ComplexFileTable(_mainStream, _tableStream, _fib.getFcClx(), fcMin);
TextPieceTable _tpt = _cft.getTextPieceTable();
// Now load the rest of the properties, which need to be adjusted
// for where text really begin
_cbt = new CHPBinTable(_mainStream, _tableStream, _fib.getFcPlcfbteChpx(), _fib.getLcbPlcfbteChpx(), _tpt);
_pbt = new PAPBinTable(_mainStream, _tableStream, _dataStream, _fib.getFcPlcfbtePapx(), _fib.getLcbPlcfbtePapx(), _tpt);
_text = _tpt.getText();
/*
* in this mode we are preserving PAPX/CHPX structure from file, so text may
* miss from output, and text order may be corrupted
*/
boolean preserveBinTables = false;
try {
preserveBinTables = Boolean.parseBoolean(System.getProperty(PROPERTY_PRESERVE_BIN_TABLES));
} catch (Exception exc) {
// ignore;
}
if (!preserveBinTables) {
_cbt.rebuild(_cft);
_pbt.rebuild(_text, _cft);
}
/*
* Property to disable text rebuilding. In this mode changing the text
* will lead to unpredictable behavior
*/
boolean preserveTextTable = false;
try {
preserveTextTable = Boolean.parseBoolean(System.getProperty(PROPERTY_PRESERVE_TEXT_TABLE));
} catch (Exception exc) {
// ignore;
}
if (!preserveTextTable) {
_cft = new ComplexFileTable();
_tpt = _cft.getTextPieceTable();
final TextPiece textPiece = new SinglentonTextPiece(_text);
_tpt.add(textPiece);
_text = textPiece.getStringBuilder();
}
// Read FSPA and Escher information
// _fspa = new FSPATable(_tableStream, _fib.getFcPlcspaMom(),
// _fib.getLcbPlcspaMom(), getTextTable().getTextPieces());
_fspaHeaders = new FSPATable(_tableStream, _fib,
FSPADocumentPart.HEADER);
_fspaMain = new FSPATable(_tableStream, _fib, FSPADocumentPart.MAIN);
officeArtContent = new OfficeArtContent(_tableStream, _fib.getFcDggInfo(), _fib.getLcbDggInfo());
// read in the pictures stream
_pictures = new PicturesTable(this, _dataStream, _mainStream, _fspaMain, officeArtContent);
// And escher pictures
_officeDrawingsHeaders = new OfficeDrawingsImpl(_fspaHeaders, officeArtContent, _mainStream);
_officeDrawingsMain = new OfficeDrawingsImpl(_fspaMain, officeArtContent, _mainStream);
_st = new SectionTable(_mainStream, _tableStream, _fib.getFcPlcfsed(), _fib.getLcbPlcfsed(), fcMin, _tpt, _fib.getSubdocumentTextStreamLength(SubdocumentType.MAIN));
_ss = new StyleSheet(_tableStream, _fib.getFcStshf());
_ft = new FontTable(_tableStream, _fib.getFcSttbfffn(), _fib.getLcbSttbfffn());
int listOffset = _fib.getFcPlfLst();
// int lfoOffset = _fib.getFcPlfLfo();
if (listOffset != 0 && _fib.getLcbPlfLst() != 0) {
_lt = new ListTables(_tableStream, listOffset, _fib.getFcPlfLfo(),
_fib.getLcbPlfLfo());
}
int sbtOffset = _fib.getFcSttbSavedBy();
int sbtLength = _fib.getLcbSttbSavedBy();
if (sbtOffset != 0 && sbtLength != 0) {
_sbt = new SavedByTable(_tableStream, sbtOffset, sbtLength);
}
int rmarkOffset = _fib.getFcSttbfRMark();
int rmarkLength = _fib.getLcbSttbfRMark();
if (rmarkOffset != 0 && rmarkLength != 0) {
_rmat = new RevisionMarkAuthorTable(_tableStream, rmarkOffset, rmarkLength);
}
_bookmarksTables = new BookmarksTables(_tableStream, _fib);
_bookmarks = new BookmarksImpl(_bookmarksTables);
_endnotesTables = new NotesTables(NoteType.ENDNOTE, _tableStream, _fib);
_endnotes = new NotesImpl(_endnotesTables);
_footnotesTables = new NotesTables(NoteType.FOOTNOTE, _tableStream, _fib);
_footnotes = new NotesImpl(_footnotesTables);
_fieldsTables = new FieldsTables(_tableStream, _fib);
_fields = new FieldsImpl(_fieldsTables);
}
@Override
@Internal
public TextPieceTable getTextTable() {
return _cft.getTextPieceTable();
}
@Internal
@Override
public StringBuilder getText() {
return _text;
}
public DocumentProperties getDocProperties() {
return _dop;
}
@Override
public Range getOverallRange() {
return new Range(0, _text.length(), this);
}
/**
* Returns the range which covers the whole of the document, but excludes
* any headers and footers.
*/
@Override
public Range getRange() {
// // First up, trigger a full-recalculate
// // Needed in case of deletes etc
// getOverallRange();
//
// if ( getFileInformationBlock().isFComplex() )
// {
// /*
// * Page 31:
// *
// * main document must be found by examining the piece table entries
// * from the 0th piece table entry from the piece table entry that
// * describes cp=fib.ccpText.
// */
// // TODO: review
// return new Range( _cpSplit.getMainDocumentStart(),
// _cpSplit.getMainDocumentEnd(), this );
// }
//
// /*
// * Page 31:
// *
// * "In a non-complex file, this means text of the: main document
// begins
// * at fib.fcMin in the file and continues through
// * fib.fcMin+fib.ccpText."
// */
// int bytesStart = getFileInformationBlock().getFcMin();
//
// int charsStart = getTextTable().getCharIndex( bytesStart );
// int charsEnd = charsStart
// + getFileInformationBlock().getSubdocumentTextStreamLength(
// SubdocumentType.MAIN );
// it seems much simpler -- sergey
return getRange(SubdocumentType.MAIN);
}
private Range getRange(SubdocumentType subdocument) {
int startCp = 0;
for (SubdocumentType previos : SubdocumentType.ORDERED) {
int length = getFileInformationBlock()
.getSubdocumentTextStreamLength(previos);
if (subdocument == previos) {
return new Range(startCp, startCp + length, this);
}
startCp += length;
}
throw new UnsupportedOperationException(
"Subdocument type not supported: " + subdocument);
}
/**
* Returns the {@link Range} which covers all the Footnotes.
*
* @return the {@link Range} which covers all the Footnotes.
*/
public Range getFootnoteRange() {
return getRange(SubdocumentType.FOOTNOTE);
}
/**
* Returns the {@link Range} which covers all endnotes.
*
* @return the {@link Range} which covers all endnotes.
*/
public Range getEndnoteRange() {
return getRange(SubdocumentType.ENDNOTE);
}
/**
* Returns the {@link Range} which covers all annotations.
*
* @return the {@link Range} which covers all annotations.
*/
public Range getCommentsRange() {
return getRange(SubdocumentType.ANNOTATION);
}
/**
* Returns the {@link Range} which covers all textboxes.
*
* @return the {@link Range} which covers all textboxes.
*/
public Range getMainTextboxRange() {
return getRange(SubdocumentType.TEXTBOX);
}
/**
* Returns the range which covers all "Header Stories".
* A header story contains a header, footer, end note
* separators and footnote separators.
*/
public Range getHeaderStoryRange() {
return getRange(SubdocumentType.HEADER);
}
/**
* Returns the character length of a document.
*
* @return the character length of a document
*/
public int characterLength() {
return _text.length();
}
/**
* Gets a reference to the saved -by table, which holds the save history for the document.
*
* @return the saved-by table.
*/
@Internal
public SavedByTable getSavedByTable() {
return _sbt;
}
/**
* Gets a reference to the revision mark author table, which holds the revision mark authors for the document.
*
* @return the saved-by table.
*/
@Internal
public RevisionMarkAuthorTable getRevisionMarkAuthorTable() {
return _rmat;
}
/**
* @return PicturesTable object, that is able to extract images from this document
*/
public PicturesTable getPicturesTable() {
return _pictures;
}
@Internal
public OfficeArtContent getOfficeArtContent() {
return officeArtContent;
}
public OfficeDrawings getOfficeDrawingsHeaders() {
return _officeDrawingsHeaders;
}
public OfficeDrawings getOfficeDrawingsMain() {
return _officeDrawingsMain;
}
/**
* @return user-friendly interface to access document bookmarks
*/
public Bookmarks getBookmarks() {
return _bookmarks;
}
/**
* @return user-friendly interface to access document endnotes
*/
public Notes getEndnotes() {
return _endnotes;
}
/**
* @return user-friendly interface to access document footnotes
*/
public Notes getFootnotes() {
return _footnotes;
}
/**
* Returns user-friendly interface to access document {@link Field}s
*
* @return user-friendly interface to access document {@link Field}s
*/
public Fields getFields() {
return _fields;
}
/**
* Write out the word file that is represented by this class, to the
* currently open {@link File}, via the writeable {@link POIFSFileSystem}
* it was opened as.
*
* <p>This will fail (with an {@link IllegalStateException} if the
* Document was opened read-only, opened from an {@link InputStream}
* instead of a File, or if this is not the root document. For those cases,
* you must use {@link #write(OutputStream)} or {@link #write(File)} to
* write to a brand new document.
*
* @since 3.15
*/
@Override
public void write() throws IOException {
validateInPlaceWritePossible();
// Update the Document+Properties streams in the file
write(getDirectory().getFileSystem(), false);
// Sync with the File on disk
getDirectory().getFileSystem().writeFilesystem();
}
/**
* Writes out the word file that is represented by an instance of this class.
* <p>
* If the {@link File} exists, it will be replaced, otherwise a new one
* will be created
*
* @param newFile The File to write to.
* @throws IOException If there is an unexpected IOException from writing
* to the File.
* @since 3.15 beta 3
*/
@Override
public void write(File newFile) throws IOException {
POIFSFileSystem pfs = POIFSFileSystem.create(newFile);
write(pfs, true);
pfs.writeFilesystem();
}
/**
* Writes out the word file that is represented by an instance of this class.
* <p>
* For better performance when writing to files, use {@link #write(File)}.
* If {@code stream} has a high cost/latency associated with each written byte,
* consider wrapping the OutputStream in a {@link java.io.BufferedOutputStream}
* to improve write performance.
*
* @param out The OutputStream to write to.
* @throws IOException If there is an unexpected IOException from the passed
* in OutputStream.
*/
@Override
public void write(OutputStream out) throws IOException {
POIFSFileSystem pfs = new POIFSFileSystem();
write(pfs, true);
pfs.writeFilesystem(out);
}
private void write(POIFSFileSystem pfs, boolean copyOtherEntries) throws IOException {
// clear the offsets and sizes in our FileInformationBlock.
_fib.clearOffsetsSizes();
// determine the FileInformationBLock size
int fibSize = _fib.getSize();
fibSize += POIFSConstants.SMALLER_BIG_BLOCK_SIZE - (fibSize % POIFSConstants.SMALLER_BIG_BLOCK_SIZE);
// initialize our streams for writing.
HWPFFileSystem docSys = new HWPFFileSystem();
ByteArrayOutputStream wordDocumentStream = docSys.getStream(STREAM_WORD_DOCUMENT);
ByteArrayOutputStream tableStream = docSys.getStream(STREAM_TABLE_1);
// preserve space for the FileInformationBlock because we will be writing
// it after we write everything else.
byte[] placeHolder = IOUtils.safelyAllocate(fibSize, MAX_RECORD_LENGTH);
wordDocumentStream.write(placeHolder);
int mainOffset = wordDocumentStream.size();
int tableOffset = 0;
// write out EncryptionInfo
updateEncryptionInfo();
EncryptionInfo ei = getEncryptionInfo();
if (ei != null) {
byte[] buf = new byte[1000];
LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0);
leos.writeShort(ei.getVersionMajor());
leos.writeShort(ei.getVersionMinor());
if (ei.getEncryptionMode() == EncryptionMode.cryptoAPI) {
leos.writeInt(ei.getEncryptionFlags());
}
((EncryptionRecord) ei.getHeader()).write(leos);
((EncryptionRecord) ei.getVerifier()).write(leos);
tableStream.write(buf, 0, leos.getWriteIndex());
tableOffset += leos.getWriteIndex();
_fib.getFibBase().setLKey(tableOffset);
}
// write out the StyleSheet.
_fib.setFcStshf(tableOffset);
_ss.writeTo(tableStream);
_fib.setLcbStshf(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
// get fcMin and fcMac because we will be writing the actual text with the
// complex table.
/*
* clx (encoding of the sprm lists for a complex file and piece table
* for an any file) Written immediately after the end of the previously
* recorded structure. This is recorded in all Word documents
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 23 of 210
*/
// write out the Complex table, includes text.
_fib.setFcClx(tableOffset);
_cft.writeTo(wordDocumentStream, tableStream);
_fib.setLcbClx(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
int fcMac = wordDocumentStream.size();
/*
* dop (document properties record) Written immediately after the end of
* the previously recorded structure. This is recorded in all Word
* documents
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 23 of 210
*/
// write out the DocumentProperties.
_fib.setFcDop(tableOffset);
_dop.writeTo(tableStream);
_fib.setLcbDop(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
/*
* plcfBkmkf (table recording beginning CPs of bookmarks) Written
* immediately after the sttbfBkmk, if the document contains bookmarks.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
if (_bookmarksTables != null) {
_bookmarksTables.writePlcfBkmkf(_fib, tableStream);
tableOffset = tableStream.size();
}
/*
* plcfBkmkl (table recording limit CPs of bookmarks) Written
* immediately after the plcfBkmkf, if the document contains bookmarks.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
if (_bookmarksTables != null) {
_bookmarksTables.writePlcfBkmkl(_fib, tableStream);
tableOffset = tableStream.size();
}
/*
* plcfbteChpx (bin table for CHP FKPs) Written immediately after the
* previously recorded table. This is recorded in all Word documents.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
// write out the CHPBinTable.
_fib.setFcPlcfbteChpx(tableOffset);
_cbt.writeTo(wordDocumentStream, tableStream, mainOffset, _cft.getTextPieceTable());
_fib.setLcbPlcfbteChpx(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
/*
* plcfbtePapx (bin table for PAP FKPs) Written immediately after the
* plcfbteChpx. This is recorded in all Word documents.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
// write out the PAPBinTable.
_fib.setFcPlcfbtePapx(tableOffset);
// Right now we don't know how to save dataStream modifications, so we can just pipe them to a black hole.
_pbt.writeTo(wordDocumentStream, tableStream, new ByteArrayOutputStream(), _cft.getTextPieceTable());
_fib.setLcbPlcfbtePapx(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
/*
* plcfendRef (endnote reference position table) Written immediately
* after the previously recorded table if the document contains endnotes
*
* plcfendTxt (endnote text position table) Written immediately after
* the plcfendRef if the document contains endnotes
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
_endnotesTables.writeRef(_fib, tableStream);
_endnotesTables.writeTxt(_fib, tableStream);
tableOffset = tableStream.size();
/*
* plcffld*** (table of field positions and statuses for annotation
* subdocument) Written immediately after the previously recorded table,
* if the ******* subdocument contains fields.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
if (_fieldsTables != null) {
_fieldsTables.write(_fib, tableStream);
tableOffset = tableStream.size();
}
/*
* plcffndRef (footnote reference position table) Written immediately
* after the stsh if the document contains footnotes
*
* plcffndTxt (footnote text position table) Written immediately after
* the plcffndRef if the document contains footnotes
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 24 of 210
*/
_footnotesTables.writeRef(_fib, tableStream);
_footnotesTables.writeTxt(_fib, tableStream);
tableOffset = tableStream.size();
/*
* plcfsed (section table) Written immediately after the previously
* recorded table. Recorded in all Word documents
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 25 of 210
*/
// write out the SectionTable.
_fib.setFcPlcfsed(tableOffset);
_st.writeTo(wordDocumentStream, tableStream);
_fib.setLcbPlcfsed(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
// write out the list tables
if (_lt != null) {
/*
* plcflst (list formats) Written immediately after the end of the
* previously recorded, if there are any lists defined in the
* document. This begins with a short count of LSTF structures
* followed by those LSTF structures. This is immediately followed
* by the allocated data hanging off the LSTFs. This data consists
* of the array of LVLs for each LSTF. (Each LVL consists of an LVLF
* followed by two grpprls and an XST.)
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 25 of 210
*/
_lt.writeListDataTo(_fib, tableStream);
tableOffset = tableStream.size();
/*
* plflfo (more list formats) Written immediately after the end of
* the plcflst and its accompanying data, if there are any lists
* defined in the document. This consists first of a PL of LFO
* records, followed by the allocated data (if any) hanging off the
* LFOs. The allocated data consists of the array of LFOLVLFs for
* each LFO (and each LFOLVLF is immediately followed by some LVLs).
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 26 of 210
*/
_lt.writeListOverridesTo(_fib, tableStream);
tableOffset = tableStream.size();
}
/*
* sttbfBkmk (table of bookmark name strings) Written immediately after
* the previously recorded table, if the document contains bookmarks.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 27 of 210
*/
if (_bookmarksTables != null) {
_bookmarksTables.writeSttbfBkmk(_fib, tableStream);
tableOffset = tableStream.size();
}
/*
* sttbSavedBy (last saved by string table) Written immediately after
* the previously recorded table.
*
* Microsoft Office Word 97-2007 Binary File Format (.doc)
* Specification; Page 27 of 210
*/
// write out the saved-by table.
if (_sbt != null) {
_fib.setFcSttbSavedBy(tableOffset);
_sbt.writeTo(tableStream);
_fib.setLcbSttbSavedBy(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
}
// write out the revision mark authors table.
if (_rmat != null) {
_fib.setFcSttbfRMark(tableOffset);
_rmat.writeTo(tableStream);
_fib.setLcbSttbfRMark(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
}
// write out the FontTable.
_fib.setFcSttbfffn(tableOffset);
_ft.writeTo(tableStream);
_fib.setLcbSttbfffn(tableStream.size() - tableOffset);
tableOffset = tableStream.size();
// set some variables in the FileInformationBlock.
_fib.getFibBase().setFcMin(mainOffset);
_fib.getFibBase().setFcMac(fcMac);
_fib.setCbMac(wordDocumentStream.size());
// make sure that the table, doc and data streams use big blocks.
byte[] mainBuf = fillUp4096(wordDocumentStream);
// Table1 stream will be used
_fib.getFibBase().setFWhichTblStm(true);
// write out the FileInformationBlock.
//_fib.serialize(mainBuf, 0);
_fib.writeTo(mainBuf, tableStream);
byte[] tableBuf = fillUp4096(tableStream);
byte[] dataBuf = fillUp4096(_dataStream);
// Create a new document - ignoring the order of the old entries
if (ei == null) {
write(pfs, mainBuf, STREAM_WORD_DOCUMENT);
write(pfs, tableBuf, STREAM_TABLE_1);
write(pfs, dataBuf, STREAM_DATA);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream(100000);
encryptBytes(mainBuf, FIB_BASE_LEN, bos);
write(pfs, bos.toByteArray(), STREAM_WORD_DOCUMENT);
bos.reset();
encryptBytes(tableBuf, _fib.getFibBase().getLKey(), bos);
write(pfs, bos.toByteArray(), STREAM_TABLE_1);
bos.reset();
encryptBytes(dataBuf, 0, bos);
write(pfs, bos.toByteArray(), STREAM_DATA);
bos.reset();
}
writeProperties(pfs);
if (copyOtherEntries && ei == null) {
// For encrypted files:
// The ObjectPool storage MUST NOT be present and if the file contains OLE objects, the storage
// objects for the OLE objects MUST be stored in the Data stream as specified in sprmCPicLocation.
DirectoryNode newRoot = pfs.getRoot();
_objectPool.writeTo(newRoot);
for (Entry entry : getDirectory()) {
String entryName = entry.getName();
if (!(
STREAM_WORD_DOCUMENT.equals(entryName) ||
STREAM_TABLE_0.equals(entryName) ||
STREAM_TABLE_1.equals(entryName) ||
STREAM_DATA.equals(entryName) ||
STREAM_OBJECT_POOL.equals(entryName) ||
SummaryInformation.DEFAULT_STREAM_NAME.equals(entryName) ||
DocumentSummaryInformation.DEFAULT_STREAM_NAME.equals(entryName)
)) {
EntryUtils.copyNodeRecursively(entry, newRoot);
}
}
}
/*
* since we updated all references in FIB and etc, using new arrays to
* access data
*/
replaceDirectory(pfs.getRoot());
this._tableStream = tableStream.toByteArray();
this._dataStream = dataBuf;
}
private void encryptBytes(byte[] plain, int encryptOffset, OutputStream bos) throws IOException {
try {
EncryptionInfo ei = getEncryptionInfo();
Encryptor enc = ei.getEncryptor();
enc.setChunkSize(RC4_REKEYING_INTERVAL);
ChunkedCipherOutputStream os = enc.getDataStream(bos, 0);
if (encryptOffset > 0) {
os.writePlain(plain, 0, encryptOffset);
}
os.write(plain, encryptOffset, plain.length - encryptOffset);
os.close();
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
private static byte[] fillUp4096(byte[] buf) {
if (buf == null) {
return new byte[4096];
} else if (buf.length < 4096) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(4096);
bos.write(buf, 0, buf.length);
return fillUp4096(bos);
} else {
return buf;
}
}
private static byte[] fillUp4096(ByteArrayOutputStream bos) {
int fillSize = 4096 - bos.size();
if (fillSize > 0) {
bos.write(new byte[fillSize], 0, fillSize);
}
return bos.toByteArray();
}
private static void write(POIFSFileSystem pfs, byte[] data, String name) throws IOException {
pfs.createOrUpdateDocument(new ByteArrayInputStream(data), name);
}
@Internal
public byte[] getDataStream() {
return _dataStream;
}
@Internal
public byte[] getTableStream() {
return _tableStream;
}
public int registerList(HWPFList list) {
if (_lt == null) {
_lt = new ListTables();
}
return _lt.addList(list.getListData(), list.getLFO(),
list.getLFOData());
}
public void delete(int start, int length) {
Range r = new Range(start, start + length, this);
r.delete();
}
}
|
googleapis/google-cloud-java | 37,391 | java-securitycenter/proto-google-cloud-securitycenter-v1/src/main/java/com/google/cloud/securitycenter/v1/ListMuteConfigsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v1/securitycenter_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycenter.v1;
/**
*
*
* <pre>
* Response message for listing mute configs.
* </pre>
*
* Protobuf type {@code google.cloud.securitycenter.v1.ListMuteConfigsResponse}
*/
public final class ListMuteConfigsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1.ListMuteConfigsResponse)
ListMuteConfigsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListMuteConfigsResponse.newBuilder() to construct.
private ListMuteConfigsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListMuteConfigsResponse() {
muteConfigs_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListMuteConfigsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListMuteConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListMuteConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.class,
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.Builder.class);
}
public static final int MUTE_CONFIGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.securitycenter.v1.MuteConfig> muteConfigs_;
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.securitycenter.v1.MuteConfig> getMuteConfigsList() {
return muteConfigs_;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.securitycenter.v1.MuteConfigOrBuilder>
getMuteConfigsOrBuilderList() {
return muteConfigs_;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public int getMuteConfigsCount() {
return muteConfigs_.size();
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v1.MuteConfig getMuteConfigs(int index) {
return muteConfigs_.get(index);
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v1.MuteConfigOrBuilder getMuteConfigsOrBuilder(int index) {
return muteConfigs_.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 < muteConfigs_.size(); i++) {
output.writeMessage(1, muteConfigs_.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 < muteConfigs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, muteConfigs_.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.securitycenter.v1.ListMuteConfigsResponse)) {
return super.equals(obj);
}
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse other =
(com.google.cloud.securitycenter.v1.ListMuteConfigsResponse) obj;
if (!getMuteConfigsList().equals(other.getMuteConfigsList())) 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 (getMuteConfigsCount() > 0) {
hash = (37 * hash) + MUTE_CONFIGS_FIELD_NUMBER;
hash = (53 * hash) + getMuteConfigsList().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.securitycenter.v1.ListMuteConfigsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse 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 listing mute configs.
* </pre>
*
* Protobuf type {@code google.cloud.securitycenter.v1.ListMuteConfigsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1.ListMuteConfigsResponse)
com.google.cloud.securitycenter.v1.ListMuteConfigsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListMuteConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListMuteConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.class,
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.Builder.class);
}
// Construct using com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (muteConfigsBuilder_ == null) {
muteConfigs_ = java.util.Collections.emptyList();
} else {
muteConfigs_ = null;
muteConfigsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_ListMuteConfigsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListMuteConfigsResponse getDefaultInstanceForType() {
return com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListMuteConfigsResponse build() {
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListMuteConfigsResponse buildPartial() {
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse result =
new com.google.cloud.securitycenter.v1.ListMuteConfigsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.securitycenter.v1.ListMuteConfigsResponse result) {
if (muteConfigsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
muteConfigs_ = java.util.Collections.unmodifiableList(muteConfigs_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.muteConfigs_ = muteConfigs_;
} else {
result.muteConfigs_ = muteConfigsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.securitycenter.v1.ListMuteConfigsResponse 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.securitycenter.v1.ListMuteConfigsResponse) {
return mergeFrom((com.google.cloud.securitycenter.v1.ListMuteConfigsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.securitycenter.v1.ListMuteConfigsResponse other) {
if (other == com.google.cloud.securitycenter.v1.ListMuteConfigsResponse.getDefaultInstance())
return this;
if (muteConfigsBuilder_ == null) {
if (!other.muteConfigs_.isEmpty()) {
if (muteConfigs_.isEmpty()) {
muteConfigs_ = other.muteConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMuteConfigsIsMutable();
muteConfigs_.addAll(other.muteConfigs_);
}
onChanged();
}
} else {
if (!other.muteConfigs_.isEmpty()) {
if (muteConfigsBuilder_.isEmpty()) {
muteConfigsBuilder_.dispose();
muteConfigsBuilder_ = null;
muteConfigs_ = other.muteConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
muteConfigsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMuteConfigsFieldBuilder()
: null;
} else {
muteConfigsBuilder_.addAllMessages(other.muteConfigs_);
}
}
}
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.securitycenter.v1.MuteConfig m =
input.readMessage(
com.google.cloud.securitycenter.v1.MuteConfig.parser(), extensionRegistry);
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.add(m);
} else {
muteConfigsBuilder_.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.securitycenter.v1.MuteConfig> muteConfigs_ =
java.util.Collections.emptyList();
private void ensureMuteConfigsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
muteConfigs_ =
new java.util.ArrayList<com.google.cloud.securitycenter.v1.MuteConfig>(muteConfigs_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v1.MuteConfig,
com.google.cloud.securitycenter.v1.MuteConfig.Builder,
com.google.cloud.securitycenter.v1.MuteConfigOrBuilder>
muteConfigsBuilder_;
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public java.util.List<com.google.cloud.securitycenter.v1.MuteConfig> getMuteConfigsList() {
if (muteConfigsBuilder_ == null) {
return java.util.Collections.unmodifiableList(muteConfigs_);
} else {
return muteConfigsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public int getMuteConfigsCount() {
if (muteConfigsBuilder_ == null) {
return muteConfigs_.size();
} else {
return muteConfigsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v1.MuteConfig getMuteConfigs(int index) {
if (muteConfigsBuilder_ == null) {
return muteConfigs_.get(index);
} else {
return muteConfigsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder setMuteConfigs(int index, com.google.cloud.securitycenter.v1.MuteConfig value) {
if (muteConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMuteConfigsIsMutable();
muteConfigs_.set(index, value);
onChanged();
} else {
muteConfigsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder setMuteConfigs(
int index, com.google.cloud.securitycenter.v1.MuteConfig.Builder builderForValue) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.set(index, builderForValue.build());
onChanged();
} else {
muteConfigsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(com.google.cloud.securitycenter.v1.MuteConfig value) {
if (muteConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMuteConfigsIsMutable();
muteConfigs_.add(value);
onChanged();
} else {
muteConfigsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(int index, com.google.cloud.securitycenter.v1.MuteConfig value) {
if (muteConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMuteConfigsIsMutable();
muteConfigs_.add(index, value);
onChanged();
} else {
muteConfigsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(
com.google.cloud.securitycenter.v1.MuteConfig.Builder builderForValue) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.add(builderForValue.build());
onChanged();
} else {
muteConfigsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(
int index, com.google.cloud.securitycenter.v1.MuteConfig.Builder builderForValue) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.add(index, builderForValue.build());
onChanged();
} else {
muteConfigsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder addAllMuteConfigs(
java.lang.Iterable<? extends com.google.cloud.securitycenter.v1.MuteConfig> values) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, muteConfigs_);
onChanged();
} else {
muteConfigsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder clearMuteConfigs() {
if (muteConfigsBuilder_ == null) {
muteConfigs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
muteConfigsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public Builder removeMuteConfigs(int index) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.remove(index);
onChanged();
} else {
muteConfigsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v1.MuteConfig.Builder getMuteConfigsBuilder(int index) {
return getMuteConfigsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v1.MuteConfigOrBuilder getMuteConfigsOrBuilder(
int index) {
if (muteConfigsBuilder_ == null) {
return muteConfigs_.get(index);
} else {
return muteConfigsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.securitycenter.v1.MuteConfigOrBuilder>
getMuteConfigsOrBuilderList() {
if (muteConfigsBuilder_ != null) {
return muteConfigsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(muteConfigs_);
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v1.MuteConfig.Builder addMuteConfigsBuilder() {
return getMuteConfigsFieldBuilder()
.addBuilder(com.google.cloud.securitycenter.v1.MuteConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v1.MuteConfig.Builder addMuteConfigsBuilder(int index) {
return getMuteConfigsFieldBuilder()
.addBuilder(index, com.google.cloud.securitycenter.v1.MuteConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1.MuteConfig mute_configs = 1;</code>
*/
public java.util.List<com.google.cloud.securitycenter.v1.MuteConfig.Builder>
getMuteConfigsBuilderList() {
return getMuteConfigsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v1.MuteConfig,
com.google.cloud.securitycenter.v1.MuteConfig.Builder,
com.google.cloud.securitycenter.v1.MuteConfigOrBuilder>
getMuteConfigsFieldBuilder() {
if (muteConfigsBuilder_ == null) {
muteConfigsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v1.MuteConfig,
com.google.cloud.securitycenter.v1.MuteConfig.Builder,
com.google.cloud.securitycenter.v1.MuteConfigOrBuilder>(
muteConfigs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
muteConfigs_ = null;
}
return muteConfigsBuilder_;
}
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.securitycenter.v1.ListMuteConfigsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListMuteConfigsResponse)
private static final com.google.cloud.securitycenter.v1.ListMuteConfigsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v1.ListMuteConfigsResponse();
}
public static com.google.cloud.securitycenter.v1.ListMuteConfigsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListMuteConfigsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListMuteConfigsResponse>() {
@java.lang.Override
public ListMuteConfigsResponse 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<ListMuteConfigsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListMuteConfigsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.ListMuteConfigsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,304 | java-functions/proto-google-cloud-functions-v2beta/src/main/java/com/google/cloud/functions/v2beta/SecretEnvVar.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/v2beta/functions.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.functions.v2beta;
/**
*
*
* <pre>
* Configuration for a secret environment variable. It has the information
* necessary to fetch the secret value from secret manager and expose it as an
* environment variable.
* </pre>
*
* Protobuf type {@code google.cloud.functions.v2beta.SecretEnvVar}
*/
public final class SecretEnvVar extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.functions.v2beta.SecretEnvVar)
SecretEnvVarOrBuilder {
private static final long serialVersionUID = 0L;
// Use SecretEnvVar.newBuilder() to construct.
private SecretEnvVar(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SecretEnvVar() {
key_ = "";
projectId_ = "";
secret_ = "";
version_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SecretEnvVar();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.functions.v2beta.FunctionsProto
.internal_static_google_cloud_functions_v2beta_SecretEnvVar_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.functions.v2beta.FunctionsProto
.internal_static_google_cloud_functions_v2beta_SecretEnvVar_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.functions.v2beta.SecretEnvVar.class,
com.google.cloud.functions.v2beta.SecretEnvVar.Builder.class);
}
public static final int KEY_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object key_ = "";
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @return The key.
*/
@java.lang.Override
public java.lang.String getKey() {
java.lang.Object ref = key_;
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();
key_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @return The bytes for key.
*/
@java.lang.Override
public com.google.protobuf.ByteString getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROJECT_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object projectId_ = "";
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @return The projectId.
*/
@java.lang.Override
public java.lang.String getProjectId() {
java.lang.Object ref = projectId_;
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();
projectId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @return The bytes for projectId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectIdBytes() {
java.lang.Object ref = projectId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
projectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SECRET_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object secret_ = "";
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @return The secret.
*/
@java.lang.Override
public java.lang.String getSecret() {
java.lang.Object ref = secret_;
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();
secret_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @return The bytes for secret.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSecretBytes() {
java.lang.Object ref = secret_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
secret_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object version_ = "";
/**
*
*
* <pre>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</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>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</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;
}
}
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(key_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, key_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(projectId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, projectId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(secret_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, secret_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, version_);
}
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(key_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, key_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(projectId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, projectId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(secret_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, secret_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, version_);
}
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.v2beta.SecretEnvVar)) {
return super.equals(obj);
}
com.google.cloud.functions.v2beta.SecretEnvVar other =
(com.google.cloud.functions.v2beta.SecretEnvVar) obj;
if (!getKey().equals(other.getKey())) return false;
if (!getProjectId().equals(other.getProjectId())) return false;
if (!getSecret().equals(other.getSecret())) return false;
if (!getVersion().equals(other.getVersion())) 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) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
hash = (37 * hash) + PROJECT_ID_FIELD_NUMBER;
hash = (53 * hash) + getProjectId().hashCode();
hash = (37 * hash) + SECRET_FIELD_NUMBER;
hash = (53 * hash) + getSecret().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.functions.v2beta.SecretEnvVar parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar 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.v2beta.SecretEnvVar parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar 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.v2beta.SecretEnvVar parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar 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.v2beta.SecretEnvVar parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar 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.v2beta.SecretEnvVar parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.functions.v2beta.SecretEnvVar 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.v2beta.SecretEnvVar prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Configuration for a secret environment variable. It has the information
* necessary to fetch the secret value from secret manager and expose it as an
* environment variable.
* </pre>
*
* Protobuf type {@code google.cloud.functions.v2beta.SecretEnvVar}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.functions.v2beta.SecretEnvVar)
com.google.cloud.functions.v2beta.SecretEnvVarOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.functions.v2beta.FunctionsProto
.internal_static_google_cloud_functions_v2beta_SecretEnvVar_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.functions.v2beta.FunctionsProto
.internal_static_google_cloud_functions_v2beta_SecretEnvVar_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.functions.v2beta.SecretEnvVar.class,
com.google.cloud.functions.v2beta.SecretEnvVar.Builder.class);
}
// Construct using com.google.cloud.functions.v2beta.SecretEnvVar.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
key_ = "";
projectId_ = "";
secret_ = "";
version_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.functions.v2beta.FunctionsProto
.internal_static_google_cloud_functions_v2beta_SecretEnvVar_descriptor;
}
@java.lang.Override
public com.google.cloud.functions.v2beta.SecretEnvVar getDefaultInstanceForType() {
return com.google.cloud.functions.v2beta.SecretEnvVar.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.functions.v2beta.SecretEnvVar build() {
com.google.cloud.functions.v2beta.SecretEnvVar result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.functions.v2beta.SecretEnvVar buildPartial() {
com.google.cloud.functions.v2beta.SecretEnvVar result =
new com.google.cloud.functions.v2beta.SecretEnvVar(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.functions.v2beta.SecretEnvVar result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.key_ = key_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.projectId_ = projectId_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.secret_ = secret_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.version_ = version_;
}
}
@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.v2beta.SecretEnvVar) {
return mergeFrom((com.google.cloud.functions.v2beta.SecretEnvVar) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.functions.v2beta.SecretEnvVar other) {
if (other == com.google.cloud.functions.v2beta.SecretEnvVar.getDefaultInstance()) return this;
if (!other.getKey().isEmpty()) {
key_ = other.key_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getProjectId().isEmpty()) {
projectId_ = other.projectId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getSecret().isEmpty()) {
secret_ = other.secret_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
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:
{
key_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
projectId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
secret_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
version_ = 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 key_ = "";
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @return The key.
*/
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @return The bytes for key.
*/
public com.google.protobuf.ByteString getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @param value The key to set.
* @return This builder for chaining.
*/
public Builder setKey(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearKey() {
key_ = getDefaultInstance().getKey();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the environment variable.
* </pre>
*
* <code>string key = 1;</code>
*
* @param value The bytes for key to set.
* @return This builder for chaining.
*/
public Builder setKeyBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
key_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object projectId_ = "";
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @return The projectId.
*/
public java.lang.String getProjectId() {
java.lang.Object ref = projectId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
projectId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @return The bytes for projectId.
*/
public com.google.protobuf.ByteString getProjectIdBytes() {
java.lang.Object ref = projectId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
projectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @param value The projectId to set.
* @return This builder for chaining.
*/
public Builder setProjectId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
projectId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearProjectId() {
projectId_ = getDefaultInstance().getProjectId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project identifier (preferably project number but can also be the
* project ID) of the project that contains the secret. If not set, it is
* assumed that the secret is in the same project as the function.
* </pre>
*
* <code>string project_id = 2;</code>
*
* @param value The bytes for projectId to set.
* @return This builder for chaining.
*/
public Builder setProjectIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
projectId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object secret_ = "";
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @return The secret.
*/
public java.lang.String getSecret() {
java.lang.Object ref = secret_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
secret_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @return The bytes for secret.
*/
public com.google.protobuf.ByteString getSecretBytes() {
java.lang.Object ref = secret_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
secret_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @param value The secret to set.
* @return This builder for chaining.
*/
public Builder setSecret(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
secret_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearSecret() {
secret_ = getDefaultInstance().getSecret();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the secret in secret manager (not the full resource name).
* </pre>
*
* <code>string secret = 3;</code>
*
* @param value The bytes for secret to set.
* @return This builder for chaining.
*/
public Builder setSecretBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
secret_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object version_ = "";
/**
*
*
* <pre>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</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>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</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>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</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_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearVersion() {
version_ = getDefaultInstance().getVersion();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Version of the secret (version number or the string 'latest'). It is
* recommended to use a numeric version for secret environment variables as
* any updates to the secret value is not reflected until new instances
* start.
* </pre>
*
* <code>string version = 4;</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_ |= 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.functions.v2beta.SecretEnvVar)
}
// @@protoc_insertion_point(class_scope:google.cloud.functions.v2beta.SecretEnvVar)
private static final com.google.cloud.functions.v2beta.SecretEnvVar DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.functions.v2beta.SecretEnvVar();
}
public static com.google.cloud.functions.v2beta.SecretEnvVar getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SecretEnvVar> PARSER =
new com.google.protobuf.AbstractParser<SecretEnvVar>() {
@java.lang.Override
public SecretEnvVar 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<SecretEnvVar> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SecretEnvVar> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.functions.v2beta.SecretEnvVar getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,358 | java-contact-center-insights/proto-google-cloud-contact-center-insights-v1/src/main/java/com/google/cloud/contactcenterinsights/v1/ListAnalysesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/contactcenterinsights/v1/contact_center_insights.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.contactcenterinsights.v1;
/**
*
*
* <pre>
* The response to list analyses.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.ListAnalysesResponse}
*/
public final class ListAnalysesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.ListAnalysesResponse)
ListAnalysesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAnalysesResponse.newBuilder() to construct.
private ListAnalysesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAnalysesResponse() {
analyses_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAnalysesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListAnalysesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListAnalysesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.class,
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.Builder.class);
}
public static final int ANALYSES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.contactcenterinsights.v1.Analysis> analyses_;
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.contactcenterinsights.v1.Analysis> getAnalysesList() {
return analyses_;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder>
getAnalysesOrBuilderList() {
return analyses_;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
@java.lang.Override
public int getAnalysesCount() {
return analyses_.size();
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.Analysis getAnalyses(int index) {
return analyses_.get(index);
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder getAnalysesOrBuilder(
int index) {
return analyses_.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 < analyses_.size(); i++) {
output.writeMessage(1, analyses_.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 < analyses_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, analyses_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse)) {
return super.equals(obj);
}
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse other =
(com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse) obj;
if (!getAnalysesList().equals(other.getAnalysesList())) 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 (getAnalysesCount() > 0) {
hash = (37 * hash) + ANALYSES_FIELD_NUMBER;
hash = (53 * hash) + getAnalysesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse 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.ListAnalysesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse 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.ListAnalysesResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse 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.ListAnalysesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse 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.ListAnalysesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse 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.ListAnalysesResponse 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.ListAnalysesResponse 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.ListAnalysesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response to list analyses.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.ListAnalysesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.ListAnalysesResponse)
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListAnalysesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListAnalysesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.class,
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.Builder.class);
}
// Construct using com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (analysesBuilder_ == null) {
analyses_ = java.util.Collections.emptyList();
} else {
analyses_ = null;
analysesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListAnalysesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse
getDefaultInstanceForType() {
return com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse build() {
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse buildPartial() {
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse result =
new com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse result) {
if (analysesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
analyses_ = java.util.Collections.unmodifiableList(analyses_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.analyses_ = analyses_;
} else {
result.analyses_ = analysesBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse) {
return mergeFrom((com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse other) {
if (other
== com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse.getDefaultInstance())
return this;
if (analysesBuilder_ == null) {
if (!other.analyses_.isEmpty()) {
if (analyses_.isEmpty()) {
analyses_ = other.analyses_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureAnalysesIsMutable();
analyses_.addAll(other.analyses_);
}
onChanged();
}
} else {
if (!other.analyses_.isEmpty()) {
if (analysesBuilder_.isEmpty()) {
analysesBuilder_.dispose();
analysesBuilder_ = null;
analyses_ = other.analyses_;
bitField0_ = (bitField0_ & ~0x00000001);
analysesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getAnalysesFieldBuilder()
: null;
} else {
analysesBuilder_.addAllMessages(other.analyses_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.contactcenterinsights.v1.Analysis m =
input.readMessage(
com.google.cloud.contactcenterinsights.v1.Analysis.parser(),
extensionRegistry);
if (analysesBuilder_ == null) {
ensureAnalysesIsMutable();
analyses_.add(m);
} else {
analysesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.contactcenterinsights.v1.Analysis> analyses_ =
java.util.Collections.emptyList();
private void ensureAnalysesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
analyses_ =
new java.util.ArrayList<com.google.cloud.contactcenterinsights.v1.Analysis>(analyses_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.Analysis,
com.google.cloud.contactcenterinsights.v1.Analysis.Builder,
com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder>
analysesBuilder_;
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public java.util.List<com.google.cloud.contactcenterinsights.v1.Analysis> getAnalysesList() {
if (analysesBuilder_ == null) {
return java.util.Collections.unmodifiableList(analyses_);
} else {
return analysesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public int getAnalysesCount() {
if (analysesBuilder_ == null) {
return analyses_.size();
} else {
return analysesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.Analysis getAnalyses(int index) {
if (analysesBuilder_ == null) {
return analyses_.get(index);
} else {
return analysesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder setAnalyses(
int index, com.google.cloud.contactcenterinsights.v1.Analysis value) {
if (analysesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAnalysesIsMutable();
analyses_.set(index, value);
onChanged();
} else {
analysesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder setAnalyses(
int index, com.google.cloud.contactcenterinsights.v1.Analysis.Builder builderForValue) {
if (analysesBuilder_ == null) {
ensureAnalysesIsMutable();
analyses_.set(index, builderForValue.build());
onChanged();
} else {
analysesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder addAnalyses(com.google.cloud.contactcenterinsights.v1.Analysis value) {
if (analysesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAnalysesIsMutable();
analyses_.add(value);
onChanged();
} else {
analysesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder addAnalyses(
int index, com.google.cloud.contactcenterinsights.v1.Analysis value) {
if (analysesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAnalysesIsMutable();
analyses_.add(index, value);
onChanged();
} else {
analysesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder addAnalyses(
com.google.cloud.contactcenterinsights.v1.Analysis.Builder builderForValue) {
if (analysesBuilder_ == null) {
ensureAnalysesIsMutable();
analyses_.add(builderForValue.build());
onChanged();
} else {
analysesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder addAnalyses(
int index, com.google.cloud.contactcenterinsights.v1.Analysis.Builder builderForValue) {
if (analysesBuilder_ == null) {
ensureAnalysesIsMutable();
analyses_.add(index, builderForValue.build());
onChanged();
} else {
analysesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder addAllAnalyses(
java.lang.Iterable<? extends com.google.cloud.contactcenterinsights.v1.Analysis> values) {
if (analysesBuilder_ == null) {
ensureAnalysesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, analyses_);
onChanged();
} else {
analysesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder clearAnalyses() {
if (analysesBuilder_ == null) {
analyses_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
analysesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public Builder removeAnalyses(int index) {
if (analysesBuilder_ == null) {
ensureAnalysesIsMutable();
analyses_.remove(index);
onChanged();
} else {
analysesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.Analysis.Builder getAnalysesBuilder(
int index) {
return getAnalysesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder getAnalysesOrBuilder(
int index) {
if (analysesBuilder_ == null) {
return analyses_.get(index);
} else {
return analysesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public java.util.List<? extends com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder>
getAnalysesOrBuilderList() {
if (analysesBuilder_ != null) {
return analysesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(analyses_);
}
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.Analysis.Builder addAnalysesBuilder() {
return getAnalysesFieldBuilder()
.addBuilder(com.google.cloud.contactcenterinsights.v1.Analysis.getDefaultInstance());
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.Analysis.Builder addAnalysesBuilder(
int index) {
return getAnalysesFieldBuilder()
.addBuilder(
index, com.google.cloud.contactcenterinsights.v1.Analysis.getDefaultInstance());
}
/**
*
*
* <pre>
* The analyses that match the request.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.Analysis analyses = 1;</code>
*/
public java.util.List<com.google.cloud.contactcenterinsights.v1.Analysis.Builder>
getAnalysesBuilderList() {
return getAnalysesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.Analysis,
com.google.cloud.contactcenterinsights.v1.Analysis.Builder,
com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder>
getAnalysesFieldBuilder() {
if (analysesBuilder_ == null) {
analysesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.Analysis,
com.google.cloud.contactcenterinsights.v1.Analysis.Builder,
com.google.cloud.contactcenterinsights.v1.AnalysisOrBuilder>(
analyses_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
analyses_ = null;
}
return analysesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.contactcenterinsights.v1.ListAnalysesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.ListAnalysesResponse)
private static final com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse();
}
public static com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAnalysesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAnalysesResponse>() {
@java.lang.Override
public ListAnalysesResponse 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<ListAnalysesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAnalysesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListAnalysesResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googlesamples/io2015-codelabs | 37,429 | voice-interaction-api/voice-interaction-start/Application/src/main/java/com/example/android/voicecamera/CameraFragment.java | /*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.voicecamera;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class CameraFragment extends Fragment implements View.OnClickListener {
/**
* Tag for the {@link Log}.
*/
private static final String TAG = "Camera2BasicFragment";
private static final String EXTRA_USE_FRONT_FACING_CAMERA = "android.intent.extra.USE_FRONT_CAMERA";
/**
* Camera state: Showing camera preview.
*/
private static final int STATE_PREVIEW = 0;
/**
* Camera state: Waiting for the focus to be locked.
*/
private static final int STATE_WAITING_LOCK = 1;
/**
* Camera state: Waiting for the exposure to be precapture state.
*/
private static final int STATE_WAITING_PRECAPTURE = 2;
/**
* Camera state: Waiting for the exposure state to be something other than precapture.
*/
private static final int STATE_WAITING_NON_PRECAPTURE = 3;
/**
* Camera state: Picture was taken.
*/
private static final int STATE_PICTURE_TAKEN = 4;
/**
* {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a
* {@link TextureView}.
*/
private final TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
Log.d(TAG, "onSurfaceTextureAvailable: ");
openCamera(width, height);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
Log.d(TAG, "onSurfaceTextureSizeChanged: ");
configureTransform(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
Log.d(TAG, "onSurfaceTextureDestroyed: ");
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture texture) {
Log.d(TAG, "onSurfaceTextureUpdated: ");
}
};
/**
* ID of the current {@link CameraDevice}.
*/
private String mCameraId;
/**
* An {@link AutoFitTextureView} for camera preview.
*/
private AutoFitTextureView mTextureView;
/**
* A {@link CameraCaptureSession } for camera preview.
*/
private CameraCaptureSession mCaptureSession;
/**
* A reference to the opened {@link CameraDevice}.
*/
private CameraDevice mCameraDevice;
/**
* The {@link android.util.Size} of camera preview.
*/
private Size mPreviewSize;
/**
* Characteristics of the current {@link CameraDevice}
*/
private CameraCharacteristics mCharacteristics;
private OrientationEventListener mOrientationListener;
/**
* Current device orientation in degrees.
*/
private int mOrientation;
/**
* {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice cameraDevice) {
Log.d(TAG, "onOpened: ");
// This method is called when the camera is opened. We start camera preview here.
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();
}
@Override
public void onDisconnected(CameraDevice cameraDevice) {
Log.d(TAG, "onDisconnected: ");
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
@Override
public void onError(CameraDevice cameraDevice, int error) {
Log.d(TAG, "onError: ");
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
}
};
/**
* An additional thread for running tasks that shouldn't block the UI.
*/
private HandlerThread mBackgroundThread;
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler mBackgroundHandler;
/**
* An {@link ImageReader} that handles still image capture.
*/
private ImageReader mImageReader;
private boolean mEnabledAutoFocus = true;
/**
* This is the output file for our picture.
*/
private File mFile;
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* still image is ready to be saved.
*/
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Log.d(TAG, "onImageAvailable: ");
mBackgroundHandler.post(new ImageSaver(getActivity(), reader.acquireNextImage(), mFile));
}
};
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
private CaptureRequest.Builder mPreviewRequestBuilder;
/**
* {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
*/
private CaptureRequest mPreviewRequest;
/**
* The current state of camera state for taking pictures.
*
* @see #mCaptureCallback
*/
private int mState = STATE_PREVIEW;
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
/**
* A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture.
*/
private CameraCaptureSession.CaptureCallback mCaptureCallback
= new CameraCaptureSession.CaptureCallback() {
private void process(CaptureResult result) {
Log.d(TAG, "process: ");
switch (mState) {
case STATE_PREVIEW: {
// We have nothing to do when the camera preview is working normally.
break;
}
case STATE_WAITING_LOCK: {
int afState = result.get(CaptureResult.CONTROL_AF_STATE);
Log.e(TAG, "afstate: " + afState);
if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
mEnabledAutoFocus = true;
// CONTROL_AE_STATE can be null on some devices
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
Log.e(TAG, "aestate: " + aeState);
if (aeState == null ||
aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
mState = STATE_WAITING_NON_PRECAPTURE;
captureStillPicture();
} else {
Log.e(TAG, "precapture");
runPrecaptureSequence();
}
} else if (CaptureResult.CONTROL_AF_MODE_OFF == afState) {
Log.e(TAG, "Autofocus disabled");
mEnabledAutoFocus = false;
mState = STATE_PICTURE_TAKEN;
captureStillPicture();
}
break;
}
case STATE_WAITING_PRECAPTURE: {
// CONTROL_AE_STATE can be null on some devices
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null ||
aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
mState = STATE_WAITING_NON_PRECAPTURE;
}
break;
}
case STATE_WAITING_NON_PRECAPTURE: {
// CONTROL_AE_STATE can be null on some devices
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
mState = STATE_PICTURE_TAKEN;
captureStillPicture();
}
break;
}
}
}
@Override
public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request,
CaptureResult partialResult) {
Log.d(TAG, "onCaptureProgressed: ");
process(partialResult);
}
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
TotalCaptureResult result) {
Log.d(TAG, "onCaptureCompleted: ");
process(result);
}
};
/**
* A {@link Handler} for showing {@link Toast}s.
*/
private Handler mMessageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "handleMessage: ");
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, (String) msg.obj, Toast.LENGTH_SHORT).show();
}
}
};
/**
* Shows a {@link Toast} on the UI thread.
*
* @param text The message to show
*/
private void showToast(String text) {
Log.d(TAG, "showToast: ");
// We show a Toast by sending request message to mMessageHandler. This makes sure that the
// Toast is shown on the UI thread.
Message message = Message.obtain();
message.obj = text;
mMessageHandler.sendMessage(message);
}
/**
* Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
* width and height are at least as large as the respective requested values, and whose aspect
* ratio matches with the specified value.
*
* @param choices The list of sizes that the camera supports for the intended output class
* @param width The minimum desired width
* @param height The minimum desired height
* @param aspectRatio The aspect ratio
* @return The optimal {@code Size}, or an arbitrary one if none were big enough
*/
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
Log.d(TAG, "chooseOptimalSize: ");
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<Size>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getHeight() == option.getWidth() * h / w &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: ");
View view = inflater.inflate(R.layout.fragment_camera2_basic, container, false);
return view;
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
Log.d(TAG, "onViewCreated: ");
view.findViewById(R.id.picture).setOnClickListener(this);
view.findViewById(R.id.info).setOnClickListener(this);
mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated: ");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "VoiceCamera");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! storageDir.exists()){
if (! storageDir.mkdirs()){
Log.d(TAG, "failed to create directory");
getActivity().finish();
}
}
mOrientationListener = new OrientationEventListener(getActivity().getApplicationContext()) {
@Override
public void onOrientationChanged(int orientation) {
mOrientation = orientation;
}
};
try {
mFile = File.createTempFile(imageFileName, ".jpg", storageDir);
Log.e(TAG, "Photo file: " + mFile.getAbsolutePath());
} catch(IOException e) {
Log.e(TAG, "Error creating file: ", e);
getActivity().finish();
}
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
startBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}
}
@Override
public void onPause() {
Log.d(TAG, "onPause: ");
closeCamera();
mOrientationListener.disable();
stopBackgroundThread();
super.onPause();
}
private boolean isCameraSpecified() {
Log.d(TAG, "isCameraSpecified: ");
return getArguments() != null && getArguments().containsKey(EXTRA_USE_FRONT_FACING_CAMERA);
}
private boolean shouldUseCamera(int lensFacing) {
Log.d(TAG, "shouldUseCamera: ");
if (getArguments().getBoolean(EXTRA_USE_FRONT_FACING_CAMERA)) {
return lensFacing == CameraCharacteristics.LENS_FACING_FRONT;
} else {
return lensFacing == CameraCharacteristics.LENS_FACING_BACK;
}
}
/**
* Sets up member variables related to camera.
*
* @param width The width of available size for camera preview
* @param height The height of available size for camera preview
*/
private void setUpCameraOutputs(int width, int height) {
Log.d(TAG, "setUpCameraOutputs: ");
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
if (!isCameraSpecified()) {
// We don't use a front facing camera in this sample.
if (characteristics.get(CameraCharacteristics.LENS_FACING)
== CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
} else if (!shouldUseCamera(characteristics.get(CameraCharacteristics.LENS_FACING))) {
// TODO: Handle case where there is no camera match
continue;
}
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
// For still image captures, we use the largest available size.
Size largest = Collections.max(
Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
new CompareSizesByArea());
mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
ImageFormat.JPEG, /*maxImages*/2);
mImageReader.setOnImageAvailableListener(
mOnImageAvailableListener, mBackgroundHandler);
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
width, height, largest);
// We fit the aspect ratio of TextureView to the size of preview we picked.
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(
mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(
mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
mCameraId = cameraId;
mCharacteristics = characteristics;
return;
}
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (NullPointerException e) {
Log.e(TAG, "NPE: ", e);
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
new ErrorDialog().show(getFragmentManager(), "dialog");
}
}
/**
* Opens the camera specified by {@link CameraFragment#mCameraId}.
*/
private void openCamera(int width, int height) {
Log.d(TAG, "openCamera: ");
setUpCameraOutputs(width, height);
configureTransform(width, height);
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
/**
* Closes the current {@link CameraDevice}.
*/
private void closeCamera() {
Log.d(TAG, "closeCamera: ");
try {
mCameraOpenCloseLock.acquire();
if (null != mCaptureSession) {
mCaptureSession.close();
mCaptureSession = null;
}
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mImageReader) {
mImageReader.close();
mImageReader = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
mCameraOpenCloseLock.release();
}
}
/**
* Starts a background thread and its {@link Handler}.
*/
private void startBackgroundThread() {
Log.d(TAG, "startBackgroundThread: ");
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
/**
* Stops the background thread and its {@link Handler}.
*/
private void stopBackgroundThread() {
Log.d(TAG, "stopBackgroundThread: ");
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
*/
private void createCameraPreviewSession() {
Log.d(TAG, "createCameraPreviewSession: ");
try {
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
// We configure the size of default buffer to be the size of camera preview we want.
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
// This is the output Surface we need to start preview.
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession cameraCaptureSession) {
// The camera is already closed
if (null == mCameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
mCaptureSession = cameraCaptureSession;
try {
// Auto focus should be continuous for camera preview.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// Flash is automatically enabled when necessary.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
// Finally, we start displaying the camera preview.
mPreviewRequest = mPreviewRequestBuilder.build();
mCaptureSession.setRepeatingRequest(mPreviewRequest,
mCaptureCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
showToast("Failed");
}
}, null
);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
* This method should be called after the camera preview size is determined in
* setUpCameraOutputs and also the size of `mTextureView` is fixed.
*
* @param viewWidth The width of `mTextureView`
* @param viewHeight The height of `mTextureView`
*/
private void configureTransform(int viewWidth, int viewHeight) {
Log.d(TAG, "configureTransform: ");
Activity activity = getActivity();
if (null == mTextureView || null == mPreviewSize || null == activity) {
return;
}
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / mPreviewSize.getHeight(),
(float) viewWidth / mPreviewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
}
mTextureView.setTransform(matrix);
}
/**
* Initiate a still image capture.
*/
private void takePicture() {
Log.d(TAG, "takePicture: ");
lockFocus();
}
/**
* Lock the focus as the first step for a still image capture.
*/
private void lockFocus() {
Log.d(TAG, "lockFocus: ");
try {
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
CameraMetadata.CONTROL_AF_TRIGGER_START);
// Tell #mCaptureCallback to wait for the lock.
mState = STATE_WAITING_LOCK;
mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), mCaptureCallback,
mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e(TAG, "CameraAccessException: " + e);
e.printStackTrace();
}
}
/**
* Run the precapture sequence for capturing a still image. This method should be called when we
* get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
*/
private void runPrecaptureSequence() {
Log.d(TAG, "runPrecaptureSequence: ");
try {
// This is how to tell the camera to trigger.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
// Tell #mCaptureCallback to wait for the precapture sequence to be set.
mState = STATE_WAITING_PRECAPTURE;
mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Capture a still picture. This method should be called when we get a response in
* {@link #mCaptureCallback} from both {@link #lockFocus()}.
*/
private void captureStillPicture() {
Log.d(TAG, "captureStillPicture: ");
try {
final Activity activity = getActivity();
if (null == activity || null == mCameraDevice) {
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
final CaptureRequest.Builder captureBuilder =
mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(mImageReader.getSurface());
// Use the same AE and AF modes as the preview.
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureBuilder.set(CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,
getJpegOrientation(mCharacteristics, mOrientation));
CameraCaptureSession.CaptureCallback CaptureCallback
= new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
TotalCaptureResult result) {
showToast("Saved Picture");
//unlockFocus();
}
};
mCaptureSession.stopRepeating();
mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Translates from the device orientation given by the Android sensor APIs to the
* orientation for a JPEG image.
*/
private int getJpegOrientation(CameraCharacteristics c, int deviceOrientation) {
Log.d(TAG, "getJpegOrientation: ");
if (deviceOrientation == android.view.OrientationEventListener.ORIENTATION_UNKNOWN)
return 0;
int sensorOrientation = c.get(CameraCharacteristics.SENSOR_ORIENTATION);
// Round device orientation to a multiple of 90
deviceOrientation = (deviceOrientation + 45) / 90 * 90;
// Reverse device orientation for front-facing cameras
boolean facingFront = c.get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT;
if (facingFront) deviceOrientation = -deviceOrientation;
// Calculate desired JPEG orientation relative to camera orientation to make
// the image upright relative to the device orientation
int jpegOrientation = (sensorOrientation + deviceOrientation + 360) % 360;
return jpegOrientation;
}
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: ");
switch (view.getId()) {
case R.id.picture: {
takePicture();
break;
}
case R.id.info: {
Activity activity = getActivity();
if (null != activity) {
new AlertDialog.Builder(activity)
.setMessage(R.string.intro_message)
.setPositiveButton(android.R.string.ok, null)
.show();
}
break;
}
}
}
/**
* Saves a JPEG {@link Image} into the specified {@link File}.
*/
private static class ImageSaver implements Runnable {
/**
* The JPEG image
*/
private final Image mImage;
/**
* The file we save the image into.
*/
private final File mFile;
private final Context mContext;
public ImageSaver(Context context, Image image, File file) {
Log.d(TAG, "ImageSaver: ");
mContext = context;
mImage = image;
mFile = file;
}
@Override
public void run() {
Log.d(TAG, "run: ");
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
FileOutputStream output = null;
try {
output = new FileOutputStream(mFile);
output.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mFile);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
}
}
/**
* Compares two {@code Size}s based on their areas.
*/
static class CompareSizesByArea implements Comparator<Size> {
@Override
public int compare(Size lhs, Size rhs) {
Log.d(TAG, "compare: ");
// We cast here to ensure the multiplications won't overflow
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
public static class ErrorDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Activity activity = getActivity();
return new AlertDialog.Builder(activity)
.setMessage("This device doesn't support Camera2 API.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d(TAG, "onClick: ");
activity.finish();
}
})
.create();
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "onAttach: ");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: ");
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG, "onDestroyView: ");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
@Override
public void onDetach() {
super.onDetach();
Log.d(TAG, "onDetach: ");
}
}
|
apache/cxf | 37,577 | services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/ValidateTokenTransformationUnitTest.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.cxf.sts.operation;
import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.security.auth.callback.CallbackHandler;
import javax.xml.namespace.QName;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import jakarta.xml.bind.JAXBElement;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.jaxws.context.WrappedMessageContext;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.rt.security.claims.Claim;
import org.apache.cxf.rt.security.claims.ClaimCollection;
import org.apache.cxf.security.SecurityContext;
import org.apache.cxf.sts.QNameConstants;
import org.apache.cxf.sts.STSConstants;
import org.apache.cxf.sts.STSPropertiesMBean;
import org.apache.cxf.sts.StaticSTSProperties;
import org.apache.cxf.sts.claims.ClaimTypes;
import org.apache.cxf.sts.claims.ClaimsAttributeStatementProvider;
import org.apache.cxf.sts.claims.ClaimsHandler;
import org.apache.cxf.sts.claims.ClaimsManager;
import org.apache.cxf.sts.claims.ClaimsMapper;
import org.apache.cxf.sts.common.CustomAttributeProvider;
import org.apache.cxf.sts.common.CustomClaimsHandler;
import org.apache.cxf.sts.common.PasswordCallbackHandler;
import org.apache.cxf.sts.request.KeyRequirements;
import org.apache.cxf.sts.request.TokenRequirements;
import org.apache.cxf.sts.service.EncryptionProperties;
import org.apache.cxf.sts.service.ServiceMBean;
import org.apache.cxf.sts.service.StaticService;
import org.apache.cxf.sts.token.provider.SAMLTokenProvider;
import org.apache.cxf.sts.token.provider.TokenProviderParameters;
import org.apache.cxf.sts.token.provider.TokenProviderResponse;
import org.apache.cxf.sts.token.realm.RealmProperties;
import org.apache.cxf.sts.token.realm.Relationship;
import org.apache.cxf.sts.token.validator.IssuerSAMLRealmCodec;
import org.apache.cxf.sts.token.validator.SAMLTokenValidator;
import org.apache.cxf.sts.token.validator.UsernameTokenValidator;
import org.apache.cxf.ws.security.sts.provider.STSException;
import org.apache.cxf.ws.security.sts.provider.model.ClaimsType;
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType;
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType;
import org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType;
import org.apache.cxf.ws.security.sts.provider.model.StatusType;
import org.apache.cxf.ws.security.sts.provider.model.ValidateTargetType;
import org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString;
import org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString;
import org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.apache.wss4j.common.saml.builder.SAML2Constants;
import org.apache.wss4j.common.util.DOM2Writer;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* In this test, a token (UsernameToken or SAMLToken) is validated and transformed into a SAML Assertion.
*/
public class ValidateTokenTransformationUnitTest {
public static final QName REQUESTED_SECURITY_TOKEN =
QNameConstants.WS_TRUST_FACTORY.createRequestedSecurityToken(null).getName();
private static final QName QNAME_WST_STATUS =
QNameConstants.WS_TRUST_FACTORY.createStatus(null).getName();
/**
* Test to successfully validate a UsernameToken and transform it into a SAML Assertion.
*/
@org.junit.Test
public void testUsernameTokenTransformation() throws Exception {
TokenValidateOperation validateOperation = new TokenValidateOperation();
// Add Token Validator
validateOperation.setTokenValidators(Collections.singletonList(
new UsernameTokenValidator()));
// Add Token Provider
validateOperation.setTokenProviders(Collections.singletonList(
new SAMLTokenProvider()));
// Add STSProperties object
STSPropertiesMBean stsProperties = new StaticSTSProperties();
Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
stsProperties.setEncryptionCrypto(crypto);
stsProperties.setSignatureCrypto(crypto);
stsProperties.setEncryptionUsername("myservicekey");
stsProperties.setSignatureUsername("mystskey");
stsProperties.setCallbackHandler(new PasswordCallbackHandler());
stsProperties.setIssuer("STS");
validateOperation.setStsProperties(stsProperties);
// Mock up a request
RequestSecurityTokenType request = new RequestSecurityTokenType();
JAXBElement<String> tokenType =
new JAXBElement<String>(
QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE
);
request.getAny().add(tokenType);
// Create a UsernameToken
JAXBElement<UsernameTokenType> usernameTokenType = createUsernameToken("alice", "clarinet");
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.setAny(usernameTokenType);
JAXBElement<ValidateTargetType> validateTargetType =
new JAXBElement<ValidateTargetType>(
QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget
);
request.getAny().add(validateTargetType);
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
Principal principal = new CustomTokenPrincipal("alice");
msgCtx.put(
SecurityContext.class.getName(),
createSecurityContext(principal)
);
// Validate a token
RequestSecurityTokenResponseType response =
validateOperation.validate(request, principal, msgCtx);
assertTrue(validateResponse(response));
// Test the generated token.
Element assertion = null;
for (Object tokenObject : response.getAny()) {
if (tokenObject instanceof JAXBElement<?>
&& REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>)tokenObject).getName())) {
RequestedSecurityTokenType rstType =
(RequestedSecurityTokenType)((JAXBElement<?>)tokenObject).getValue();
assertion = (Element)rstType.getAny();
break;
}
}
assertNotNull(assertion);
String tokenString = DOM2Writer.nodeToString(assertion);
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("alice"));
assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
}
/**
* Test to successfully validate a UsernameToken (which was issued in realm "A") and
* transform it into a SAML Assertion in Realm "B".
*/
@org.junit.Test
public void testUsernameTokenTransformationRealm() throws Exception {
TokenValidateOperation validateOperation = new TokenValidateOperation();
// Add Token Validator
UsernameTokenValidator validator = new UsernameTokenValidator();
validator.setUsernameTokenRealmCodec(new CustomUsernameTokenRealmCodec());
validateOperation.setTokenValidators(Collections.singletonList(validator));
// Add Token Provider
SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
validateOperation.setTokenProviders(Collections.singletonList(samlTokenProvider));
// Add STSProperties object
STSPropertiesMBean stsProperties = new StaticSTSProperties();
Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
stsProperties.setEncryptionCrypto(crypto);
stsProperties.setSignatureCrypto(crypto);
stsProperties.setEncryptionUsername("myservicekey");
stsProperties.setSignatureUsername("mystskey");
stsProperties.setCallbackHandler(new PasswordCallbackHandler());
stsProperties.setIssuer("STS");
stsProperties.setRealmParser(new CustomRealmParser());
stsProperties.setIdentityMapper(new CustomIdentityMapper());
validateOperation.setStsProperties(stsProperties);
// Mock up a request
RequestSecurityTokenType request = new RequestSecurityTokenType();
JAXBElement<String> tokenType =
new JAXBElement<String>(
QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE
);
request.getAny().add(tokenType);
// Create a UsernameToken
JAXBElement<UsernameTokenType> usernameTokenType = createUsernameToken("alice", "clarinet");
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.setAny(usernameTokenType);
JAXBElement<ValidateTargetType> validateTargetType =
new JAXBElement<ValidateTargetType>(
QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget
);
request.getAny().add(validateTargetType);
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
Principal principal = new CustomTokenPrincipal("alice");
msgCtx.put(
SecurityContext.class.getName(),
createSecurityContext(principal)
);
msgCtx.put("url", "https");
// Validate a token - this will fail as the tokenProvider doesn't understand how to handle
// realm "B"
try {
validateOperation.validate(request, principal, msgCtx);
} catch (STSException ex) {
// expected
}
samlTokenProvider.setRealmMap(createSamlRealms());
RequestSecurityTokenResponseType response = validateOperation.validate(request, principal, msgCtx);
assertTrue(validateResponse(response));
// Test the generated token.
Element assertion = null;
for (Object tokenObject : response.getAny()) {
if (tokenObject instanceof JAXBElement<?>
&& REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>)tokenObject).getName())) {
RequestedSecurityTokenType rstType =
(RequestedSecurityTokenType)((JAXBElement<?>)tokenObject).getValue();
assertion = (Element)rstType.getAny();
break;
}
}
assertNotNull(assertion);
String tokenString = DOM2Writer.nodeToString(assertion);
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("ALICE"));
assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
}
/**
* Test to successfully validate a UsernameToken and transform it into a SAML Assertion.
* Required claims are a child of RST element
*/
@org.junit.Test
public void testUsernameTokenTransformationClaims() throws Exception {
runUsernameTokenTransformationClaims(false);
}
/**
* Test to successfully validate a UsernameToken and transform it into a SAML Assertion.
* Required claims are a child of SecondaryParameters element
*/
@org.junit.Test
public void testUsernameTokenTransformationClaimsSecondaryParameters() throws Exception {
runUsernameTokenTransformationClaims(true);
}
/**
* Test to successfully validate a SAML 2 Token issued by realm "A" and
* transform it into a SAML 2 token (realm "B")
* The relationship type between realm A and B is: FederateIdentity
* IdentityMapper is configured globally in STSPropertiesMBean
*/
@org.junit.Test
public void testValidateSaml2TokenOnBehalfOfSaml2DifferentRealmFederateIdentityGlobalConfig()
throws Exception {
runValidateSaml2TokenOnBehalfOfSaml2DifferentRealmFederateIdentity(true);
}
/**
* Test to successfully validate a SAML 2 Token issued by realm "A" and
* transform it into a SAML 2 token (realm "B")
* The relationship type between realm A and B is: FederateIdentity
* IdentityMapper is configured in the Relationship
*/
@org.junit.Test
//[TODO] should work after Relationship support in validateoperation
public void testValidateSaml2TokenOnBehalfOfSaml2DifferentRealmFederateIdentityRelationshipConfig()
throws Exception {
runValidateSaml2TokenOnBehalfOfSaml2DifferentRealmFederateIdentity(false);
}
/**
* Test to successfully validate a SAML 2 Token issued by realm "A" and
* transform it into a SAML 2 token (realm "B")
* The relationship type between realm A and B is: FederateClaims
*/
@org.junit.Test
public void testValidateSaml2TokenOnBehalfOfSaml2DifferentRealmFederateClaims() throws Exception {
TokenValidateOperation validateOperation = new TokenValidateOperation();
Map<String, RealmProperties> realms = createSamlRealms();
// Add Token Provider
SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
samlTokenProvider.setRealmMap(realms);
samlTokenProvider.setAttributeStatementProviders(Collections.singletonList(
new ClaimsAttributeStatementProvider()));
validateOperation.setTokenProviders(Collections.singletonList(samlTokenProvider));
// Add Token Validator
SAMLTokenValidator samlTokenValidator = new SAMLTokenValidator();
samlTokenValidator.setSamlRealmCodec(new IssuerSAMLRealmCodec());
validateOperation.setTokenValidators(Collections.singletonList(samlTokenValidator));
// Add Service
ServiceMBean service = new StaticService();
service.setEndpoints(Collections.singletonList("http://dummy-service.com/dummy"));
validateOperation.setServices(Collections.singletonList(service));
// Add Relationship list
Relationship rs = createRelationship();
// Add STSProperties object
Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
STSPropertiesMBean stsProperties = createSTSPropertiesMBean(crypto);
stsProperties.setRealmParser(new CustomRealmParser());
stsProperties.setIdentityMapper(new CustomIdentityMapper());
stsProperties.setRelationships(Collections.singletonList(rs));
validateOperation.setStsProperties(stsProperties);
// Set the ClaimsManager
ClaimsManager claimsManager = new ClaimsManager();
claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler)new CustomClaimsHandler()));
validateOperation.setClaimsManager(claimsManager);
// Mock up a request
RequestSecurityTokenType request = new RequestSecurityTokenType();
JAXBElement<String> tokenType =
new JAXBElement<String>(
QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE
);
request.getAny().add(tokenType);
// Add a ClaimsType
ClaimsType claimsType = new ClaimsType();
claimsType.setDialect(STSConstants.IDT_NS_05_05);
Document doc = DOMUtils.createDocument();
Element claimType = createClaimsType(doc);
claimsType.getAny().add(claimType);
JAXBElement<ClaimsType> claimsTypeJaxb =
new JAXBElement<ClaimsType>(
QNameConstants.CLAIMS, ClaimsType.class, claimsType
);
request.getAny().add(claimsTypeJaxb);
//request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));
// create a SAML Token via the SAMLTokenProvider which contains claims
CallbackHandler callbackHandler = new PasswordCallbackHandler();
Element samlToken =
createSAMLAssertion(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey",
callbackHandler, realms);
Document docToken = samlToken.getOwnerDocument();
samlToken = (Element)docToken.appendChild(samlToken);
String samlString = DOM2Writer.nodeToString(samlToken);
assertTrue(samlString.contains("AttributeStatement"));
assertTrue(samlString.contains("alice"));
assertTrue(samlString.contains("doe"));
assertTrue(samlString.contains(SAML2Constants.CONF_BEARER));
// Add SAML token as ValidateTarget element
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.setAny(samlToken);
JAXBElement<ValidateTargetType> validateTargetType =
new JAXBElement<ValidateTargetType>(
QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget
);
request.getAny().add(validateTargetType);
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
msgCtx.put("url", "https");
// Validate a token
RequestSecurityTokenResponseType response =
validateOperation.validate(request, null, msgCtx);
assertTrue(validateResponse(response));
// Test the generated token.
Element assertion = null;
for (Object tokenObject : response.getAny()) {
if (tokenObject instanceof JAXBElement<?>
&& REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>)tokenObject).getName())) {
RequestedSecurityTokenType rstType =
(RequestedSecurityTokenType)((JAXBElement<?>)tokenObject).getValue();
assertion = (Element)rstType.getAny();
break;
}
}
assertNotNull(assertion);
String tokenString = DOM2Writer.nodeToString(assertion);
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("alice")); //subject unchanged
assertTrue(tokenString.contains("DOE")); //claim changed (to uppercase)
assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
}
/**
* Test to successfully validate a UsernameToken and transform it into a SAML Assertion with claims.
*/
private void runUsernameTokenTransformationClaims(boolean useSecondaryParameters) throws Exception {
TokenValidateOperation validateOperation = new TokenValidateOperation();
// Add Token Validator
validateOperation.setTokenValidators(Collections.singletonList(
new UsernameTokenValidator()));
// Add Token Provider
SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
samlTokenProvider.setAttributeStatementProviders(Collections.singletonList(
new CustomAttributeProvider()));
validateOperation.setTokenProviders(Collections.singletonList(samlTokenProvider));
// Add STSProperties object
STSPropertiesMBean stsProperties = new StaticSTSProperties();
Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
stsProperties.setEncryptionCrypto(crypto);
stsProperties.setSignatureCrypto(crypto);
stsProperties.setEncryptionUsername("myservicekey");
stsProperties.setSignatureUsername("mystskey");
stsProperties.setCallbackHandler(new PasswordCallbackHandler());
stsProperties.setIssuer("STS");
validateOperation.setStsProperties(stsProperties);
// Set the ClaimsManager
ClaimsManager claimsManager = new ClaimsManager();
ClaimsHandler claimsHandler = new CustomClaimsHandler();
claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
validateOperation.setClaimsManager(claimsManager);
// Mock up a request
RequestSecurityTokenType request = new RequestSecurityTokenType();
JAXBElement<String> tokenType =
new JAXBElement<String>(
QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE
);
request.getAny().add(tokenType);
Object claims =
useSecondaryParameters ? createClaimsElementInSecondaryParameters() : createClaimsElement();
request.getAny().add(claims);
// Create a UsernameToken
JAXBElement<UsernameTokenType> usernameTokenType = createUsernameToken("alice", "clarinet");
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.setAny(usernameTokenType);
JAXBElement<ValidateTargetType> validateTargetType =
new JAXBElement<ValidateTargetType>(
QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget
);
request.getAny().add(validateTargetType);
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
Principal principal = new CustomTokenPrincipal("ted");
msgCtx.put(
SecurityContext.class.getName(),
createSecurityContext(principal)
);
// Validate a token
RequestSecurityTokenResponseType response =
validateOperation.validate(request, principal, msgCtx);
assertTrue(validateResponse(response));
// Test the generated token.
Element assertion = null;
for (Object tokenObject : response.getAny()) {
if (tokenObject instanceof JAXBElement<?>
&& REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>)tokenObject).getName())) {
RequestedSecurityTokenType rstType =
(RequestedSecurityTokenType)((JAXBElement<?>)tokenObject).getValue();
assertion = (Element)rstType.getAny();
break;
}
}
assertNotNull(assertion);
String tokenString = DOM2Writer.nodeToString(assertion);
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("alice"));
assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
assertTrue(tokenString.contains(ClaimTypes.LASTNAME.toString()));
}
private void runValidateSaml2TokenOnBehalfOfSaml2DifferentRealmFederateIdentity(
boolean useGlobalIdentityMapper) throws WSSecurityException {
TokenValidateOperation validateOperation = new TokenValidateOperation();
Map<String, RealmProperties> realms = createSamlRealms();
// Add Token Provider
SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
samlTokenProvider.setRealmMap(realms);
samlTokenProvider.setAttributeStatementProviders(Collections.singletonList(
new ClaimsAttributeStatementProvider()));
validateOperation.setTokenProviders(Collections.singletonList(samlTokenProvider));
// Add Token Validator
SAMLTokenValidator samlTokenValidator = new SAMLTokenValidator();
samlTokenValidator.setSamlRealmCodec(new IssuerSAMLRealmCodec());
validateOperation.setTokenValidators(Collections.singletonList(samlTokenValidator));
// Add Service
ServiceMBean service = new StaticService();
service.setEndpoints(Collections.singletonList("http://dummy-service.com/dummy"));
validateOperation.setServices(Collections.singletonList(service));
// Add Relationship list
Relationship rs = createRelationship();
rs.setType(Relationship.FED_TYPE_IDENTITY);
rs.setIdentityMapper(new CustomIdentityMapper());
// Add STSProperties object
Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
STSPropertiesMBean stsProperties = createSTSPropertiesMBean(crypto);
stsProperties.setRealmParser(new CustomRealmParser());
if (useGlobalIdentityMapper) {
stsProperties.setIdentityMapper(new CustomIdentityMapper());
} else {
stsProperties.setRelationships(Collections.singletonList(rs));
}
validateOperation.setStsProperties(stsProperties);
// Set the ClaimsManager
ClaimsManager claimsManager = new ClaimsManager();
claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler)new CustomClaimsHandler()));
validateOperation.setClaimsManager(claimsManager);
// Mock up a request
RequestSecurityTokenType request = new RequestSecurityTokenType();
JAXBElement<String> tokenType =
new JAXBElement<String>(
QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE
);
request.getAny().add(tokenType);
// Add a ClaimsType
ClaimsType claimsType = new ClaimsType();
claimsType.setDialect(STSConstants.IDT_NS_05_05);
Document doc = DOMUtils.createDocument();
Element claimType = createClaimsType(doc);
claimsType.getAny().add(claimType);
JAXBElement<ClaimsType> claimsTypeJaxb =
new JAXBElement<ClaimsType>(
QNameConstants.CLAIMS, ClaimsType.class, claimsType
);
request.getAny().add(claimsTypeJaxb);
//request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));
// create a SAML Token via the SAMLTokenProvider which contains claims
CallbackHandler callbackHandler = new PasswordCallbackHandler();
Element samlToken =
createSAMLAssertion(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey",
callbackHandler, realms);
Document docToken = samlToken.getOwnerDocument();
samlToken = (Element)docToken.appendChild(samlToken);
String samlString = DOM2Writer.nodeToString(samlToken);
assertTrue(samlString.contains("AttributeStatement"));
assertTrue(samlString.contains("alice"));
assertTrue(samlString.contains("doe"));
assertTrue(samlString.contains(SAML2Constants.CONF_BEARER));
// Add SAML token as ValidateTarget element
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.setAny(samlToken);
JAXBElement<ValidateTargetType> validateTargetType =
new JAXBElement<ValidateTargetType>(
QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget
);
request.getAny().add(validateTargetType);
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
msgCtx.put("url", "https");
// Validate a token
RequestSecurityTokenResponseType response =
validateOperation.validate(request, null, msgCtx);
assertTrue(validateResponse(response));
// Test the generated token.
Element assertion = null;
for (Object tokenObject : response.getAny()) {
if (tokenObject instanceof JAXBElement<?>
&& REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>)tokenObject).getName())) {
RequestedSecurityTokenType rstType =
(RequestedSecurityTokenType)((JAXBElement<?>)tokenObject).getValue();
assertion = (Element)rstType.getAny();
break;
}
}
assertNotNull(assertion);
String tokenString = DOM2Writer.nodeToString(assertion);
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("ALICE")); //subject changed (to uppercase)
assertTrue(tokenString.contains("doe")); //claim unchanged but requested
assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
}
/*
* Create a security context object
*/
private SecurityContext createSecurityContext(final Principal p) {
return new SecurityContext() {
public Principal getUserPrincipal() {
return p;
}
public boolean isUserInRole(String role) {
return false;
}
};
}
private Relationship createRelationship() {
Relationship rs = new Relationship();
ClaimsMapper claimsMapper = new CustomClaimsMapper();
rs.setClaimsMapper(claimsMapper);
rs.setSourceRealm("A");
rs.setTargetRealm("B");
rs.setType(Relationship.FED_TYPE_CLAIMS);
return rs;
}
/*
* Create STSPropertiesMBean object
*/
private STSPropertiesMBean createSTSPropertiesMBean(Crypto crypto) throws WSSecurityException {
STSPropertiesMBean stsProperties = new StaticSTSProperties();
stsProperties.setEncryptionCrypto(crypto);
stsProperties.setSignatureCrypto(crypto);
stsProperties.setEncryptionUsername("myservicekey");
stsProperties.setSignatureUsername("mystskey");
stsProperties.setCallbackHandler(new PasswordCallbackHandler());
stsProperties.setIssuer("STS");
return stsProperties;
}
private Map<String, RealmProperties> createSamlRealms() {
// Create Realms
Map<String, RealmProperties> samlRealms = new HashMap<>();
RealmProperties samlRealm = new RealmProperties();
samlRealm.setIssuer("A-Issuer");
samlRealms.put("A", samlRealm);
samlRealm = new RealmProperties();
samlRealm.setIssuer("B-Issuer");
samlRealms.put("B", samlRealm);
return samlRealms;
}
/**
* Return true if the response has a valid status, false otherwise
*/
private boolean validateResponse(RequestSecurityTokenResponseType response) {
assertTrue(response != null && response.getAny() != null && !response.getAny().isEmpty());
for (Object requestObject : response.getAny()) {
if (requestObject instanceof JAXBElement<?>) {
JAXBElement<?> jaxbElement = (JAXBElement<?>) requestObject;
if (QNAME_WST_STATUS.equals(jaxbElement.getName())) {
StatusType status = (StatusType)jaxbElement.getValue();
if (STSConstants.VALID_CODE.equals(status.getCode())) {
return true;
}
}
}
}
return false;
}
private Properties getEncryptionProperties() {
Properties properties = new Properties();
properties.put(
"org.apache.wss4j.crypto.provider", "org.apache.wss4j.common.crypto.Merlin"
);
properties.put("org.apache.wss4j.crypto.merlin.keystore.password", "stsspass");
properties.put("org.apache.wss4j.crypto.merlin.keystore.file", "keys/stsstore.jks");
return properties;
}
private JAXBElement<UsernameTokenType> createUsernameToken(String name, String password) {
UsernameTokenType usernameToken = new UsernameTokenType();
AttributedString username = new AttributedString();
username.setValue(name);
usernameToken.setUsername(username);
// Add a password
PasswordString passwordString = new PasswordString();
passwordString.setValue(password);
passwordString.setType(WSS4JConstants.PASSWORD_TEXT);
JAXBElement<PasswordString> passwordType =
new JAXBElement<PasswordString>(
QNameConstants.PASSWORD, PasswordString.class, passwordString
);
usernameToken.getAny().add(passwordType);
return new JAXBElement<UsernameTokenType>(
QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameToken
);
}
/*
* Mock up a DOM Element containing some claims
*/
private JAXBElement<ClaimsType> createClaimsElement() {
Document doc = DOMUtils.getEmptyDocument();
Element claimType = createClaimsType(doc);
ClaimsType claims = new ClaimsType();
claims.setDialect(STSConstants.IDT_NS_05_05);
claims.getAny().add(claimType);
return new JAXBElement<ClaimsType>(
QNameConstants.CLAIMS, ClaimsType.class, claims
);
}
/*
* Mock up a SecondaryParameters DOM Element containing some claims
*/
private Element createClaimsElementInSecondaryParameters() {
Document doc = DOMUtils.getEmptyDocument();
Element secondary = doc.createElementNS(STSConstants.WST_NS_05_12, "SecondaryParameters");
secondary.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns", STSConstants.WST_NS_05_12);
Element claims = doc.createElementNS(STSConstants.WST_NS_05_12, "Claims");
claims.setAttributeNS(null, "Dialect", STSConstants.IDT_NS_05_05);
Element claimType = createClaimsType(doc);
claims.appendChild(claimType);
secondary.appendChild(claims);
return secondary;
}
private Element createClaimsType(Document doc) {
Element claimType = doc.createElementNS(STSConstants.IDT_NS_05_05, "ClaimType");
claimType.setAttributeNS(
null, "Uri", ClaimTypes.LASTNAME.toString()
);
claimType.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns", STSConstants.IDT_NS_05_05);
return claimType;
}
/*
* Mock up an SAML assertion element
*/
private static Element createSAMLAssertion(
String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler,
Map<String, RealmProperties> realms
) throws WSSecurityException {
SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
samlTokenProvider.setRealmMap(realms);
samlTokenProvider.setAttributeStatementProviders(Collections.singletonList(
new ClaimsAttributeStatementProvider()));
TokenProviderParameters providerParameters =
createProviderParameters(
tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler
);
if (realms != null) {
providerParameters.setRealm("A");
}
// Set the ClaimsManager
ClaimsManager claimsManager = new ClaimsManager();
ClaimsHandler claimsHandler = new CustomClaimsHandler();
claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
providerParameters.setClaimsManager(claimsManager);
ClaimCollection requestedClaims = new ClaimCollection();
Claim requestClaim = new Claim();
requestClaim.setClaimType(ClaimTypes.LASTNAME);
requestClaim.setOptional(false);
requestedClaims.add(requestClaim);
providerParameters.setRequestedSecondaryClaims(requestedClaims);
TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
assertNotNull(providerResponse);
assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
return (Element)providerResponse.getToken();
}
private static TokenProviderParameters createProviderParameters(
String tokenType, String keyType, Crypto crypto,
String signatureUsername, CallbackHandler callbackHandler
) throws WSSecurityException {
TokenProviderParameters parameters = new TokenProviderParameters();
TokenRequirements tokenRequirements = new TokenRequirements();
tokenRequirements.setTokenType(tokenType);
parameters.setTokenRequirements(tokenRequirements);
KeyRequirements keyRequirements = new KeyRequirements();
keyRequirements.setKeyType(keyType);
parameters.setKeyRequirements(keyRequirements);
parameters.setPrincipal(new CustomTokenPrincipal("alice"));
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
parameters.setMessageContext(msgCtx);
parameters.setAppliesToAddress("http://dummy-service.com/dummy");
// Add STSProperties object
StaticSTSProperties stsProperties = new StaticSTSProperties();
stsProperties.setSignatureCrypto(crypto);
stsProperties.setSignatureUsername(signatureUsername);
stsProperties.setCallbackHandler(callbackHandler);
stsProperties.setIssuer("STS");
parameters.setStsProperties(stsProperties);
parameters.setEncryptionProperties(new EncryptionProperties());
return parameters;
}
}
|
apache/datasketches-website | 37,515 | src/main/java/org/apache/datasketches/Files.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.datasketches;
import static java.nio.channels.FileChannel.MapMode.READ_ONLY;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* A collection of useful static file handlers that conveniently convert the
* java.io checked exceptions into runtime exceptions.
*
* @author Lee Rhodes
*/
//@SuppressWarnings("javadoc")
public final class Files {
private static final String LS = System.getProperty("line.separator");
private static final byte CR = 0xD;
private static final byte LF = 0xA;
public static final int DEFAULT_BUFSIZE = 8192;
// Common IO & NIO file methods
/**
* If the fileName string is null or empty, this method throws a
* RuntimeException.
*
* @param fileName the given fileName
* @throws RuntimeException if fileName is null or empty.
*/
public static void checkFileName(final String fileName) {
if (fileName == null) {
throw new RuntimeException(LS + "FileName is null.");
}
if (fileName.length() == 0) {
throw new RuntimeException(LS + "FileName is empty.");
}
return;
}
/**
* Gets an existing normal file as a File. If fileName is null, or empty, or
* if the file is actually a directory, or doesn't exist this will throw a
* Runtime Exception; otherwise it will return the fileName as a File object.
*
* @param fileName the given fileName
* @return a File object
* @throws RuntimeException if fileName cannot resolve to a existing normal
* file.
*/
public static File getExistingFile(final String fileName) {
checkFileName(fileName);
final File file = new File(fileName);
if (file.isFile()) {
return file;
}
if (file.isDirectory()) {
throw new RuntimeException(LS + "FileName is a Directory: " + fileName);
}
throw new RuntimeException(LS + "FileName does not exist: " + fileName);
}
/**
* Returns true if file is a normal file and not a directory.
*
* @param fileName the given fileName
* @return true if file is a normal file and not a directory.
* @throws RuntimeException if fileName is null or empty.
*/
public static boolean isFileValid(final String fileName) {
checkFileName(fileName);
final File file = new File(fileName);
return file.isFile();
}
/**
* Gets the System.getProperty("user.dir"), which is the expected location of
* the user root directory.
*
* @return location of user root directory
*/
public static String getUserDir() {
return System.getProperty("user.dir");
}
/**
* Opens a RandomAccessFile given a File object and String mode: "r", "rw",
* "rws" or "rwd". The returned object must be closed by the calling program.
*
* @param file the given file
* @param mode the given mode
* @return RandomAccessFile
* @throws RuntimeException if an IOException occurs.
*/
public static RandomAccessFile openRandomAccessFile(final File file, final String mode) {
final RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, mode);
} catch (final FileNotFoundException e) {
throw new RuntimeException(LS + "Failed to open RandomAccessFile " + LS + e);
}
return raf;
}
/**
* Gets the FileDescriptor from the given RandomAccessFile.
*
* @param raf RandomAccessFile
* @return the FileDescriptor
* @throws RuntimeException if an IOException occurs.
*/
public static FileDescriptor getFD(final RandomAccessFile raf) {
FileDescriptor fd = null;
try {
fd = raf.getFD();
} catch (final IOException e) {
throw new RuntimeException(LS + "RandomAccessFile.getFD() failure" + LS + e);
}
return fd;
}
/**
* Sets the position of the given RandomAccessFile to the given position.
*
* @param raf RandomAccessFile
* @param position the given position
* @throws RuntimeException if an IOException occurs.
*/
public static void seek(final RandomAccessFile raf, final long position) {
try {
raf.seek(position);
} catch (final IOException e) {
throw new RuntimeException(LS + "RandomAccessFile seek failure" + LS + e);
}
}
/**
* Reads buf.length bytes into the given buf.
*
* @param raf RandomAccessFile
* @param buf the size of this buffer is the number of bytes requested.
* @return the number of bytes actually read.
* @throws RuntimeException if an IOException occurs.
*/
public static int readBytes(final RandomAccessFile raf, final byte[] buf) {
final int len = buf.length;
int read = 0;
try {
read = raf.read(buf);
} catch (final IOException e) {
throw new RuntimeException(LS + "RandomAccessFile read failure" + LS + e);
}
if (read < len) {
Arrays.fill(buf, read, len, (byte) 0);
}
return read;
}
// ************************
// NIO OPERATIONS
// ************************
// ByteBuffer methods
/**
* Gets a MappedByteBuffer from the given FileChannel, mode, position and
* size.
*
* @param fChan the given FileChannel
* @param mmode the given MapMode
* @param position the given position
* @param size the given size
* @return a MappedByteBuffer
* @throws RuntimeException if an IOException occurs.
*/
public static MappedByteBuffer getMappedByteBuffer(final FileChannel fChan,
final FileChannel.MapMode mmode, final long position, final long size) {
final MappedByteBuffer mbBuf;
try {
mbBuf = fChan.map(mmode, position, size);
} catch (final IOException e) {
throw new RuntimeException(e);
}
return mbBuf;
}
/**
* Gets a MappedByteBuffer from the given FileChannel and mode. Assumes a
* start position of zero and size of the length of the file (via the
* FileChannel. Equivalent to:<br>
* getMappedByteBuffer(FileChannel, FileChanel.MapMode, 0L, size(fChan));
*
* @param fChan the given FileChannel
* @param mmode the given MapMode
* @return a MappedByteBuffer
* @throws RuntimeException if an IOException occurs.
*/
public static MappedByteBuffer getMappedByteBuffer(final FileChannel fChan,
final FileChannel.MapMode mmode) {
return getMappedByteBuffer(fChan, mmode, 0L, size(fChan));
}
/**
* Reads bytes from the given (Mapped)ByteBuffer until either a CR, LF or CRLF
* is detected in the byte stream and then converts the captured bytes,
* excluding the CR and LF characters into a string. This method will work
* with US-ASCII, ISO-8859 families, Windows 1252, and UTF-8. encodings. In
* general any character encoding that is isomorphic with respect to the
* exclusive use of the CR (0xD) and the LF (0xA) codes. Equivalent to:<br>
* readLine(ByteBuffer, ByteArrayBuilder, Charset.defaultCharset());
*
* @param mbBuf Given ByteBuffer or MappedByteBuffer
* @param bab an optional ByteArrayBuilder for internal reuse, which will
* improve multi-line reading performance. The result of the read as an array
* of bytes is available from the bab.
* @return the line as a string
*
*/
public static String readLine(final ByteBuffer mbBuf, final ByteArrayBuilder bab) {
return readLine(mbBuf, bab, Charset.defaultCharset());
}
/**
* Reads bytes from the given (Mapped)ByteBuffer until either a CR, LF or CRLF
* is detected in the byte stream and then converts the captured bytes,
* excluding the CR and LF characters into a string. This method will work
* with US-ASCII, ISO-8859 families, Windows 1252, and UTF-8. encodings. In
* general any character encoding that is isomorphic with respect to the
* exclusive use of the CR (0xD) and the LF (0xA) codes.
*
* @param mbBuf Given ByteBuffer or MappedByteBuffer
* @param bab an optional ByteArrayBuilder for internal reuse, which will
* improve multiline reading performance. The result of the read as an array
* of bytes is available from the bab.
* @param charset The Charset to use when converting arrays of bytes from the
* source to a Unicode String (UTF-16).
* @return The characters of a line, or NULL if End-of-File, or "" if line was
* empty.
*/
public static String readLine(final ByteBuffer mbBuf, final ByteArrayBuilder bab,
final Charset charset) {
if (!mbBuf.hasRemaining()) {
return null;
}
final ByteArrayBuilder bab1;
if (bab == null) {
bab1 = new ByteArrayBuilder();
} else {
bab1 = bab;
bab1.setLength(0);
}
while (mbBuf.hasRemaining()) {
final byte b = mbBuf.get();
if (b == LF) {
break; // EOL
}
if (b == CR) {
if (mbBuf.hasRemaining()) {
// peek next byte without moving position
if (mbBuf.get(mbBuf.position()) == LF) {
mbBuf.get(); // consume it
}
}
break; // EOL
}
bab1.append(b); // transfer the byte
}
if (bab1.length() == 0) {
if (!mbBuf.hasRemaining()) {
return null;
}
return "";
}
final byte[] out = bab1.toByteArray();
final String s = new String(out, charset);
return s;
}
/**
* Reads a ByteBuffer (or subclass) with a request for numBytes. The result is
* stuffed into the provided byte[] array (required), which must be larger or
* equal to numBytes.
*
* @param bb The ByteBuffer to read from
* @param numBytes The requested number of bytes to read.
* @param out The target array for the bytes.
* @return the actual number of bytes read.
* @throws java.nio.BufferUnderflowException if numBytes is greater than bytes
* available in the buffer.
*/
public static int readByteBuffer(final ByteBuffer bb, final int numBytes, final byte[] out) {
final int rem = bb.remaining();
if (rem == 0) {
return 0;
}
final int nBytes = rem < numBytes ? rem : numBytes;
bb.get(out);
return nBytes;
}
// FileChannel methods
/**
* Sets the FileChannel position.
*
* @param fc FileChannel
* @param position the position
* @throws RuntimeException if an IOException occurs.
*/
public static void position(final FileChannel fc, final long position) {
try {
fc.position(position);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
/**
* Gets the current size of the FileChannel.
*
* @param fc FileChannel
* @return the size in bytes.
* @throws RuntimeException if an IOException occurs.
*/
public static long size(final FileChannel fc) {
final long sz;
try {
sz = fc.size();
} catch (final IOException e) {
throw new RuntimeException(e);
}
return sz;
}
/**
* Appends the given string to the end of the file specified via the given
* FileChannel. Equivalent to:<br>
* append(String, FileChannel, Charset.defaultCharset());
*
* @param out the string to append
* @param fc the given FileChannel
* @return the number of bytes actually appended.
* @throws RuntimeException if an IOException occurs.
*/
public static int append(final String out, final FileChannel fc) {
return append(out, fc, Charset.defaultCharset());
}
/**
* Appends the given string to the end of the file specified via the given
* FileChannel.
*
* @param out the string to append
* @param fc the given FileChannel
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @return the number of bytes actually appended.
* @throws RuntimeException if an IOException occurs.
*/
public static int append(final String out, final FileChannel fc, final Charset charset) {
final int bytes;
final ByteBuffer bb = ByteBuffer.wrap(out.getBytes(charset));
try {
bytes = fc.write(bb, fc.size());
} catch (final IOException e) {
throw new RuntimeException(e);
}
return bytes;
}
/**
* Appends the given byteArr to the end of the file specified via the given
* FileChannel.
*
* @param byteArr the byte[] to append
* @param fc the given FileChannel
* @return the number of bytes actually appended.
* @throws RuntimeException if an IOException occurs.
*/
public static int append(final byte[] byteArr, final FileChannel fc) {
final int bytes;
final ByteBuffer bb = ByteBuffer.wrap(byteArr);
try {
bytes = fc.write(bb, fc.size());
} catch (final IOException e) {
throw new RuntimeException(e);
}
return bytes;
}
/**
* Writes the given string out to the file specified via the given FileChannel
* starting at the given file position. Equivalent to:<br>
* write(String, FileChannel, long, Charset.defaultCharset());
*
* @param out the given string
* @param fc FileChannel
* @param position the position
* @return the total number of bytes written.
* @throws RuntimeException if an IOException occurs.
*/
public static int write(final String out, final FileChannel fc, final long position) {
return write(out, fc, position, Charset.defaultCharset());
}
/**
* Writes the given string out to the file specified via the given FileChannel
* starting at the given file position.
*
* @param out the given string
* @param fc FileChannel
* @param position the given position
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @return the total number of bytes written.
* @throws RuntimeException if an IOException occurs.
*/
public static int write(final String out, final FileChannel fc, final long position,
final Charset charset) {
final int bytes;
final ByteBuffer bb = ByteBuffer.wrap(out.getBytes(charset));
try {
bytes = fc.write(bb, position);
} catch (final IOException e) {
throw new RuntimeException(e);
}
return bytes;
}
/**
* Writes the given byteArr to the file specified via the given FileChannel at
* the given position.
*
* @param byteArr the byte[] to append
* @param fc the given FileChannel
* @param position the given position
* @return the number of bytes actually appended.
* @throws RuntimeException if an IOException occurs.
*/
public static int write(final byte[] byteArr, final FileChannel fc, final long position) {
final int bytes;
final ByteBuffer bb = ByteBuffer.wrap(byteArr);
try {
bytes = fc.write(bb, position);
} catch (final IOException e) {
throw new RuntimeException(e);
}
return bytes;
}
// Complete NIO BASED FILE WRITE OPERATIONS
/**
* Writes the given String text to the fileName using NIO FileChannel.
*
* @param text Source string to place in a file. Equivalent to: <br>
* stringToFileNIO(String, String, Charset.defaultCharset());
* @param fileName name of target file
* @return the total number of bytes written.
* @throws RuntimeException if an IOException occurs.
*/
public static int stringToFileNIO(final String text, final String fileName) {
return stringToFileNIO(text, fileName, Charset.defaultCharset());
}
/**
* Writes the given String text to the fileName using NIO FileChannel
*
* @param text Source string to place in a file.
* @param fileName name of target file
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @return the total number of bytes written.
* @throws RuntimeException if an IOException occurs.
*/
//@SuppressWarnings("resource")
public static int stringToFileNIO(final String text, final String fileName,
final Charset charset) {
checkFileName(fileName);
final File file = new File(fileName);
int bytes = 0;
if (!file.isFile()) {
try {
file.createNewFile();
} catch (final IOException e) {
throw new RuntimeException("Cannot create new file: " + fileName + LS + e);
}
try (FileChannel fc = openRandomAccessFile(file, "rw").getChannel()) {
bytes = write(text, fc, 0L, charset);
} catch (final IOException e) {
throw new RuntimeException("Cannot create File Channel: " + fileName + LS + e);
}
}
return bytes;
}
/**
* Appends a String to a file using NIO. If fileName does not exist, this
* creates a new empty file of that name. This closes the file after
* appending.
*
* @param text is the source String. Equivalent to: <br>
* appendStringToFileNIO(String, String, Charset.defautCharset());
* @param fileName the given fileName
* @return the total number of bytes written
* @throws RuntimeException if IOException or SecurityException occurs, or if
* fileName is null or empty.
*/
public static int appendStringToFileNIO(final String text, final String fileName) {
return appendStringToFileNIO(text, fileName, Charset.defaultCharset());
}
/**
* Appends a String to a file using NIO and a Charset. If fileName does not
* exist, this creates a new empty file of that name. This closes the file
* after appending.
*
* @param text is the source String.
* @param fileName the given fileName
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @return the total number of bytes written
* @throws RuntimeException if IOException or SecurityException occurs, or if
* fileName is null or empty.
*/
//@SuppressWarnings("resource")
public static int appendStringToFileNIO(final String text, final String fileName,
final Charset charset) {
checkFileName(fileName);
final File file = new File(fileName);
if (!file.isFile()) { // does not exist
try {
file.createNewFile();
} catch (final Exception e) {
throw new RuntimeException("Cannot create file: " + fileName + LS + e);
}
}
int bytes = 0;
try (FileChannel fc = openRandomAccessFile(file, "rw").getChannel()) {
bytes = append(text, fc, charset);
} catch (final IOException e) {
throw new RuntimeException("Cannot create File Channel: " + fileName + LS + e);
}
return bytes;
}
// Complete NIO BASED FILE READ OPERATIONS
/**
* Reads a file into a char array using NIO FileChannel, then closes the file. Useful when
* special handling of Line-Separation characters is required. Equivalent to:
* <br>
* fileToCharArrayNIO(String, Charset.defaultCharset());
*
* @param fileName the given fileName
* @return a char[]
* @throws RuntimeException if IOException occurs.
* @throws IllegalArgumentException if File size is greater than
* Integer.MAX_VALUE.
*/
public static char[] fileToCharArrayNIO(final String fileName) {
return fileToCharArrayNIO(fileName, Charset.defaultCharset());
}
/**
* Reads a file into a char array using NIO FileChannel, then closes the file. Useful when
* special handling of Line-Separation characters is required.
*
* @param fileName the given fileName
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @return a char[]
* @throws RuntimeException if IOException occurs.
* @throws IllegalArgumentException if File size is greater than
* Integer.MAX_VALUE.
*/
public static char[] fileToCharArrayNIO(final String fileName, final Charset charset) {
final File file = getExistingFile(fileName);
char[] chArr = null;
try (RandomAccessFile raf = openRandomAccessFile(file, "r");
FileChannel fc = raf.getChannel()) {
final MappedByteBuffer mbBuf = getMappedByteBuffer(fc, READ_ONLY);
final long len = size(fc);
if (len > Integer.MAX_VALUE) {
fc.close();
throw new IllegalArgumentException("File size cannot exceed Integer.MAX_VALUE.");
}
final byte[] in = new byte[(int) len];
mbBuf.get(in); // fill the buffer
final String out = new String(in, charset);
chArr = out.toCharArray();
} catch (final IOException e) {
throw new RuntimeException("Could not create or close File Channel.");
}
return chArr;
}
/**
* Reads a file into a String using NIO FileChannel. Each line of the file is delimited by
* the current operating systems's "line.separator" characters. Closes the
* file. This method is equivalent to:<br>
* fileToStringNIO(String fileName, Charset.defaultCharset())
*
* @param fileName given fileName
* @return a String
* @throws RuntimeException if IOException occurs.
*/
public static String fileToStringNIO(final String fileName) {
return fileToStringNIO(fileName, Charset.defaultCharset());
}
/**
* Reads a file into a String using NIO FileChannel. Each line of the file is delimited by
* the current operating systems's "line.separator" characters. Closes the
* file.
*
* @param fileName given fileName
* @param charset The Charset to use when converting arrays of bytes from the
* source to a Unicode String (UTF-16).
* @return a String
* @throws RuntimeException if IOException occurs.
*/
public static String fileToStringNIO(final String fileName, final Charset charset) {
final File file = getExistingFile(fileName);
final StringBuilder sb = new StringBuilder(1024);
try (RandomAccessFile raf = openRandomAccessFile(file, "r");
FileChannel fChan = raf.getChannel();) {
final MappedByteBuffer mbBuf = getMappedByteBuffer(fChan, READ_ONLY);
final ByteArrayBuilder bab = new ByteArrayBuilder();
String s;
while ((s = readLine(mbBuf, bab, charset)) != null) {
sb.append(s);
sb.append(LS);
}
} catch (final IOException e) {
throw new RuntimeException("Cannot create File Channel.");
}
return sb.toString();
}
// *******************************
// STANDARD IO READER OPERATIONS
// *******************************
/**
* Opens a BufferedReader wrapped around a File. Equivalent to the call<br>
* openBufferedReader(file, DEFAULT_BUFSIZE) Rethrows any IOException as a
* RuntimeException. The returned object must be closed by the calling program.
*
* @param file the given file
* @return BufferedReader object
* @throws RuntimeException if File Not Found.
*/
public static BufferedReader openBufferedReader(final File file) {
return openBufferedReader(file, DEFAULT_BUFSIZE, Charset.defaultCharset());
}
/**
* Opens a BufferedReader wrapped around a FileReader with a specified file
* and buffer size. If bufSize is less than the default (8192) the default
* will be used. The returned object must be closed by the calling program.
*
* @param file the given file
* @param bufSize the given buffer size
* @return a BufferedReader object
* @throws RuntimeException if File Not Found.
*/
public static BufferedReader openBufferedReader(final File file, final int bufSize) {
return openBufferedReader(file, bufSize, Charset.defaultCharset());
}
/**
* Opens a BufferedReader, which specifies a bufSize, wrapped around an
* InputStreamReader, which specifies a Charset. The InputStreamReader wraps a
* FileInputStream. If bufSize is less than the default (8192) the default
* will be used. If the charset is null, Charset.defaultCharset() will be
* used. The returned object must be closed by the calling program.
*
* @param file the given file
* @param bufSize the given buffer size
* @param charset the given Charset
* @return a BufferedReader object
* @throws RuntimeException if FileNotFoundException occurs.
*/
public static BufferedReader openBufferedReader(final File file, final int bufSize,
final Charset charset) {
final int bufSz = bufSize < DEFAULT_BUFSIZE ? DEFAULT_BUFSIZE : bufSize;
final Charset cSet = charset == null ? Charset.defaultCharset() : charset;
BufferedReader in = null; // default bufsize is 8192.
try {
final FileInputStream fis = new FileInputStream(file);
final InputStreamReader isr = new InputStreamReader(fis, cSet);
in = new BufferedReader(isr, bufSz);
} catch (final FileNotFoundException e) { // from FileInputStream
// never opened, so don't close it.
throw new RuntimeException(LS + "File Not Found: " + file.getPath() + LS + e);
}
return in;
}
/**
* Configures a file for string writing. If a file by the same name exists, it will be
* deleted. If fileName is not fully qualified, it will be relative to the root of this
* package. The returned object must be closed by the calling program.
* @param fileName the name of the file to configure
* @return a PrintWriter
*/
public static final PrintWriter openPrintWriter(final String fileName) {
File file = null;
PrintWriter pw = null;
if (fileName != null && !fileName.isEmpty()) {
file = new File(fileName);
if (file.isFile()) {
file.delete(); //remove old file if it exists
} else {
try {
file.createNewFile();
} catch (final Exception e) {
throw new RuntimeException("Cannot create file: " + fileName + LS + e);
}
}
final BufferedWriter bw;
try {
final FileOutputStream fos = new FileOutputStream(file, true);
final OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.defaultCharset());
bw = new BufferedWriter(osw, 8192);
} catch (final IOException e) {
// never opened, so don't close it.
throw new RuntimeException("Could not create: " + file.getPath() + LS + e);
}
pw = new PrintWriter(bw);
}
return pw;
}
/**
* Tests a Reader object if it is ready.
*
* @param in the given Reader
* @return boolean true if ready.
* @throws RuntimeException if IOException occurs.
*/
public static boolean ready(final Reader in) {
boolean out = false;
try {
out = in.ready();
} catch (final IOException e) {
throw new RuntimeException(LS + "Reader.ready() unsuccessful: " + LS + e);
}
return out;
}
/**
* Skips bytes in the given Reader object.
*
* @param in the given Reader
* @param skipLen in bytes.
* @throws RuntimeException if IOException occurs.
*/
public static void skip(final Reader in, final long skipLen) {
try {
in.skip(skipLen);
} catch (final IOException e) {
try {
in.close();
} catch (final IOException f) {
throw new RuntimeException(LS + "Close Unsuccessful" + LS + f);
}
throw new RuntimeException(LS + "Reader.skip(len) unsuccessful: " + LS + e);
}
}
/**
* Reads characters from the given Reader into the given character array.
*
* @param in the given Reader
* @param length number of characters to read
* @param cArr Array must be equal to or larger than length
* @return number of characters actually read from Reader
* @throws RuntimeException if IOException occurs.
*/
public static int readCharacters(final Reader in, final int length, final char[] cArr) {
int readLen = 0;
try {
readLen = in.read(cArr, 0, length);
} catch (final IOException e) {
try {
in.close();
} catch (final IOException f) {
throw new RuntimeException(LS + "Close Unsuccessful" + LS + f);
}
throw new RuntimeException(LS + "Reader.read(char[],0,len) unsuccessful: " + LS + e);
}
return readLen;
}
/**
* Reads a file into a char array, then closes the file. Useful when special
* handling of Line-Separation characters is required. Equivalent to: <br>
* fileToCharArray(String, int, Charset.defaultCharset());
*
* @param fileName the given fileName
* @return a char[]
* @throws RuntimeException if IOException occurs.
* @throws IllegalArgumentException if File size is greater than
* Integer.MAX_VALUE.
*/
public static char[] fileToCharArray(final String fileName) {
return fileToCharArray(fileName, DEFAULT_BUFSIZE, Charset.defaultCharset());
}
/**
* Reads a file into a char array, then closes the file. Useful when special
* handling of Line-Separation characters is required.
*
* @param fileName the given fileName
* @param bufSize if less than 8192 it defaults to 8192
* @param charset The Charset to use when converting arrays of bytes from the
* source to a Unicode String (UTF-16).
* @return a char[]
* @throws RuntimeException if IOException occurs.
* @throws IllegalArgumentException if File size is greater than
* Integer.MAX_VALUE.
*/
public static char[] fileToCharArray(final String fileName, final int bufSize,
final Charset charset) {
final File file = getExistingFile(fileName);
char[] cArr = null;
final long fileLen = (long) (file.length() * 1.1); // 10% headroom
if (fileLen > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
LS + "File Size is too large: " + fileLen + " >" + " Max: " + Integer.MAX_VALUE);
}
final int len = (int) fileLen;
try (BufferedReader in = openBufferedReader(file, bufSize, charset)) {
cArr = new char[len];
in.read(cArr, 0, len);
} catch (final IOException e) { // thrown by read()
throw new RuntimeException(LS + "BufferedReader.read(char[],0,len) unsuccessful: " + LS + e);
}
return cArr;
}
/**
* Reads a file into a String. Each line of the file is delimited by the
* current operating systems's "line.separator" characters. Closes the file.
* Equivalent to: <br>
* fileToString(String, 8192, Charset.defaultCharset());
*
* @param fileName the given fileName
* @return a String
* @throws RuntimeException if IOException occurs.
*/
public static String fileToString(final String fileName) {
return fileToString(fileName, DEFAULT_BUFSIZE, Charset.defaultCharset());
}
/**
* Reads a file into a String. Each line of the file is delimited by the
* current operating systems's "line.separator" characters. Closes the file.
*
* @param fileName the given fileName
* @param bufSize if less than 8192 it defaults to 8192
* @param charset The Charset to use when converting arrays of bytes from the
* source to a Unicode String (UTF-16).
* @return String
* @throws RuntimeException if IOException occurs.
*/
public static String fileToString(final String fileName, final int bufSize,
final Charset charset) {
final StringBuilder sb = new StringBuilder();
final File file = getExistingFile(fileName);
try (BufferedReader in = openBufferedReader(file, bufSize, charset)) {
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append(LS);
}
} catch (final IOException e) { // thrown by readLine()
throw new RuntimeException(LS + "BufferedReader.readLine() unsuccessful: " + LS + e);
}
return sb.toString();
}
// STANDARD IO WRITE OPERATIONS
/**
* Opens a BufferedWriter wrapped around a FileWriter with a specified file
* and buffer size. If bufSize is less than the default (8192) the default
* will be used. The returned object must be closed by the calling program.
*
* @param file the given file
* @param bufSize the given buffer size
* @param append to existing file if true.
* @return BufferedWriter object
* @throws RuntimeException if IOException occurs.
*/
public static BufferedWriter openBufferedWriter(final File file, final int bufSize,
final boolean append) {
return openBufferedWriter(file, bufSize, append, Charset.defaultCharset());
}
/**
* Opens a BufferedWriter wrapped around a FileWriter with a specified file
* and buffer size. If bufSize is less than the default (8192) the default
* will be used. The returned object must be closed by the calling program.
*
* @param file the given file
* @param bufSize if less than 8192 it defaults to 8192.
* @param append to existing file if true.
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @return BufferedWriter object
* @throws RuntimeException if IOException occurs.
*/
public static BufferedWriter openBufferedWriter(final File file, final int bufSize,
final boolean append, final Charset charset) {
final int bufSz = bufSize < DEFAULT_BUFSIZE ? DEFAULT_BUFSIZE : bufSize;
BufferedWriter out = null; // default bufsize is 8192.
try {
final FileOutputStream fos = new FileOutputStream(file, append);
final OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
out = new BufferedWriter(osw, bufSz);
} catch (final IOException e) {
// never opened, so don't close it.
throw new RuntimeException(LS + "Could not create: " + file.getPath() + LS + e);
}
return out;
}
/**
* Writes a String to a file using a BufferedWriter. Closes the file.
*
* @param text is the source String.
* @param fileName the given fileName
* @throws RuntimeException if IOException occurs or if fileName is null or
* empty.
*/
public static void stringToFile(final String text, final String fileName) {
stringToFile(text, fileName, DEFAULT_BUFSIZE, Charset.defaultCharset());
}
/**
* Writes a String to a file using a BufferedWriter. Closes the file.
*
* @param text is the source String.
* @param fileName the given fileName
* @param bufSize if less than 8192 it defaults to 8192.
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @throws RuntimeException if IOException occurs or if fileName is null or
* empty.
*/
public static void stringToFile(final String text, final String fileName, final int bufSize,
final Charset charset) {
checkFileName(fileName);
final File file = new File(fileName);
try (BufferedWriter bw = openBufferedWriter(file, bufSize, false, charset);
PrintWriter out = new PrintWriter(bw);) {
out.print(text);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
/**
* Appends a String to a file using a BufferedWriter. If fileName does not
* exist, this creates a new empty file of that name. This closes the file
* after appending.
*
* @param text is the source String.
* @param fileName the given fileName
* @throws RuntimeException if IOException or SecurityException occurs, or if
* fileName is null or empty.
*/
public static void appendStringToFile(final String text, final String fileName) {
appendStringToFile(text, fileName, DEFAULT_BUFSIZE, Charset.defaultCharset());
}
/**
* Appends a String to a file using a BufferedWriter, bufSize and Charset. If
* fileName does not exist, this creates a new empty file of that name. This
* closes the file after appending.
*
* @param text is the source String.
* @param fileName the given fileName
* @param bufSize if less than 8192 it defaults to 8192.
* @param charset The Charset to use when converting the source string
* (UTF-16) to a sequence of encoded bytes of the Charset.
* @throws RuntimeException if IOException or SecurityException occurs, or if
* fileName is null or empty.
*/
public static void appendStringToFile(final String text, final String fileName,
final int bufSize, final Charset charset) {
checkFileName(fileName);
final File file = new File(fileName);
if (!file.isFile()) { // does not exist
try {
file.createNewFile();
} catch (final Exception e) {
throw new RuntimeException("Cannot create file: " + fileName + LS + e);
}
}
try (BufferedWriter bw = openBufferedWriter(file, bufSize, true, charset);
PrintWriter out = new PrintWriter(bw);) {
out.print(text);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
}
|
googleapis/google-cloud-java | 37,383 | java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/ListAgentsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3/agent.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.cx.v3;
/**
*
*
* <pre>
* The response message for
* [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3.ListAgentsResponse}
*/
public final class ListAgentsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3.ListAgentsResponse)
ListAgentsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAgentsResponse.newBuilder() to construct.
private ListAgentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAgentsResponse() {
agents_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAgentsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ListAgentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ListAgentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.class,
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.Builder.class);
}
public static final int AGENTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.dialogflow.cx.v3.Agent> agents_;
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.cx.v3.Agent> getAgentsList() {
return agents_;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.cx.v3.AgentOrBuilder>
getAgentsOrBuilderList() {
return agents_;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
@java.lang.Override
public int getAgentsCount() {
return agents_.size();
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.Agent getAgents(int index) {
return agents_.get(index);
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.AgentOrBuilder getAgentsOrBuilder(int index) {
return agents_.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 < agents_.size(); i++) {
output.writeMessage(1, agents_.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 < agents_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, agents_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.cx.v3.ListAgentsResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse other =
(com.google.cloud.dialogflow.cx.v3.ListAgentsResponse) obj;
if (!getAgentsList().equals(other.getAgentsList())) 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 (getAgentsCount() > 0) {
hash = (37 * hash) + AGENTS_FIELD_NUMBER;
hash = (53 * hash) + getAgentsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dialogflow.cx.v3.ListAgentsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response message for
* [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3.ListAgentsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3.ListAgentsResponse)
com.google.cloud.dialogflow.cx.v3.ListAgentsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ListAgentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ListAgentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.class,
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (agentsBuilder_ == null) {
agents_ = java.util.Collections.emptyList();
} else {
agents_ = null;
agentsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.cx.v3.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3_ListAgentsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListAgentsResponse getDefaultInstanceForType() {
return com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListAgentsResponse build() {
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListAgentsResponse buildPartial() {
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse result =
new com.google.cloud.dialogflow.cx.v3.ListAgentsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.dialogflow.cx.v3.ListAgentsResponse result) {
if (agentsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
agents_ = java.util.Collections.unmodifiableList(agents_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.agents_ = agents_;
} else {
result.agents_ = agentsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.dialogflow.cx.v3.ListAgentsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.cx.v3.ListAgentsResponse) {
return mergeFrom((com.google.cloud.dialogflow.cx.v3.ListAgentsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3.ListAgentsResponse other) {
if (other == com.google.cloud.dialogflow.cx.v3.ListAgentsResponse.getDefaultInstance())
return this;
if (agentsBuilder_ == null) {
if (!other.agents_.isEmpty()) {
if (agents_.isEmpty()) {
agents_ = other.agents_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureAgentsIsMutable();
agents_.addAll(other.agents_);
}
onChanged();
}
} else {
if (!other.agents_.isEmpty()) {
if (agentsBuilder_.isEmpty()) {
agentsBuilder_.dispose();
agentsBuilder_ = null;
agents_ = other.agents_;
bitField0_ = (bitField0_ & ~0x00000001);
agentsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getAgentsFieldBuilder()
: null;
} else {
agentsBuilder_.addAllMessages(other.agents_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.dialogflow.cx.v3.Agent m =
input.readMessage(
com.google.cloud.dialogflow.cx.v3.Agent.parser(), extensionRegistry);
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.add(m);
} else {
agentsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.dialogflow.cx.v3.Agent> agents_ =
java.util.Collections.emptyList();
private void ensureAgentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
agents_ = new java.util.ArrayList<com.google.cloud.dialogflow.cx.v3.Agent>(agents_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3.Agent,
com.google.cloud.dialogflow.cx.v3.Agent.Builder,
com.google.cloud.dialogflow.cx.v3.AgentOrBuilder>
agentsBuilder_;
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.cx.v3.Agent> getAgentsList() {
if (agentsBuilder_ == null) {
return java.util.Collections.unmodifiableList(agents_);
} else {
return agentsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public int getAgentsCount() {
if (agentsBuilder_ == null) {
return agents_.size();
} else {
return agentsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Agent getAgents(int index) {
if (agentsBuilder_ == null) {
return agents_.get(index);
} else {
return agentsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder setAgents(int index, com.google.cloud.dialogflow.cx.v3.Agent value) {
if (agentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAgentsIsMutable();
agents_.set(index, value);
onChanged();
} else {
agentsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder setAgents(
int index, com.google.cloud.dialogflow.cx.v3.Agent.Builder builderForValue) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.set(index, builderForValue.build());
onChanged();
} else {
agentsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder addAgents(com.google.cloud.dialogflow.cx.v3.Agent value) {
if (agentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAgentsIsMutable();
agents_.add(value);
onChanged();
} else {
agentsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder addAgents(int index, com.google.cloud.dialogflow.cx.v3.Agent value) {
if (agentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAgentsIsMutable();
agents_.add(index, value);
onChanged();
} else {
agentsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder addAgents(com.google.cloud.dialogflow.cx.v3.Agent.Builder builderForValue) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.add(builderForValue.build());
onChanged();
} else {
agentsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder addAgents(
int index, com.google.cloud.dialogflow.cx.v3.Agent.Builder builderForValue) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.add(index, builderForValue.build());
onChanged();
} else {
agentsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder addAllAgents(
java.lang.Iterable<? extends com.google.cloud.dialogflow.cx.v3.Agent> values) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, agents_);
onChanged();
} else {
agentsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder clearAgents() {
if (agentsBuilder_ == null) {
agents_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
agentsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public Builder removeAgents(int index) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.remove(index);
onChanged();
} else {
agentsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Agent.Builder getAgentsBuilder(int index) {
return getAgentsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.AgentOrBuilder getAgentsOrBuilder(int index) {
if (agentsBuilder_ == null) {
return agents_.get(index);
} else {
return agentsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.cx.v3.AgentOrBuilder>
getAgentsOrBuilderList() {
if (agentsBuilder_ != null) {
return agentsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(agents_);
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Agent.Builder addAgentsBuilder() {
return getAgentsFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.cx.v3.Agent.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Agent.Builder addAgentsBuilder(int index) {
return getAgentsFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.cx.v3.Agent.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Agent agents = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.cx.v3.Agent.Builder> getAgentsBuilderList() {
return getAgentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3.Agent,
com.google.cloud.dialogflow.cx.v3.Agent.Builder,
com.google.cloud.dialogflow.cx.v3.AgentOrBuilder>
getAgentsFieldBuilder() {
if (agentsBuilder_ == null) {
agentsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3.Agent,
com.google.cloud.dialogflow.cx.v3.Agent.Builder,
com.google.cloud.dialogflow.cx.v3.AgentOrBuilder>(
agents_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
agents_ = null;
}
return agentsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.cx.v3.ListAgentsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3.ListAgentsResponse)
private static final com.google.cloud.dialogflow.cx.v3.ListAgentsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3.ListAgentsResponse();
}
public static com.google.cloud.dialogflow.cx.v3.ListAgentsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAgentsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAgentsResponse>() {
@java.lang.Override
public ListAgentsResponse 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<ListAgentsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAgentsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListAgentsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,396 | java-domains/proto-google-cloud-domains-v1beta1/src/main/java/com/google/cloud/domains/v1beta1/ListRegistrationsResponse.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/domains/v1beta1/domains.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.domains.v1beta1;
/**
*
*
* <pre>
* Response for the `ListRegistrations` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.ListRegistrationsResponse}
*/
public final class ListRegistrationsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.domains.v1beta1.ListRegistrationsResponse)
ListRegistrationsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListRegistrationsResponse.newBuilder() to construct.
private ListRegistrationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListRegistrationsResponse() {
registrations_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListRegistrationsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ListRegistrationsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ListRegistrationsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.ListRegistrationsResponse.class,
com.google.cloud.domains.v1beta1.ListRegistrationsResponse.Builder.class);
}
public static final int REGISTRATIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.domains.v1beta1.Registration> registrations_;
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.domains.v1beta1.Registration> getRegistrationsList() {
return registrations_;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.domains.v1beta1.RegistrationOrBuilder>
getRegistrationsOrBuilderList() {
return registrations_;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
@java.lang.Override
public int getRegistrationsCount() {
return registrations_.size();
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
@java.lang.Override
public com.google.cloud.domains.v1beta1.Registration getRegistrations(int index) {
return registrations_.get(index);
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
@java.lang.Override
public com.google.cloud.domains.v1beta1.RegistrationOrBuilder getRegistrationsOrBuilder(
int index) {
return registrations_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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 < registrations_.size(); i++) {
output.writeMessage(1, registrations_.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 < registrations_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, registrations_.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.domains.v1beta1.ListRegistrationsResponse)) {
return super.equals(obj);
}
com.google.cloud.domains.v1beta1.ListRegistrationsResponse other =
(com.google.cloud.domains.v1beta1.ListRegistrationsResponse) obj;
if (!getRegistrationsList().equals(other.getRegistrationsList())) 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 (getRegistrationsCount() > 0) {
hash = (37 * hash) + REGISTRATIONS_FIELD_NUMBER;
hash = (53 * hash) + getRegistrationsList().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.domains.v1beta1.ListRegistrationsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse 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.domains.v1beta1.ListRegistrationsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse 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.domains.v1beta1.ListRegistrationsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse 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.domains.v1beta1.ListRegistrationsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse 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.domains.v1beta1.ListRegistrationsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse 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.domains.v1beta1.ListRegistrationsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response for the `ListRegistrations` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.ListRegistrationsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.domains.v1beta1.ListRegistrationsResponse)
com.google.cloud.domains.v1beta1.ListRegistrationsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ListRegistrationsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ListRegistrationsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.ListRegistrationsResponse.class,
com.google.cloud.domains.v1beta1.ListRegistrationsResponse.Builder.class);
}
// Construct using com.google.cloud.domains.v1beta1.ListRegistrationsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (registrationsBuilder_ == null) {
registrations_ = java.util.Collections.emptyList();
} else {
registrations_ = null;
registrationsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ListRegistrationsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ListRegistrationsResponse getDefaultInstanceForType() {
return com.google.cloud.domains.v1beta1.ListRegistrationsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ListRegistrationsResponse build() {
com.google.cloud.domains.v1beta1.ListRegistrationsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ListRegistrationsResponse buildPartial() {
com.google.cloud.domains.v1beta1.ListRegistrationsResponse result =
new com.google.cloud.domains.v1beta1.ListRegistrationsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.domains.v1beta1.ListRegistrationsResponse result) {
if (registrationsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
registrations_ = java.util.Collections.unmodifiableList(registrations_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.registrations_ = registrations_;
} else {
result.registrations_ = registrationsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.domains.v1beta1.ListRegistrationsResponse 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.domains.v1beta1.ListRegistrationsResponse) {
return mergeFrom((com.google.cloud.domains.v1beta1.ListRegistrationsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.domains.v1beta1.ListRegistrationsResponse other) {
if (other == com.google.cloud.domains.v1beta1.ListRegistrationsResponse.getDefaultInstance())
return this;
if (registrationsBuilder_ == null) {
if (!other.registrations_.isEmpty()) {
if (registrations_.isEmpty()) {
registrations_ = other.registrations_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureRegistrationsIsMutable();
registrations_.addAll(other.registrations_);
}
onChanged();
}
} else {
if (!other.registrations_.isEmpty()) {
if (registrationsBuilder_.isEmpty()) {
registrationsBuilder_.dispose();
registrationsBuilder_ = null;
registrations_ = other.registrations_;
bitField0_ = (bitField0_ & ~0x00000001);
registrationsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getRegistrationsFieldBuilder()
: null;
} else {
registrationsBuilder_.addAllMessages(other.registrations_);
}
}
}
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.domains.v1beta1.Registration m =
input.readMessage(
com.google.cloud.domains.v1beta1.Registration.parser(), extensionRegistry);
if (registrationsBuilder_ == null) {
ensureRegistrationsIsMutable();
registrations_.add(m);
} else {
registrationsBuilder_.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.domains.v1beta1.Registration> registrations_ =
java.util.Collections.emptyList();
private void ensureRegistrationsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
registrations_ =
new java.util.ArrayList<com.google.cloud.domains.v1beta1.Registration>(registrations_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.domains.v1beta1.Registration,
com.google.cloud.domains.v1beta1.Registration.Builder,
com.google.cloud.domains.v1beta1.RegistrationOrBuilder>
registrationsBuilder_;
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public java.util.List<com.google.cloud.domains.v1beta1.Registration> getRegistrationsList() {
if (registrationsBuilder_ == null) {
return java.util.Collections.unmodifiableList(registrations_);
} else {
return registrationsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public int getRegistrationsCount() {
if (registrationsBuilder_ == null) {
return registrations_.size();
} else {
return registrationsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public com.google.cloud.domains.v1beta1.Registration getRegistrations(int index) {
if (registrationsBuilder_ == null) {
return registrations_.get(index);
} else {
return registrationsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder setRegistrations(
int index, com.google.cloud.domains.v1beta1.Registration value) {
if (registrationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRegistrationsIsMutable();
registrations_.set(index, value);
onChanged();
} else {
registrationsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder setRegistrations(
int index, com.google.cloud.domains.v1beta1.Registration.Builder builderForValue) {
if (registrationsBuilder_ == null) {
ensureRegistrationsIsMutable();
registrations_.set(index, builderForValue.build());
onChanged();
} else {
registrationsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder addRegistrations(com.google.cloud.domains.v1beta1.Registration value) {
if (registrationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRegistrationsIsMutable();
registrations_.add(value);
onChanged();
} else {
registrationsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder addRegistrations(
int index, com.google.cloud.domains.v1beta1.Registration value) {
if (registrationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRegistrationsIsMutable();
registrations_.add(index, value);
onChanged();
} else {
registrationsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder addRegistrations(
com.google.cloud.domains.v1beta1.Registration.Builder builderForValue) {
if (registrationsBuilder_ == null) {
ensureRegistrationsIsMutable();
registrations_.add(builderForValue.build());
onChanged();
} else {
registrationsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder addRegistrations(
int index, com.google.cloud.domains.v1beta1.Registration.Builder builderForValue) {
if (registrationsBuilder_ == null) {
ensureRegistrationsIsMutable();
registrations_.add(index, builderForValue.build());
onChanged();
} else {
registrationsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder addAllRegistrations(
java.lang.Iterable<? extends com.google.cloud.domains.v1beta1.Registration> values) {
if (registrationsBuilder_ == null) {
ensureRegistrationsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, registrations_);
onChanged();
} else {
registrationsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder clearRegistrations() {
if (registrationsBuilder_ == null) {
registrations_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
registrationsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public Builder removeRegistrations(int index) {
if (registrationsBuilder_ == null) {
ensureRegistrationsIsMutable();
registrations_.remove(index);
onChanged();
} else {
registrationsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public com.google.cloud.domains.v1beta1.Registration.Builder getRegistrationsBuilder(
int index) {
return getRegistrationsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public com.google.cloud.domains.v1beta1.RegistrationOrBuilder getRegistrationsOrBuilder(
int index) {
if (registrationsBuilder_ == null) {
return registrations_.get(index);
} else {
return registrationsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public java.util.List<? extends com.google.cloud.domains.v1beta1.RegistrationOrBuilder>
getRegistrationsOrBuilderList() {
if (registrationsBuilder_ != null) {
return registrationsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(registrations_);
}
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public com.google.cloud.domains.v1beta1.Registration.Builder addRegistrationsBuilder() {
return getRegistrationsFieldBuilder()
.addBuilder(com.google.cloud.domains.v1beta1.Registration.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public com.google.cloud.domains.v1beta1.Registration.Builder addRegistrationsBuilder(
int index) {
return getRegistrationsFieldBuilder()
.addBuilder(index, com.google.cloud.domains.v1beta1.Registration.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of `Registration`s.
* </pre>
*
* <code>repeated .google.cloud.domains.v1beta1.Registration registrations = 1;</code>
*/
public java.util.List<com.google.cloud.domains.v1beta1.Registration.Builder>
getRegistrationsBuilderList() {
return getRegistrationsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.domains.v1beta1.Registration,
com.google.cloud.domains.v1beta1.Registration.Builder,
com.google.cloud.domains.v1beta1.RegistrationOrBuilder>
getRegistrationsFieldBuilder() {
if (registrationsBuilder_ == null) {
registrationsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.domains.v1beta1.Registration,
com.google.cloud.domains.v1beta1.Registration.Builder,
com.google.cloud.domains.v1beta1.RegistrationOrBuilder>(
registrations_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
registrations_ = null;
}
return registrationsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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>
* When present, there are more results to retrieve. Set `page_token` to this
* value on a subsequent call to get 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.cloud.domains.v1beta1.ListRegistrationsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.domains.v1beta1.ListRegistrationsResponse)
private static final com.google.cloud.domains.v1beta1.ListRegistrationsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.domains.v1beta1.ListRegistrationsResponse();
}
public static com.google.cloud.domains.v1beta1.ListRegistrationsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListRegistrationsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListRegistrationsResponse>() {
@java.lang.Override
public ListRegistrationsResponse 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<ListRegistrationsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListRegistrationsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ListRegistrationsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,401 | java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/UpdateChannelGroupRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/analytics/admin/v1alpha/analytics_admin.proto
// Protobuf Java Version: 3.25.8
package com.google.analytics.admin.v1alpha;
/**
*
*
* <pre>
* Request message for UpdateChannelGroup RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdateChannelGroupRequest}
*/
public final class UpdateChannelGroupRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.UpdateChannelGroupRequest)
UpdateChannelGroupRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateChannelGroupRequest.newBuilder() to construct.
private UpdateChannelGroupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateChannelGroupRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateChannelGroupRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateChannelGroupRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateChannelGroupRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.class,
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.Builder.class);
}
private int bitField0_;
public static final int CHANNEL_GROUP_FIELD_NUMBER = 1;
private com.google.analytics.admin.v1alpha.ChannelGroup channelGroup_;
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the channelGroup field is set.
*/
@java.lang.Override
public boolean hasChannelGroup() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The channelGroup.
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.ChannelGroup getChannelGroup() {
return channelGroup_ == null
? com.google.analytics.admin.v1alpha.ChannelGroup.getDefaultInstance()
: channelGroup_;
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.ChannelGroupOrBuilder getChannelGroupOrBuilder() {
return channelGroup_ == null
? com.google.analytics.admin.v1alpha.ChannelGroup.getDefaultInstance()
: channelGroup_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getChannelGroup());
}
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, getChannelGroup());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest other =
(com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest) obj;
if (hasChannelGroup() != other.hasChannelGroup()) return false;
if (hasChannelGroup()) {
if (!getChannelGroup().equals(other.getChannelGroup())) 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 (hasChannelGroup()) {
hash = (37 * hash) + CHANNEL_GROUP_FIELD_NUMBER;
hash = (53 * hash) + getChannelGroup().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest 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 UpdateChannelGroup RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdateChannelGroupRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.UpdateChannelGroupRequest)
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateChannelGroupRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateChannelGroupRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.class,
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.Builder.class);
}
// Construct using com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getChannelGroupFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
channelGroup_ = null;
if (channelGroupBuilder_ != null) {
channelGroupBuilder_.dispose();
channelGroupBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateChannelGroupRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest
getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest build() {
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest buildPartial() {
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest result =
new com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.channelGroup_ =
channelGroupBuilder_ == null ? channelGroup_ : channelGroupBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest) {
return mergeFrom((com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest other) {
if (other
== com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest.getDefaultInstance())
return this;
if (other.hasChannelGroup()) {
mergeChannelGroup(other.getChannelGroup());
}
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(getChannelGroupFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.analytics.admin.v1alpha.ChannelGroup channelGroup_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.ChannelGroup,
com.google.analytics.admin.v1alpha.ChannelGroup.Builder,
com.google.analytics.admin.v1alpha.ChannelGroupOrBuilder>
channelGroupBuilder_;
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the channelGroup field is set.
*/
public boolean hasChannelGroup() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The channelGroup.
*/
public com.google.analytics.admin.v1alpha.ChannelGroup getChannelGroup() {
if (channelGroupBuilder_ == null) {
return channelGroup_ == null
? com.google.analytics.admin.v1alpha.ChannelGroup.getDefaultInstance()
: channelGroup_;
} else {
return channelGroupBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setChannelGroup(com.google.analytics.admin.v1alpha.ChannelGroup value) {
if (channelGroupBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
channelGroup_ = value;
} else {
channelGroupBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setChannelGroup(
com.google.analytics.admin.v1alpha.ChannelGroup.Builder builderForValue) {
if (channelGroupBuilder_ == null) {
channelGroup_ = builderForValue.build();
} else {
channelGroupBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeChannelGroup(com.google.analytics.admin.v1alpha.ChannelGroup value) {
if (channelGroupBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& channelGroup_ != null
&& channelGroup_
!= com.google.analytics.admin.v1alpha.ChannelGroup.getDefaultInstance()) {
getChannelGroupBuilder().mergeFrom(value);
} else {
channelGroup_ = value;
}
} else {
channelGroupBuilder_.mergeFrom(value);
}
if (channelGroup_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearChannelGroup() {
bitField0_ = (bitField0_ & ~0x00000001);
channelGroup_ = null;
if (channelGroupBuilder_ != null) {
channelGroupBuilder_.dispose();
channelGroupBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.analytics.admin.v1alpha.ChannelGroup.Builder getChannelGroupBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getChannelGroupFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.analytics.admin.v1alpha.ChannelGroupOrBuilder getChannelGroupOrBuilder() {
if (channelGroupBuilder_ != null) {
return channelGroupBuilder_.getMessageOrBuilder();
} else {
return channelGroup_ == null
? com.google.analytics.admin.v1alpha.ChannelGroup.getDefaultInstance()
: channelGroup_;
}
}
/**
*
*
* <pre>
* Required. The ChannelGroup to update.
* The resource's `name` field is used to identify the ChannelGroup to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.ChannelGroup channel_group = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.ChannelGroup,
com.google.analytics.admin.v1alpha.ChannelGroup.Builder,
com.google.analytics.admin.v1alpha.ChannelGroupOrBuilder>
getChannelGroupFieldBuilder() {
if (channelGroupBuilder_ == null) {
channelGroupBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.ChannelGroup,
com.google.analytics.admin.v1alpha.ChannelGroup.Builder,
com.google.analytics.admin.v1alpha.ChannelGroupOrBuilder>(
getChannelGroup(), getParentForChildren(), isClean());
channelGroup_ = null;
}
return channelGroupBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.UpdateChannelGroupRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.UpdateChannelGroupRequest)
private static final com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest();
}
public static com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateChannelGroupRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateChannelGroupRequest>() {
@java.lang.Override
public UpdateChannelGroupRequest 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<UpdateChannelGroupRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateChannelGroupRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateChannelGroupRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/flink-cdc | 37,483 | flink-cdc-connect/flink-cdc-source-connectors/flink-connector-postgres-cdc/src/main/java/io/debezium/connector/postgresql/connection/PostgresConnection.java | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.connector.postgresql.connection;
import com.zaxxer.hikari.pool.HikariProxyConnection;
import io.debezium.DebeziumException;
import io.debezium.annotation.VisibleForTesting;
import io.debezium.config.Configuration;
import io.debezium.connector.postgresql.PgOid;
import io.debezium.connector.postgresql.PostgresConnectorConfig;
import io.debezium.connector.postgresql.PostgresSchema;
import io.debezium.connector.postgresql.PostgresType;
import io.debezium.connector.postgresql.PostgresValueConverter;
import io.debezium.connector.postgresql.TypeRegistry;
import io.debezium.connector.postgresql.spi.SlotState;
import io.debezium.data.SpecialValueDecimal;
import io.debezium.jdbc.JdbcConfiguration;
import io.debezium.jdbc.JdbcConnection;
import io.debezium.relational.Column;
import io.debezium.relational.ColumnEditor;
import io.debezium.relational.Table;
import io.debezium.relational.TableId;
import io.debezium.relational.Tables;
import io.debezium.schema.DatabaseSchema;
import io.debezium.util.Clock;
import io.debezium.util.Metronome;
import org.apache.kafka.connect.errors.ConnectException;
import org.postgresql.core.BaseConnection;
import org.postgresql.jdbc.PgConnection;
import org.postgresql.jdbc.TimestampUtils;
import org.postgresql.replication.LogSequenceNumber;
import org.postgresql.util.PGmoney;
import org.postgresql.util.PSQLState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
/**
* {@link JdbcConnection} connection extension used for connecting to Postgres instances.
*
* @author Horia Chiorean
* <p>Copied from Debezium 1.9.8-Final with three additional methods:
* <ul>
* <li>Constructor PostgresConnection( Configuration config, PostgresValueConverterBuilder
* valueConverterBuilder, ConnectionFactory factory) to allow passing a custom
* ConnectionFactory
* <li>override connection() to return a unwrapped PgConnection (otherwise, it will complain
* about HikariProxyConnection cannot be cast to class org.postgresql.core.BaseConnection)
* <li>override isTableUniqueIndexIncluded: Copied DBZ-5398 from Debezium 2.0.0.Final to fix
* https://github.com/ververica/flink-cdc-connectors/issues/2710. Remove this comment
* after bumping debezium version to 2.0.0.Final.
* </ul>
*/
public class PostgresConnection extends JdbcConnection {
public static final String CONNECTION_STREAMING = "Debezium Streaming";
public static final String CONNECTION_SLOT_INFO = "Debezium Slot Info";
public static final String CONNECTION_DROP_SLOT = "Debezium Drop Slot";
public static final String CONNECTION_VALIDATE_CONNECTION = "Debezium Validate Connection";
public static final String CONNECTION_HEARTBEAT = "Debezium Heartbeat";
public static final String CONNECTION_GENERAL = "Debezium General";
private static final Pattern FUNCTION_DEFAULT_PATTERN =
Pattern.compile("^[(]?[A-Za-z0-9_.]+\\((?:.+(?:, ?.+)*)?\\)");
private static final Pattern EXPRESSION_DEFAULT_PATTERN =
Pattern.compile("\\(+(?:.+(?:[+ - * / < > = ~ ! @ # % ^ & | ` ?] ?.+)+)+\\)");
private static Logger LOGGER = LoggerFactory.getLogger(PostgresConnection.class);
private static final String URL_PATTERN =
"jdbc:postgresql://${"
+ JdbcConfiguration.HOSTNAME
+ "}:${"
+ JdbcConfiguration.PORT
+ "}/${"
+ JdbcConfiguration.DATABASE
+ "}";
protected static final ConnectionFactory FACTORY =
JdbcConnection.patternBasedFactory(
URL_PATTERN,
org.postgresql.Driver.class.getName(),
PostgresConnection.class.getClassLoader(),
JdbcConfiguration.PORT.withDefault(
PostgresConnectorConfig.PORT.defaultValueAsString()));
/**
* Obtaining a replication slot may fail if there's a pending transaction. We're retrying to get
* a slot for 30 min.
*/
private static final int MAX_ATTEMPTS_FOR_OBTAINING_REPLICATION_SLOT = 900;
private static final Duration PAUSE_BETWEEN_REPLICATION_SLOT_RETRIEVAL_ATTEMPTS =
Duration.ofSeconds(2);
private final TypeRegistry typeRegistry;
private final PostgresDefaultValueConverter defaultValueConverter;
/**
* Creates a Postgres connection using the supplied configuration. If necessary this connection
* is able to resolve data type mappings. Such a connection requires a {@link
* PostgresValueConverter}, and will provide its own {@link TypeRegistry}. Usually only one such
* connection per connector is needed.
*
* @param config {@link Configuration} instance, may not be null.
* @param valueConverterBuilder supplies a configured {@link PostgresValueConverter} for a given
* {@link TypeRegistry}
* @param connectionUsage a symbolic name of the connection to be tracked in monitoring tools
*/
public PostgresConnection(
JdbcConfiguration config,
PostgresValueConverterBuilder valueConverterBuilder,
String connectionUsage) {
this(config, valueConverterBuilder, connectionUsage, FACTORY);
}
/**
* Creates a Postgres connection using the supplied configuration. If necessary this connection
* is able to resolve data type mappings. Such a connection requires a {@link
* PostgresValueConverter}, and will provide its own {@link TypeRegistry}. Usually only one such
* connection per connector is needed.
*
* @param config {@link Configuration} instance, may not be null.
* @param valueConverterBuilder supplies a configured {@link PostgresValueConverter} for a given
* {@link TypeRegistry}
* @param connectionUsage a symbolic name of the connection to be tracked in monitoring tools
*/
public PostgresConnection(
JdbcConfiguration config,
PostgresValueConverterBuilder valueConverterBuilder,
String connectionUsage,
ConnectionFactory factory) {
super(
addDefaultSettings(config, connectionUsage),
factory,
PostgresConnection::validateServerVersion,
null,
"\"",
"\"");
if (Objects.isNull(valueConverterBuilder)) {
this.typeRegistry = null;
this.defaultValueConverter = null;
} else {
this.typeRegistry = new TypeRegistry(this);
final PostgresValueConverter valueConverter =
valueConverterBuilder.build(this.typeRegistry);
this.defaultValueConverter =
new PostgresDefaultValueConverter(valueConverter, this.getTimestampUtils());
}
}
/**
* Create a Postgres connection using the supplied configuration and {@link TypeRegistry}
*
* @param config {@link Configuration} instance, may not be null.
* @param typeRegistry an existing/already-primed {@link TypeRegistry} instance
* @param connectionUsage a symbolic name of the connection to be tracked in monitoring tools
*/
public PostgresConnection(
PostgresConnectorConfig config, TypeRegistry typeRegistry, String connectionUsage) {
super(
addDefaultSettings(config.getJdbcConfig(), connectionUsage),
FACTORY,
PostgresConnection::validateServerVersion,
null,
"\"",
"\"");
if (Objects.isNull(typeRegistry)) {
this.typeRegistry = null;
this.defaultValueConverter = null;
} else {
this.typeRegistry = typeRegistry;
final PostgresValueConverter valueConverter =
PostgresValueConverter.of(config, this.getDatabaseCharset(), typeRegistry);
this.defaultValueConverter =
new PostgresDefaultValueConverter(valueConverter, this.getTimestampUtils());
}
}
/**
* Creates a Postgres connection using the supplied configuration. The connector is the regular
* one without datatype resolution capabilities.
*
* @param config {@link Configuration} instance, may not be null.
* @param connectionUsage a symbolic name of the connection to be tracked in monitoring tools
*/
public PostgresConnection(JdbcConfiguration config, String connectionUsage) {
this(config, null, connectionUsage);
}
/** Return an unwrapped PgConnection instead of HikariProxyConnection */
@Override
public synchronized Connection connection() throws SQLException {
Connection conn = connection(true);
if (conn instanceof HikariProxyConnection) {
// assuming HikariCP use org.postgresql.jdbc.PgConnection
return conn.unwrap(PgConnection.class);
}
return conn;
}
static JdbcConfiguration addDefaultSettings(
JdbcConfiguration configuration, String connectionUsage) {
// we require Postgres 9.4 as the minimum server version since that's where logical
// replication was first introduced
return JdbcConfiguration.adapt(
configuration
.edit()
.with("assumeMinServerVersion", "9.4")
.with("ApplicationName", connectionUsage)
.build());
}
/**
* Returns a JDBC connection string for the current configuration.
*
* @return a {@code String} where the variables in {@code urlPattern} are replaced with values
* from the configuration
*/
public String connectionString() {
return connectionString(URL_PATTERN);
}
/**
* Prints out information about the REPLICA IDENTITY status of a table. This in turn determines
* how much information is available for UPDATE and DELETE operations for logical replication.
*
* @param tableId the identifier of the table
* @return the replica identity information; never null
* @throws SQLException if there is a problem obtaining the replica identity information for the
* given table
*/
public ServerInfo.ReplicaIdentity readReplicaIdentityInfo(TableId tableId) throws SQLException {
String statement =
"SELECT relreplident FROM pg_catalog.pg_class c "
+ "LEFT JOIN pg_catalog.pg_namespace n ON c.relnamespace=n.oid "
+ "WHERE n.nspname=? and c.relname=?";
String schema =
tableId.schema() != null && tableId.schema().length() > 0
? tableId.schema()
: "public";
StringBuilder replIdentity = new StringBuilder();
prepareQuery(
statement,
stmt -> {
stmt.setString(1, schema);
stmt.setString(2, tableId.table());
},
rs -> {
if (rs.next()) {
replIdentity.append(rs.getString(1));
} else {
LOGGER.warn(
"Cannot determine REPLICA IDENTITY information for table '{}'",
tableId);
}
});
return ServerInfo.ReplicaIdentity.parseFromDB(replIdentity.toString());
}
/**
* Returns the current state of the replication slot
*
* @param slotName the name of the slot
* @param pluginName the name of the plugin used for the desired slot
* @return the {@link SlotState} or null, if no slot state is found
* @throws SQLException
*/
public SlotState getReplicationSlotState(String slotName, String pluginName)
throws SQLException {
ServerInfo.ReplicationSlot slot;
try {
slot = readReplicationSlotInfo(slotName, pluginName);
if (slot.equals(ServerInfo.ReplicationSlot.INVALID)) {
return null;
} else {
return slot.asSlotState();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ConnectException(
"Interrupted while waiting for valid replication slot info", e);
}
}
/**
* Fetches the state of a replication stage given a slot name and plugin name
*
* @param slotName the name of the slot
* @param pluginName the name of the plugin used for the desired slot
* @return the {@link ServerInfo.ReplicationSlot} object or a {@link
* ServerInfo.ReplicationSlot#INVALID} if the slot is not valid
* @throws SQLException is thrown by the underlying JDBC
*/
private ServerInfo.ReplicationSlot fetchReplicationSlotInfo(String slotName, String pluginName)
throws SQLException {
final String database = database();
final ServerInfo.ReplicationSlot slot =
queryForSlot(
slotName,
database,
pluginName,
rs -> {
if (rs.next()) {
boolean active = rs.getBoolean("active");
final Lsn confirmedFlushedLsn =
parseConfirmedFlushLsn(slotName, pluginName, database, rs);
if (confirmedFlushedLsn == null) {
return null;
}
Lsn restartLsn =
parseRestartLsn(slotName, pluginName, database, rs);
if (restartLsn == null) {
return null;
}
final Long xmin = rs.getLong("catalog_xmin");
return new ServerInfo.ReplicationSlot(
active, confirmedFlushedLsn, restartLsn, xmin);
} else {
LOGGER.debug(
"No replication slot '{}' is present for plugin '{}' and database '{}'",
slotName,
pluginName,
database);
return ServerInfo.ReplicationSlot.INVALID;
}
});
return slot;
}
/**
* Fetches a replication slot, repeating the query until either the slot is created or until the
* max number of attempts has been reached
*
* <p>To fetch the slot without the retries, use the {@link
* PostgresConnection#fetchReplicationSlotInfo} call
*
* @param slotName the slot name
* @param pluginName the name of the plugin
* @return the {@link ServerInfo.ReplicationSlot} object or a {@link
* ServerInfo.ReplicationSlot#INVALID} if the slot is not valid
* @throws SQLException is thrown by the underyling jdbc driver
* @throws InterruptedException is thrown if we don't return an answer within the set number of
* retries
*/
@VisibleForTesting
ServerInfo.ReplicationSlot readReplicationSlotInfo(String slotName, String pluginName)
throws SQLException, InterruptedException {
final String database = database();
final Metronome metronome =
Metronome.parker(PAUSE_BETWEEN_REPLICATION_SLOT_RETRIEVAL_ATTEMPTS, Clock.SYSTEM);
for (int attempt = 1; attempt <= MAX_ATTEMPTS_FOR_OBTAINING_REPLICATION_SLOT; attempt++) {
final ServerInfo.ReplicationSlot slot = fetchReplicationSlotInfo(slotName, pluginName);
if (slot != null) {
LOGGER.info("Obtained valid replication slot {}", slot);
return slot;
}
LOGGER.warn(
"Cannot obtain valid replication slot '{}' for plugin '{}' and database '{}' [during attempt {} out of {}, concurrent tx probably blocks taking snapshot.",
slotName,
pluginName,
database,
attempt,
MAX_ATTEMPTS_FOR_OBTAINING_REPLICATION_SLOT);
metronome.pause();
}
throw new ConnectException(
"Unable to obtain valid replication slot. "
+ "Make sure there are no long-running transactions running in parallel as they may hinder the allocation of the replication slot when starting this connector");
}
protected ServerInfo.ReplicationSlot queryForSlot(
String slotName,
String database,
String pluginName,
ResultSetMapper<ServerInfo.ReplicationSlot> map)
throws SQLException {
return prepareQueryAndMap(
"select * from pg_replication_slots where slot_name = ? and database = ? and plugin = ?",
statement -> {
statement.setString(1, slotName);
statement.setString(2, database);
statement.setString(3, pluginName);
},
map);
}
/**
* Obtains the LSN to resume streaming from. On PG 9.5 there is no confirmed_flushed_lsn yet, so
* restart_lsn will be read instead. This may result in more records to be re-read after a
* restart.
*/
private Lsn parseConfirmedFlushLsn(
String slotName, String pluginName, String database, ResultSet rs) {
Lsn confirmedFlushedLsn = null;
try {
confirmedFlushedLsn =
tryParseLsn(slotName, pluginName, database, rs, "confirmed_flush_lsn");
} catch (SQLException e) {
LOGGER.info("unable to find confirmed_flushed_lsn, falling back to restart_lsn");
try {
confirmedFlushedLsn =
tryParseLsn(slotName, pluginName, database, rs, "restart_lsn");
} catch (SQLException e2) {
throw new ConnectException(
"Neither confirmed_flush_lsn nor restart_lsn could be found");
}
}
return confirmedFlushedLsn;
}
private Lsn parseRestartLsn(String slotName, String pluginName, String database, ResultSet rs) {
Lsn restartLsn = null;
try {
restartLsn = tryParseLsn(slotName, pluginName, database, rs, "restart_lsn");
} catch (SQLException e) {
throw new ConnectException("restart_lsn could be found");
}
return restartLsn;
}
private Lsn tryParseLsn(
String slotName, String pluginName, String database, ResultSet rs, String column)
throws ConnectException, SQLException {
Lsn lsn = null;
String lsnStr = rs.getString(column);
if (lsnStr == null) {
return null;
}
try {
lsn = Lsn.valueOf(lsnStr);
} catch (Exception e) {
throw new ConnectException(
"Value "
+ column
+ " in the pg_replication_slots table for slot = '"
+ slotName
+ "', plugin = '"
+ pluginName
+ "', database = '"
+ database
+ "' is not valid. This is an abnormal situation and the database status should be checked.");
}
if (!lsn.isValid()) {
throw new ConnectException("Invalid LSN returned from database");
}
return lsn;
}
/**
* Drops a replication slot that was created on the DB
*
* @param slotName the name of the replication slot, may not be null
* @return {@code true} if the slot was dropped, {@code false} otherwise
*/
public boolean dropReplicationSlot(String slotName) {
final int ATTEMPTS = 3;
for (int i = 0; i < ATTEMPTS; i++) {
try {
execute("select pg_drop_replication_slot('" + slotName + "')");
return true;
} catch (SQLException e) {
// slot is active
if (PSQLState.OBJECT_IN_USE.getState().equals(e.getSQLState())) {
if (i < ATTEMPTS - 1) {
LOGGER.debug(
"Cannot drop replication slot '{}' because it's still in use",
slotName);
} else {
LOGGER.warn(
"Cannot drop replication slot '{}' because it's still in use",
slotName);
return false;
}
} else if (PSQLState.UNDEFINED_OBJECT.getState().equals(e.getSQLState())) {
LOGGER.debug("Replication slot {} has already been dropped", slotName);
return false;
} else {
LOGGER.error("Unexpected error while attempting to drop replication slot", e);
return false;
}
}
try {
Metronome.parker(Duration.ofSeconds(1), Clock.system()).pause();
} catch (InterruptedException e) {
}
}
return false;
}
/**
* Drops the debezium publication that was created.
*
* @param publicationName the publication name, may not be null
* @return {@code true} if the publication was dropped, {@code false} otherwise
*/
public boolean dropPublication(String publicationName) {
try {
LOGGER.debug("Dropping publication '{}'", publicationName);
execute("DROP PUBLICATION " + publicationName);
return true;
} catch (SQLException e) {
if (PSQLState.UNDEFINED_OBJECT.getState().equals(e.getSQLState())) {
LOGGER.debug("Publication {} has already been dropped", publicationName);
} else {
LOGGER.error("Unexpected error while attempting to drop publication", e);
}
return false;
}
}
@Override
public synchronized void close() {
try {
super.close();
} catch (SQLException e) {
LOGGER.error("Unexpected error while closing Postgres connection", e);
}
}
/**
* Returns the PG id of the current active transaction
*
* @return a PG transaction identifier, or null if no tx is active
* @throws SQLException if anything fails.
*/
public Long currentTransactionId() throws SQLException {
AtomicLong txId = new AtomicLong(0);
query(
"select (case pg_is_in_recovery() when 't' then 0 else txid_current() end) AS pg_current_txid",
rs -> {
if (rs.next()) {
txId.compareAndSet(0, rs.getLong(1));
}
});
long value = txId.get();
return value > 0 ? value : null;
}
/**
* Returns the current position in the server tx log.
*
* @return a long value, never negative
* @throws SQLException if anything unexpected fails.
*/
public long currentXLogLocation() throws SQLException {
AtomicLong result = new AtomicLong(0);
int majorVersion = connection().getMetaData().getDatabaseMajorVersion();
query(
majorVersion >= 10
? "select (case pg_is_in_recovery() when 't' then pg_last_wal_receive_lsn() else pg_current_wal_lsn() end) AS pg_current_wal_lsn"
: "select * from pg_current_xlog_location()",
rs -> {
if (!rs.next()) {
throw new IllegalStateException(
"there should always be a valid xlog position");
}
result.compareAndSet(0, LogSequenceNumber.valueOf(rs.getString(1)).asLong());
});
return result.get();
}
/**
* Returns information about the PG server to which this instance is connected.
*
* @return a {@link ServerInfo} instance, never {@code null}
* @throws SQLException if anything fails
*/
public ServerInfo serverInfo() throws SQLException {
ServerInfo serverInfo = new ServerInfo();
query(
"SELECT version(), current_user, current_database()",
rs -> {
if (rs.next()) {
serverInfo
.withServer(rs.getString(1))
.withUsername(rs.getString(2))
.withDatabase(rs.getString(3));
}
});
String username = serverInfo.username();
if (username != null) {
query(
"SELECT oid, rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication FROM pg_roles "
+ "WHERE pg_has_role('"
+ username
+ "', oid, 'member')",
rs -> {
while (rs.next()) {
String roleInfo =
"superuser: "
+ rs.getBoolean(3)
+ ", replication: "
+ rs.getBoolean(8)
+ ", inherit: "
+ rs.getBoolean(4)
+ ", create role: "
+ rs.getBoolean(5)
+ ", create db: "
+ rs.getBoolean(6)
+ ", can log in: "
+ rs.getBoolean(7);
String roleName = rs.getString(2);
serverInfo.addRole(roleName, roleInfo);
}
});
}
return serverInfo;
}
public Charset getDatabaseCharset() {
try {
return Charset.forName(((BaseConnection) connection()).getEncoding().name());
} catch (SQLException e) {
throw new DebeziumException("Couldn't obtain encoding for database " + database(), e);
}
}
public TimestampUtils getTimestampUtils() {
try {
return ((PgConnection) this.connection()).getTimestampUtils();
} catch (SQLException e) {
throw new DebeziumException(
"Couldn't get timestamp utils from underlying connection", e);
}
}
private static void validateServerVersion(Statement statement) throws SQLException {
DatabaseMetaData metaData = statement.getConnection().getMetaData();
int majorVersion = metaData.getDatabaseMajorVersion();
int minorVersion = metaData.getDatabaseMinorVersion();
if (majorVersion < 9 || (majorVersion == 9 && minorVersion < 4)) {
throw new SQLException("Cannot connect to a version of Postgres lower than 9.4");
}
}
@Override
public String quotedColumnIdString(String columnName) {
if (columnName.contains("\"")) {
columnName = columnName.replaceAll("\"", "\"\"");
}
return super.quotedColumnIdString(columnName);
}
@Override
protected int resolveNativeType(String typeName) {
return getTypeRegistry().get(typeName).getRootType().getOid();
}
@Override
protected int resolveJdbcType(int metadataJdbcType, int nativeType) {
// Special care needs to be taken for columns that use user-defined domain type data types
// where resolution of the column's JDBC type needs to be that of the root type instead of
// the actual column to properly influence schema building and value conversion.
return getTypeRegistry().get(nativeType).getRootType().getJdbcId();
}
@Override
protected Optional<ColumnEditor> readTableColumn(
ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter)
throws SQLException {
return doReadTableColumn(columnMetadata, tableId, columnFilter);
}
public Optional<Column> readColumnForDecoder(
ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnNameFilter)
throws SQLException {
return doReadTableColumn(columnMetadata, tableId, columnNameFilter)
.map(ColumnEditor::create);
}
private Optional<ColumnEditor> doReadTableColumn(
ResultSet columnMetadata, TableId tableId, Tables.ColumnNameFilter columnFilter)
throws SQLException {
final String columnName = columnMetadata.getString(4);
if (columnFilter == null
|| columnFilter.matches(
tableId.catalog(), tableId.schema(), tableId.table(), columnName)) {
final ColumnEditor column = Column.editor().name(columnName);
column.type(columnMetadata.getString(6));
// first source the length/scale from the column metadata provided by the driver
// this may be overridden below if the column type is a user-defined domain type
column.length(columnMetadata.getInt(7));
if (columnMetadata.getObject(9) != null) {
column.scale(columnMetadata.getInt(9));
}
column.optional(isNullable(columnMetadata.getInt(11)));
column.position(columnMetadata.getInt(17));
column.autoIncremented("YES".equalsIgnoreCase(columnMetadata.getString(23)));
String autogenerated = null;
try {
autogenerated = columnMetadata.getString(24);
} catch (SQLException e) {
// ignore, some drivers don't have this index - e.g. Postgres
}
column.generated("YES".equalsIgnoreCase(autogenerated));
// Lookup the column type from the TypeRegistry
// For all types, we need to set the Native and Jdbc types by using the root-type
final PostgresType nativeType = getTypeRegistry().get(column.typeName());
column.nativeType(nativeType.getRootType().getOid());
column.jdbcType(nativeType.getRootType().getJdbcId());
// For domain types, the postgres driver is unable to traverse a nested unbounded
// hierarchy of types and report the right length/scale of a given type. We use
// the TypeRegistry to accomplish this since it is capable of traversing the type
// hierarchy upward to resolve length/scale regardless of hierarchy depth.
if (TypeRegistry.DOMAIN_TYPE == nativeType.getJdbcId()) {
column.length(nativeType.getDefaultLength());
column.scale(nativeType.getDefaultScale());
}
final String defaultValueExpression = columnMetadata.getString(13);
if (defaultValueExpression != null
&& getDefaultValueConverter().supportConversion(column.typeName())) {
column.defaultValueExpression(defaultValueExpression);
}
return Optional.of(column);
}
return Optional.empty();
}
public PostgresDefaultValueConverter getDefaultValueConverter() {
Objects.requireNonNull(
defaultValueConverter, "Connection does not provide default value converter");
return defaultValueConverter;
}
public TypeRegistry getTypeRegistry() {
Objects.requireNonNull(typeRegistry, "Connection does not provide type registry");
return typeRegistry;
}
@Override
public <T extends DatabaseSchema<TableId>> Object getColumnValue(
ResultSet rs, int columnIndex, Column column, Table table, T schema)
throws SQLException {
try {
final ResultSetMetaData metaData = rs.getMetaData();
final String columnTypeName = metaData.getColumnTypeName(columnIndex);
final PostgresType type =
((PostgresSchema) schema).getTypeRegistry().get(columnTypeName);
LOGGER.trace("Type of incoming data is: {}", type.getOid());
LOGGER.trace("ColumnTypeName is: {}", columnTypeName);
LOGGER.trace("Type is: {}", type);
if (type.isArrayType()) {
return rs.getArray(columnIndex);
}
switch (type.getOid()) {
case PgOid.MONEY:
// TODO author=Horia Chiorean date=14/11/2016 description=workaround for
// https://github.com/pgjdbc/pgjdbc/issues/100
final String sMoney = rs.getString(columnIndex);
if (sMoney == null) {
return sMoney;
}
if (sMoney.startsWith("-")) {
// PGmoney expects negative values to be provided in the format of
// "($XXXXX.YY)"
final String negativeMoney = "(" + sMoney.substring(1) + ")";
return new PGmoney(negativeMoney).val;
}
return new PGmoney(sMoney).val;
case PgOid.BIT:
return rs.getString(columnIndex);
case PgOid.NUMERIC:
final String s = rs.getString(columnIndex);
if (s == null) {
return s;
}
Optional<SpecialValueDecimal> value = PostgresValueConverter.toSpecialValue(s);
return value.isPresent()
? value.get()
: new SpecialValueDecimal(rs.getBigDecimal(columnIndex));
case PgOid.TIME:
// To handle time 24:00:00 supported by TIME columns, read the column as a
// string.
case PgOid.TIMETZ:
// In order to guarantee that we resolve TIMETZ columns with proper microsecond
// precision,
// read the column as a string instead and then re-parse inside the converter.
return rs.getString(columnIndex);
default:
Object x = rs.getObject(columnIndex);
if (x != null) {
LOGGER.trace(
"rs getobject returns class: {}; rs getObject value is: {}",
x.getClass(),
x);
}
return x;
}
} catch (SQLException e) {
// not a known type
return super.getColumnValue(rs, columnIndex, column, table, schema);
}
}
@Override
protected String[] supportedTableTypes() {
return new String[] {"VIEW", "MATERIALIZED VIEW", "TABLE", "PARTITIONED TABLE"};
}
@Override
protected boolean isTableType(String tableType) {
return "TABLE".equals(tableType) || "PARTITIONED TABLE".equals(tableType);
}
@Override
protected boolean isTableUniqueIndexIncluded(String indexName, String columnName) {
if (columnName != null) {
return !FUNCTION_DEFAULT_PATTERN.matcher(columnName).matches()
&& !EXPRESSION_DEFAULT_PATTERN.matcher(columnName).matches();
}
return false;
}
/**
* Retrieves all {@code TableId}s in a given database catalog, including partitioned tables.
*
* @param catalogName the catalog/database name
* @return set of all table ids for existing table objects
* @throws SQLException if a database exception occurred
*/
public Set<TableId> getAllTableIds(String catalogName) throws SQLException {
return readTableNames(catalogName, null, null, new String[] {"TABLE", "PARTITIONED TABLE"});
}
@FunctionalInterface
public interface PostgresValueConverterBuilder {
PostgresValueConverter build(TypeRegistry registry);
}
}
|
googleapis/google-cloud-java | 37,497 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/InterconnectDiagnosticsLinkOpticalPower.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower}
*/
public final class InterconnectDiagnosticsLinkOpticalPower
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower)
InterconnectDiagnosticsLinkOpticalPowerOrBuilder {
private static final long serialVersionUID = 0L;
// Use InterconnectDiagnosticsLinkOpticalPower.newBuilder() to construct.
private InterconnectDiagnosticsLinkOpticalPower(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InterconnectDiagnosticsLinkOpticalPower() {
state_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new InterconnectDiagnosticsLinkOpticalPower();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_InterconnectDiagnosticsLinkOpticalPower_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_InterconnectDiagnosticsLinkOpticalPower_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.class,
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.Builder.class);
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* </pre>
*
* Protobuf enum {@code google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.State}
*/
public enum State implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* A value indicating that the enum field is not set.
* </pre>
*
* <code>UNDEFINED_STATE = 0;</code>
*/
UNDEFINED_STATE(0),
/**
*
*
* <pre>
* The value has crossed above the high alarm threshold.
* </pre>
*
* <code>HIGH_ALARM = 305363284;</code>
*/
HIGH_ALARM(305363284),
/**
*
*
* <pre>
* The value of the current optical power has crossed above the high warning threshold.
* </pre>
*
* <code>HIGH_WARNING = 220984799;</code>
*/
HIGH_WARNING(220984799),
/**
*
*
* <pre>
* The value of the current optical power has crossed below the low alarm threshold.
* </pre>
*
* <code>LOW_ALARM = 316659046;</code>
*/
LOW_ALARM(316659046),
/**
*
*
* <pre>
* The value of the current optical power has crossed below the low warning threshold.
* </pre>
*
* <code>LOW_WARNING = 338793841;</code>
*/
LOW_WARNING(338793841),
/**
*
*
* <pre>
* The value of the current optical power has not crossed a warning threshold.
* </pre>
*
* <code>OK = 2524;</code>
*/
OK(2524),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* A value indicating that the enum field is not set.
* </pre>
*
* <code>UNDEFINED_STATE = 0;</code>
*/
public static final int UNDEFINED_STATE_VALUE = 0;
/**
*
*
* <pre>
* The value has crossed above the high alarm threshold.
* </pre>
*
* <code>HIGH_ALARM = 305363284;</code>
*/
public static final int HIGH_ALARM_VALUE = 305363284;
/**
*
*
* <pre>
* The value of the current optical power has crossed above the high warning threshold.
* </pre>
*
* <code>HIGH_WARNING = 220984799;</code>
*/
public static final int HIGH_WARNING_VALUE = 220984799;
/**
*
*
* <pre>
* The value of the current optical power has crossed below the low alarm threshold.
* </pre>
*
* <code>LOW_ALARM = 316659046;</code>
*/
public static final int LOW_ALARM_VALUE = 316659046;
/**
*
*
* <pre>
* The value of the current optical power has crossed below the low warning threshold.
* </pre>
*
* <code>LOW_WARNING = 338793841;</code>
*/
public static final int LOW_WARNING_VALUE = 338793841;
/**
*
*
* <pre>
* The value of the current optical power has not crossed a warning threshold.
* </pre>
*
* <code>OK = 2524;</code>
*/
public static final int OK_VALUE = 2524;
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 State 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 State forNumber(int value) {
switch (value) {
case 0:
return UNDEFINED_STATE;
case 305363284:
return HIGH_ALARM;
case 220984799:
return HIGH_WARNING;
case 316659046:
return LOW_ALARM;
case 338793841:
return LOW_WARNING;
case 2524:
return OK;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<State> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<State> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<State>() {
public State findValueByNumber(int number) {
return State.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final State[] VALUES = values();
public static State 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 State(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.State)
}
private int bitField0_;
public static final int STATE_FIELD_NUMBER = 109757585;
@SuppressWarnings("serial")
private volatile java.lang.Object state_ = "";
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return Whether the state field is set.
*/
@java.lang.Override
public boolean hasState() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return The state.
*/
@java.lang.Override
public java.lang.String getState() {
java.lang.Object ref = state_;
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();
state_ = s;
return s;
}
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return The bytes for state.
*/
@java.lang.Override
public com.google.protobuf.ByteString getStateBytes() {
java.lang.Object ref = state_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
state_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VALUE_FIELD_NUMBER = 111972721;
private float value_ = 0F;
/**
*
*
* <pre>
* Value of the current receiving or transmitting optical power, read in dBm. Take a known good optical value, give it a 10% margin and trigger warnings relative to that value. In general, a -7dBm warning and a -11dBm alarm are good optical value estimates for most links.
* </pre>
*
* <code>optional float value = 111972721;</code>
*
* @return Whether the value field is set.
*/
@java.lang.Override
public boolean hasValue() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Value of the current receiving or transmitting optical power, read in dBm. Take a known good optical value, give it a 10% margin and trigger warnings relative to that value. In general, a -7dBm warning and a -11dBm alarm are good optical value estimates for most links.
* </pre>
*
* <code>optional float value = 111972721;</code>
*
* @return The value.
*/
@java.lang.Override
public float getValue() {
return value_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 109757585, state_);
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeFloat(111972721, value_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(109757585, state_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(111972721, value_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower other =
(com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower) obj;
if (hasState() != other.hasState()) return false;
if (hasState()) {
if (!getState().equals(other.getState())) return false;
}
if (hasValue() != other.hasValue()) return false;
if (hasValue()) {
if (java.lang.Float.floatToIntBits(getValue())
!= java.lang.Float.floatToIntBits(other.getValue())) 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 (hasState()) {
hash = (37 * hash) + STATE_FIELD_NUMBER;
hash = (53 * hash) + getState().hashCode();
}
if (hasValue()) {
hash = (37 * hash) + VALUE_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getValue());
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower)
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPowerOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_InterconnectDiagnosticsLinkOpticalPower_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_InterconnectDiagnosticsLinkOpticalPower_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.class,
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.Builder.class);
}
// Construct using
// com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
state_ = "";
value_ = 0F;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_InterconnectDiagnosticsLinkOpticalPower_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
getDefaultInstanceForType() {
return com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower build() {
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower buildPartial() {
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower result =
new com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.state_ = state_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.value_ = value_;
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower) {
return mergeFrom(
(com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower other) {
if (other
== com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
.getDefaultInstance()) return this;
if (other.hasState()) {
state_ = other.state_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasValue()) {
setValue(other.getValue());
}
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 878060682:
{
state_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 878060682
case 895781773:
{
value_ = input.readFloat();
bitField0_ |= 0x00000002;
break;
} // case 895781773
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 state_ = "";
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return Whether the state field is set.
*/
public boolean hasState() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return The state.
*/
public java.lang.String getState() {
java.lang.Object ref = state_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
state_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return The bytes for state.
*/
public com.google.protobuf.ByteString getStateBytes() {
java.lang.Object ref = state_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
state_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @param value The state to set.
* @return This builder for chaining.
*/
public Builder setState(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
state_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @return This builder for chaining.
*/
public Builder clearState() {
state_ = getDefaultInstance().getState();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The status of the current value when compared to the warning and alarm levels for the receiving or transmitting transceiver. Possible states include: - OK: The value has not crossed a warning threshold. - LOW_WARNING: The value has crossed below the low warning threshold. - HIGH_WARNING: The value has crossed above the high warning threshold. - LOW_ALARM: The value has crossed below the low alarm threshold. - HIGH_ALARM: The value has crossed above the high alarm threshold.
* Check the State enum for the list of possible values.
* </pre>
*
* <code>optional string state = 109757585;</code>
*
* @param value The bytes for state to set.
* @return This builder for chaining.
*/
public Builder setStateBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
state_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private float value_;
/**
*
*
* <pre>
* Value of the current receiving or transmitting optical power, read in dBm. Take a known good optical value, give it a 10% margin and trigger warnings relative to that value. In general, a -7dBm warning and a -11dBm alarm are good optical value estimates for most links.
* </pre>
*
* <code>optional float value = 111972721;</code>
*
* @return Whether the value field is set.
*/
@java.lang.Override
public boolean hasValue() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Value of the current receiving or transmitting optical power, read in dBm. Take a known good optical value, give it a 10% margin and trigger warnings relative to that value. In general, a -7dBm warning and a -11dBm alarm are good optical value estimates for most links.
* </pre>
*
* <code>optional float value = 111972721;</code>
*
* @return The value.
*/
@java.lang.Override
public float getValue() {
return value_;
}
/**
*
*
* <pre>
* Value of the current receiving or transmitting optical power, read in dBm. Take a known good optical value, give it a 10% margin and trigger warnings relative to that value. In general, a -7dBm warning and a -11dBm alarm are good optical value estimates for most links.
* </pre>
*
* <code>optional float value = 111972721;</code>
*
* @param value The value to set.
* @return This builder for chaining.
*/
public Builder setValue(float value) {
value_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Value of the current receiving or transmitting optical power, read in dBm. Take a known good optical value, give it a 10% margin and trigger warnings relative to that value. In general, a -7dBm warning and a -11dBm alarm are good optical value estimates for most links.
* </pre>
*
* <code>optional float value = 111972721;</code>
*
* @return This builder for chaining.
*/
public Builder clearValue() {
bitField0_ = (bitField0_ & ~0x00000002);
value_ = 0F;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower)
private static final com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower();
}
public static com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InterconnectDiagnosticsLinkOpticalPower> PARSER =
new com.google.protobuf.AbstractParser<InterconnectDiagnosticsLinkOpticalPower>() {
@java.lang.Override
public InterconnectDiagnosticsLinkOpticalPower 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<InterconnectDiagnosticsLinkOpticalPower> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InterconnectDiagnosticsLinkOpticalPower> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.InterconnectDiagnosticsLinkOpticalPower
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/adk-java | 37,563 | core/src/main/java/com/google/adk/agents/LlmAgent.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
*
* 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.adk.agents;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.stream.Collectors.joining;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.adk.SchemaUtils;
import com.google.adk.agents.Callbacks.AfterAgentCallback;
import com.google.adk.agents.Callbacks.AfterAgentCallbackBase;
import com.google.adk.agents.Callbacks.AfterAgentCallbackSync;
import com.google.adk.agents.Callbacks.AfterModelCallback;
import com.google.adk.agents.Callbacks.AfterModelCallbackBase;
import com.google.adk.agents.Callbacks.AfterModelCallbackSync;
import com.google.adk.agents.Callbacks.AfterToolCallback;
import com.google.adk.agents.Callbacks.AfterToolCallbackBase;
import com.google.adk.agents.Callbacks.AfterToolCallbackSync;
import com.google.adk.agents.Callbacks.BeforeAgentCallback;
import com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;
import com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;
import com.google.adk.agents.Callbacks.BeforeModelCallback;
import com.google.adk.agents.Callbacks.BeforeModelCallbackBase;
import com.google.adk.agents.Callbacks.BeforeModelCallbackSync;
import com.google.adk.agents.Callbacks.BeforeToolCallback;
import com.google.adk.agents.Callbacks.BeforeToolCallbackBase;
import com.google.adk.agents.Callbacks.BeforeToolCallbackSync;
import com.google.adk.agents.ConfigAgentUtils.ConfigurationException;
import com.google.adk.codeexecutors.BaseCodeExecutor;
import com.google.adk.events.Event;
import com.google.adk.examples.BaseExampleProvider;
import com.google.adk.examples.Example;
import com.google.adk.flows.llmflows.AutoFlow;
import com.google.adk.flows.llmflows.BaseLlmFlow;
import com.google.adk.flows.llmflows.SingleFlow;
import com.google.adk.models.BaseLlm;
import com.google.adk.models.LlmRegistry;
import com.google.adk.models.Model;
import com.google.adk.tools.BaseTool;
import com.google.adk.tools.BaseToolset;
import com.google.adk.utils.ComponentRegistry;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.Schema;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Single;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The LLM-based agent. */
public class LlmAgent extends BaseAgent {
private static final Logger logger = LoggerFactory.getLogger(LlmAgent.class);
/**
* Enum to define if contents of previous events should be included in requests to the underlying
* LLM.
*/
public enum IncludeContents {
DEFAULT,
NONE;
}
private final Optional<Model> model;
private final Instruction instruction;
private final Instruction globalInstruction;
private final List<Object> toolsUnion;
private final ImmutableList<BaseToolset> toolsets;
private final Optional<GenerateContentConfig> generateContentConfig;
// TODO: Remove exampleProvider field - examples should only be provided via ExampleTool
private final Optional<BaseExampleProvider> exampleProvider;
private final IncludeContents includeContents;
private final boolean planning;
private final Optional<Integer> maxSteps;
private final boolean disallowTransferToParent;
private final boolean disallowTransferToPeers;
private final Optional<List<? extends BeforeModelCallback>> beforeModelCallback;
private final Optional<List<? extends AfterModelCallback>> afterModelCallback;
private final Optional<List<? extends BeforeToolCallback>> beforeToolCallback;
private final Optional<List<? extends AfterToolCallback>> afterToolCallback;
private final Optional<Schema> inputSchema;
private final Optional<Schema> outputSchema;
private final Optional<Executor> executor;
private final Optional<String> outputKey;
private final Optional<BaseCodeExecutor> codeExecutor;
private volatile Model resolvedModel;
private final BaseLlmFlow llmFlow;
protected LlmAgent(Builder builder) {
super(
builder.name,
builder.description,
builder.subAgents,
builder.beforeAgentCallback,
builder.afterAgentCallback);
this.model = Optional.ofNullable(builder.model);
this.instruction =
builder.instruction == null ? new Instruction.Static("") : builder.instruction;
this.globalInstruction =
builder.globalInstruction == null ? new Instruction.Static("") : builder.globalInstruction;
this.generateContentConfig = Optional.ofNullable(builder.generateContentConfig);
this.exampleProvider = Optional.ofNullable(builder.exampleProvider);
this.includeContents =
builder.includeContents != null ? builder.includeContents : IncludeContents.DEFAULT;
this.planning = builder.planning != null && builder.planning;
this.maxSteps = Optional.ofNullable(builder.maxSteps);
this.disallowTransferToParent = builder.disallowTransferToParent;
this.disallowTransferToPeers = builder.disallowTransferToPeers;
this.beforeModelCallback = Optional.ofNullable(builder.beforeModelCallback);
this.afterModelCallback = Optional.ofNullable(builder.afterModelCallback);
this.beforeToolCallback = Optional.ofNullable(builder.beforeToolCallback);
this.afterToolCallback = Optional.ofNullable(builder.afterToolCallback);
this.inputSchema = Optional.ofNullable(builder.inputSchema);
this.outputSchema = Optional.ofNullable(builder.outputSchema);
this.executor = Optional.ofNullable(builder.executor);
this.outputKey = Optional.ofNullable(builder.outputKey);
this.toolsUnion = builder.toolsUnion != null ? builder.toolsUnion : ImmutableList.of();
this.toolsets = extractToolsets(this.toolsUnion);
this.codeExecutor = Optional.ofNullable(builder.codeExecutor);
this.llmFlow = determineLlmFlow();
// Validate name not empty.
Preconditions.checkArgument(!this.name().isEmpty(), "Agent name cannot be empty.");
}
/** Returns a {@link Builder} for {@link LlmAgent}. */
public static Builder builder() {
return new Builder();
}
/** Extracts BaseToolset instances from the toolsUnion list. */
private static ImmutableList<BaseToolset> extractToolsets(List<Object> toolsUnion) {
return toolsUnion.stream()
.filter(obj -> obj instanceof BaseToolset)
.map(obj -> (BaseToolset) obj)
.collect(toImmutableList());
}
/** Builder for {@link LlmAgent}. */
public static class Builder {
private String name;
private String description;
private Model model;
private Instruction instruction;
private Instruction globalInstruction;
private ImmutableList<BaseAgent> subAgents;
private ImmutableList<Object> toolsUnion;
private GenerateContentConfig generateContentConfig;
private BaseExampleProvider exampleProvider;
private IncludeContents includeContents;
private Boolean planning;
private Integer maxSteps;
private Boolean disallowTransferToParent;
private Boolean disallowTransferToPeers;
private ImmutableList<? extends BeforeModelCallback> beforeModelCallback;
private ImmutableList<? extends AfterModelCallback> afterModelCallback;
private ImmutableList<? extends BeforeAgentCallback> beforeAgentCallback;
private ImmutableList<? extends AfterAgentCallback> afterAgentCallback;
private ImmutableList<? extends BeforeToolCallback> beforeToolCallback;
private ImmutableList<? extends AfterToolCallback> afterToolCallback;
private Schema inputSchema;
private Schema outputSchema;
private Executor executor;
private String outputKey;
private BaseCodeExecutor codeExecutor;
@CanIgnoreReturnValue
public Builder name(String name) {
this.name = name;
return this;
}
@CanIgnoreReturnValue
public Builder description(String description) {
this.description = description;
return this;
}
@CanIgnoreReturnValue
public Builder model(String model) {
this.model = Model.builder().modelName(model).build();
return this;
}
@CanIgnoreReturnValue
public Builder model(BaseLlm model) {
this.model = Model.builder().model(model).build();
return this;
}
@CanIgnoreReturnValue
public Builder instruction(Instruction instruction) {
this.instruction = instruction;
return this;
}
@CanIgnoreReturnValue
public Builder instruction(String instruction) {
this.instruction = (instruction == null) ? null : new Instruction.Static(instruction);
return this;
}
@CanIgnoreReturnValue
public Builder globalInstruction(Instruction globalInstruction) {
this.globalInstruction = globalInstruction;
return this;
}
@CanIgnoreReturnValue
public Builder globalInstruction(String globalInstruction) {
this.globalInstruction =
(globalInstruction == null) ? null : new Instruction.Static(globalInstruction);
return this;
}
@CanIgnoreReturnValue
public Builder subAgents(List<? extends BaseAgent> subAgents) {
this.subAgents = ImmutableList.copyOf(subAgents);
return this;
}
@CanIgnoreReturnValue
public Builder subAgents(BaseAgent... subAgents) {
this.subAgents = ImmutableList.copyOf(subAgents);
return this;
}
@CanIgnoreReturnValue
public Builder tools(List<?> tools) {
this.toolsUnion = ImmutableList.copyOf(tools);
return this;
}
@CanIgnoreReturnValue
public Builder tools(Object... tools) {
this.toolsUnion = ImmutableList.copyOf(tools);
return this;
}
@CanIgnoreReturnValue
public Builder generateContentConfig(GenerateContentConfig generateContentConfig) {
this.generateContentConfig = generateContentConfig;
return this;
}
// TODO: Remove these example provider methods and only use ExampleTool for providing examples.
// Direct example methods should be deprecated in favor of using ExampleTool consistently.
@CanIgnoreReturnValue
public Builder exampleProvider(BaseExampleProvider exampleProvider) {
this.exampleProvider = exampleProvider;
return this;
}
@CanIgnoreReturnValue
public Builder exampleProvider(List<Example> examples) {
this.exampleProvider = (query) -> examples;
return this;
}
@CanIgnoreReturnValue
public Builder exampleProvider(Example... examples) {
this.exampleProvider = (query) -> ImmutableList.copyOf(examples);
return this;
}
@CanIgnoreReturnValue
public Builder includeContents(IncludeContents includeContents) {
this.includeContents = includeContents;
return this;
}
@CanIgnoreReturnValue
public Builder planning(boolean planning) {
this.planning = planning;
return this;
}
@CanIgnoreReturnValue
public Builder maxSteps(int maxSteps) {
this.maxSteps = maxSteps;
return this;
}
@CanIgnoreReturnValue
public Builder disallowTransferToParent(boolean disallowTransferToParent) {
this.disallowTransferToParent = disallowTransferToParent;
return this;
}
@CanIgnoreReturnValue
public Builder disallowTransferToPeers(boolean disallowTransferToPeers) {
this.disallowTransferToPeers = disallowTransferToPeers;
return this;
}
@CanIgnoreReturnValue
public Builder beforeModelCallback(BeforeModelCallback beforeModelCallback) {
this.beforeModelCallback = ImmutableList.of(beforeModelCallback);
return this;
}
@CanIgnoreReturnValue
public Builder beforeModelCallback(List<BeforeModelCallbackBase> beforeModelCallback) {
if (beforeModelCallback == null) {
this.beforeModelCallback = null;
} else if (beforeModelCallback.isEmpty()) {
this.beforeModelCallback = ImmutableList.of();
} else {
ImmutableList.Builder<BeforeModelCallback> builder = ImmutableList.builder();
for (BeforeModelCallbackBase callback : beforeModelCallback) {
if (callback instanceof BeforeModelCallback beforeModelCallbackInstance) {
builder.add(beforeModelCallbackInstance);
} else if (callback instanceof BeforeModelCallbackSync beforeModelCallbackSyncInstance) {
builder.add(
(BeforeModelCallback)
(callbackContext, llmRequestBuilder) ->
Maybe.fromOptional(
beforeModelCallbackSyncInstance.call(
callbackContext, llmRequestBuilder)));
} else {
logger.warn(
"Invalid beforeModelCallback callback type: %s. Ignoring this callback.",
callback.getClass().getName());
}
}
this.beforeModelCallback = builder.build();
}
return this;
}
@CanIgnoreReturnValue
public Builder beforeModelCallbackSync(BeforeModelCallbackSync beforeModelCallbackSync) {
this.beforeModelCallback =
ImmutableList.of(
(callbackContext, llmRequestBuilder) ->
Maybe.fromOptional(
beforeModelCallbackSync.call(callbackContext, llmRequestBuilder)));
return this;
}
@CanIgnoreReturnValue
public Builder afterModelCallback(AfterModelCallback afterModelCallback) {
this.afterModelCallback = ImmutableList.of(afterModelCallback);
return this;
}
@CanIgnoreReturnValue
public Builder afterModelCallback(List<AfterModelCallbackBase> afterModelCallback) {
if (afterModelCallback == null) {
this.afterModelCallback = null;
} else if (afterModelCallback.isEmpty()) {
this.afterModelCallback = ImmutableList.of();
} else {
ImmutableList.Builder<AfterModelCallback> builder = ImmutableList.builder();
for (AfterModelCallbackBase callback : afterModelCallback) {
if (callback instanceof AfterModelCallback afterModelCallbackInstance) {
builder.add(afterModelCallbackInstance);
} else if (callback instanceof AfterModelCallbackSync afterModelCallbackSyncInstance) {
builder.add(
(AfterModelCallback)
(callbackContext, llmResponse) ->
Maybe.fromOptional(
afterModelCallbackSyncInstance.call(callbackContext, llmResponse)));
} else {
logger.warn(
"Invalid afterModelCallback callback type: %s. Ignoring this callback.",
callback.getClass().getName());
}
}
this.afterModelCallback = builder.build();
}
return this;
}
@CanIgnoreReturnValue
public Builder afterModelCallbackSync(AfterModelCallbackSync afterModelCallbackSync) {
this.afterModelCallback =
ImmutableList.of(
(callbackContext, llmResponse) ->
Maybe.fromOptional(afterModelCallbackSync.call(callbackContext, llmResponse)));
return this;
}
@CanIgnoreReturnValue
public Builder beforeAgentCallback(BeforeAgentCallback beforeAgentCallback) {
this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);
return this;
}
@CanIgnoreReturnValue
public Builder beforeAgentCallback(List<BeforeAgentCallbackBase> beforeAgentCallback) {
this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);
return this;
}
@CanIgnoreReturnValue
public Builder beforeAgentCallbackSync(BeforeAgentCallbackSync beforeAgentCallbackSync) {
this.beforeAgentCallback =
ImmutableList.of(
(callbackContext) ->
Maybe.fromOptional(beforeAgentCallbackSync.call(callbackContext)));
return this;
}
@CanIgnoreReturnValue
public Builder afterAgentCallback(AfterAgentCallback afterAgentCallback) {
this.afterAgentCallback = ImmutableList.of(afterAgentCallback);
return this;
}
@CanIgnoreReturnValue
public Builder afterAgentCallback(List<AfterAgentCallbackBase> afterAgentCallback) {
this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);
return this;
}
@CanIgnoreReturnValue
public Builder afterAgentCallbackSync(AfterAgentCallbackSync afterAgentCallbackSync) {
this.afterAgentCallback =
ImmutableList.of(
(callbackContext) ->
Maybe.fromOptional(afterAgentCallbackSync.call(callbackContext)));
return this;
}
@CanIgnoreReturnValue
public Builder beforeToolCallback(BeforeToolCallback beforeToolCallback) {
this.beforeToolCallback = ImmutableList.of(beforeToolCallback);
return this;
}
@CanIgnoreReturnValue
public Builder beforeToolCallback(
@Nullable List<? extends BeforeToolCallbackBase> beforeToolCallbacks) {
if (beforeToolCallbacks == null) {
this.beforeToolCallback = null;
} else if (beforeToolCallbacks.isEmpty()) {
this.beforeToolCallback = ImmutableList.of();
} else {
ImmutableList.Builder<BeforeToolCallback> builder = ImmutableList.builder();
for (BeforeToolCallbackBase callback : beforeToolCallbacks) {
if (callback instanceof BeforeToolCallback beforeToolCallbackInstance) {
builder.add(beforeToolCallbackInstance);
} else if (callback instanceof BeforeToolCallbackSync beforeToolCallbackSyncInstance) {
builder.add(
(invocationContext, baseTool, input, toolContext) ->
Maybe.fromOptional(
beforeToolCallbackSyncInstance.call(
invocationContext, baseTool, input, toolContext)));
} else {
logger.warn(
"Invalid beforeToolCallback callback type: {}. Ignoring this callback.",
callback.getClass().getName());
}
}
this.beforeToolCallback = builder.build();
}
return this;
}
@CanIgnoreReturnValue
public Builder beforeToolCallbackSync(BeforeToolCallbackSync beforeToolCallbackSync) {
this.beforeToolCallback =
ImmutableList.of(
(invocationContext, baseTool, input, toolContext) ->
Maybe.fromOptional(
beforeToolCallbackSync.call(
invocationContext, baseTool, input, toolContext)));
return this;
}
@CanIgnoreReturnValue
public Builder afterToolCallback(AfterToolCallback afterToolCallback) {
this.afterToolCallback = ImmutableList.of(afterToolCallback);
return this;
}
@CanIgnoreReturnValue
public Builder afterToolCallback(@Nullable List<AfterToolCallbackBase> afterToolCallbacks) {
if (afterToolCallbacks == null) {
this.afterToolCallback = null;
} else if (afterToolCallbacks.isEmpty()) {
this.afterToolCallback = ImmutableList.of();
} else {
ImmutableList.Builder<AfterToolCallback> builder = ImmutableList.builder();
for (AfterToolCallbackBase callback : afterToolCallbacks) {
if (callback instanceof AfterToolCallback afterToolCallbackInstance) {
builder.add(afterToolCallbackInstance);
} else if (callback instanceof AfterToolCallbackSync afterToolCallbackSyncInstance) {
builder.add(
(invocationContext, baseTool, input, toolContext, response) ->
Maybe.fromOptional(
afterToolCallbackSyncInstance.call(
invocationContext, baseTool, input, toolContext, response)));
} else {
logger.warn(
"Invalid afterToolCallback callback type: {}. Ignoring this callback.",
callback.getClass().getName());
}
}
this.afterToolCallback = builder.build();
}
return this;
}
@CanIgnoreReturnValue
public Builder afterToolCallbackSync(AfterToolCallbackSync afterToolCallbackSync) {
this.afterToolCallback =
ImmutableList.of(
(invocationContext, baseTool, input, toolContext, response) ->
Maybe.fromOptional(
afterToolCallbackSync.call(
invocationContext, baseTool, input, toolContext, response)));
return this;
}
@CanIgnoreReturnValue
public Builder inputSchema(Schema inputSchema) {
this.inputSchema = inputSchema;
return this;
}
@CanIgnoreReturnValue
public Builder outputSchema(Schema outputSchema) {
this.outputSchema = outputSchema;
return this;
}
@CanIgnoreReturnValue
public Builder executor(Executor executor) {
this.executor = executor;
return this;
}
@CanIgnoreReturnValue
public Builder outputKey(String outputKey) {
this.outputKey = outputKey;
return this;
}
@CanIgnoreReturnValue
public Builder codeExecutor(BaseCodeExecutor codeExecutor) {
this.codeExecutor = codeExecutor;
return this;
}
protected void validate() {
this.disallowTransferToParent =
this.disallowTransferToParent != null && this.disallowTransferToParent;
this.disallowTransferToPeers =
this.disallowTransferToPeers != null && this.disallowTransferToPeers;
if (this.outputSchema != null) {
if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {
System.err.println(
"Warning: Invalid config for agent "
+ this.name
+ ": outputSchema cannot co-exist with agent transfer"
+ " configurations. Setting disallowTransferToParent=true and"
+ " disallowTransferToPeers=true.");
this.disallowTransferToParent = true;
this.disallowTransferToPeers = true;
}
if (this.subAgents != null && !this.subAgents.isEmpty()) {
throw new IllegalArgumentException(
"Invalid config for agent "
+ this.name
+ ": if outputSchema is set, subAgents must be empty to disable agent"
+ " transfer.");
}
if (this.toolsUnion != null && !this.toolsUnion.isEmpty()) {
throw new IllegalArgumentException(
"Invalid config for agent "
+ this.name
+ ": if outputSchema is set, tools must be empty.");
}
}
}
public LlmAgent build() {
validate();
return new LlmAgent(this);
}
}
protected BaseLlmFlow determineLlmFlow() {
if (disallowTransferToParent() && disallowTransferToPeers() && subAgents().isEmpty()) {
return new SingleFlow(maxSteps);
} else {
return new AutoFlow(maxSteps);
}
}
private void maybeSaveOutputToState(Event event) {
if (outputKey().isPresent() && event.finalResponse() && event.content().isPresent()) {
// Concatenate text from all parts.
Object output;
String rawResult =
event.content().flatMap(Content::parts).orElse(ImmutableList.of()).stream()
.map(part -> part.text().orElse(""))
.collect(joining());
Optional<Schema> outputSchema = outputSchema();
if (outputSchema.isPresent()) {
try {
Map<String, Object> validatedMap =
SchemaUtils.validateOutputSchema(rawResult, outputSchema.get());
output = validatedMap;
} catch (JsonProcessingException e) {
logger.error(
"LlmAgent output for outputKey '{}' was not valid JSON, despite an outputSchema being"
+ " present. Saving raw output to state.",
outputKey().get(),
e);
output = rawResult;
} catch (IllegalArgumentException e) {
logger.error(
"LlmAgent output for outputKey '{}' did not match the outputSchema. Saving raw output"
+ " to state.",
outputKey().get(),
e);
output = rawResult;
}
} else {
output = rawResult;
}
event.actions().stateDelta().put(outputKey().get(), output);
}
}
@Override
protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
return llmFlow.run(invocationContext).doOnNext(this::maybeSaveOutputToState);
}
@Override
protected Flowable<Event> runLiveImpl(InvocationContext invocationContext) {
return llmFlow.runLive(invocationContext).doOnNext(this::maybeSaveOutputToState);
}
/**
* Constructs the text instruction for this agent based on the {@link #instruction} field. Also
* returns a boolean indicating that state injection should be bypassed when the instruction is
* constructed with an {@link Instruction.Provider}.
*
* <p>This method is only for use by Agent Development Kit.
*
* @param context The context to retrieve the session state.
* @return The resolved instruction as a {@link Single} wrapped Map.Entry. The key is the
* instruction string and the value is a boolean indicating if state injection should be
* bypassed.
*/
public Single<Map.Entry<String, Boolean>> canonicalInstruction(ReadonlyContext context) {
if (instruction instanceof Instruction.Static staticInstr) {
return Single.just(Map.entry(staticInstr.instruction(), false));
} else if (instruction instanceof Instruction.Provider provider) {
return provider.getInstruction().apply(context).map(instr -> Map.entry(instr, true));
}
throw new IllegalStateException("Unknown Instruction subtype: " + instruction.getClass());
}
/**
* Constructs the text global instruction for this agent based on the {@link #globalInstruction}
* field. Also returns a boolean indicating that state injection should be bypassed when the
* instruction is constructed with an {@link Instruction.Provider}.
*
* <p>This method is only for use by Agent Development Kit.
*
* @param context The context to retrieve the session state.
* @return The resolved global instruction as a {@link Single} wrapped Map.Entry. The key is the
* instruction string and the value is a boolean indicating if state injection should be
* bypassed.
*/
public Single<Map.Entry<String, Boolean>> canonicalGlobalInstruction(ReadonlyContext context) {
if (globalInstruction instanceof Instruction.Static staticInstr) {
return Single.just(Map.entry(staticInstr.instruction(), false));
} else if (globalInstruction instanceof Instruction.Provider provider) {
return provider.getInstruction().apply(context).map(instr -> Map.entry(instr, true));
}
throw new IllegalStateException("Unknown Instruction subtype: " + globalInstruction.getClass());
}
/**
* Constructs the list of tools for this agent based on the {@link #tools} field.
*
* <p>This method is only for use by Agent Development Kit.
*
* @param context The context to retrieve the session state.
* @return The resolved list of tools as a {@link Single} wrapped list of {@link BaseTool}.
*/
public Flowable<BaseTool> canonicalTools(Optional<ReadonlyContext> context) {
List<Flowable<BaseTool>> toolFlowables = new ArrayList<>();
for (Object toolOrToolset : toolsUnion) {
if (toolOrToolset instanceof BaseTool baseTool) {
toolFlowables.add(Flowable.just(baseTool));
} else if (toolOrToolset instanceof BaseToolset baseToolset) {
toolFlowables.add(baseToolset.getTools(context.orElse(null)));
} else {
throw new IllegalArgumentException(
"Object in tools list is not of a supported type: "
+ toolOrToolset.getClass().getName());
}
}
return Flowable.concat(toolFlowables);
}
/** Overload of canonicalTools that defaults to an empty context. */
public Flowable<BaseTool> canonicalTools() {
return canonicalTools(Optional.empty());
}
/** Convenience overload of canonicalTools that accepts a non-optional ReadonlyContext. */
public Flowable<BaseTool> canonicalTools(ReadonlyContext context) {
return canonicalTools(Optional.ofNullable(context));
}
public Instruction instruction() {
return instruction;
}
public Instruction globalInstruction() {
return globalInstruction;
}
public Optional<Model> model() {
return model;
}
public boolean planning() {
return planning;
}
public Optional<Integer> maxSteps() {
return maxSteps;
}
public Optional<GenerateContentConfig> generateContentConfig() {
return generateContentConfig;
}
// TODO: Remove this getter - examples should only be provided via ExampleTool
public Optional<BaseExampleProvider> exampleProvider() {
return exampleProvider;
}
public IncludeContents includeContents() {
return includeContents;
}
public List<BaseTool> tools() {
return canonicalTools().toList().blockingGet();
}
public List<Object> toolsUnion() {
return toolsUnion;
}
public ImmutableList<BaseToolset> toolsets() {
return toolsets;
}
public boolean disallowTransferToParent() {
return disallowTransferToParent;
}
public boolean disallowTransferToPeers() {
return disallowTransferToPeers;
}
public Optional<List<? extends BeforeModelCallback>> beforeModelCallback() {
return beforeModelCallback;
}
public Optional<List<? extends AfterModelCallback>> afterModelCallback() {
return afterModelCallback;
}
public Optional<List<? extends BeforeToolCallback>> beforeToolCallback() {
return beforeToolCallback;
}
public Optional<List<? extends AfterToolCallback>> afterToolCallback() {
return afterToolCallback;
}
public Optional<Schema> inputSchema() {
return inputSchema;
}
public Optional<Schema> outputSchema() {
return outputSchema;
}
public Optional<Executor> executor() {
return executor;
}
public Optional<String> outputKey() {
return outputKey;
}
@Nullable
public BaseCodeExecutor codeExecutor() {
return codeExecutor.orElse(null);
}
public Model resolvedModel() {
if (resolvedModel == null) {
synchronized (this) {
if (resolvedModel == null) {
resolvedModel = resolveModelInternal();
}
}
}
return resolvedModel;
}
/**
* Resolves the model for this agent, checking first if it is defined locally, then searching
* through ancestors.
*
* <p>This method is only for use by Agent Development Kit.
*
* @return The resolved {@link Model} for this agent.
* @throws IllegalStateException if no model is found for this agent or its ancestors.
*/
private Model resolveModelInternal() {
if (this.model.isPresent()) {
Model currentModel = this.model.get();
if (currentModel.model().isPresent()) {
return currentModel;
}
if (currentModel.modelName().isPresent()) {
String modelName = currentModel.modelName().get();
BaseLlm resolvedLlm = LlmRegistry.getLlm(modelName);
return Model.builder().modelName(modelName).model(resolvedLlm).build();
}
}
BaseAgent current = this.parentAgent();
while (current != null) {
if (current instanceof LlmAgent) {
return ((LlmAgent) current).resolvedModel();
}
current = current.parentAgent();
}
throw new IllegalStateException("No model found for agent " + name() + " or its ancestors.");
}
/**
* Creates an LlmAgent from configuration with full subagent support.
*
* @param config the agent configuration
* @param configAbsPath The absolute path to the agent config file. This is needed for resolving
* relative paths for e.g. tools and subagents.
* @return the configured LlmAgent
* @throws ConfigurationException if the configuration is invalid
*/
public static LlmAgent fromConfig(LlmAgentConfig config, String configAbsPath)
throws ConfigurationException {
logger.debug("Creating LlmAgent from config: {}", config.name());
// Validate required fields
if (config.name() == null || config.name().trim().isEmpty()) {
throw new ConfigurationException("Agent name is required");
}
if (config.instruction() == null || config.instruction().trim().isEmpty()) {
throw new ConfigurationException("Agent instruction is required");
}
// Create builder with required fields
Builder builder =
LlmAgent.builder()
.name(config.name())
.description(nullToEmpty(config.description()))
.instruction(config.instruction());
if (config.model() != null && !config.model().trim().isEmpty()) {
builder.model(config.model());
}
try {
if (config.tools() != null) {
builder.tools(ToolResolver.resolveToolsAndToolsets(config.tools(), configAbsPath));
}
} catch (ConfigurationException e) {
throw new ConfigurationException("Error resolving tools for agent " + config.name(), e);
}
// Resolve and add subagents using the utility class
if (config.subAgents() != null && !config.subAgents().isEmpty()) {
ImmutableList<BaseAgent> subAgents =
ConfigAgentUtils.resolveSubAgents(config.subAgents(), configAbsPath);
builder.subAgents(subAgents);
}
// Set optional transfer configuration
if (config.disallowTransferToParent() != null) {
builder.disallowTransferToParent(config.disallowTransferToParent());
}
if (config.disallowTransferToPeers() != null) {
builder.disallowTransferToPeers(config.disallowTransferToPeers());
}
// Set optional output key
if (config.outputKey() != null && !config.outputKey().trim().isEmpty()) {
builder.outputKey(config.outputKey());
}
// Set optional include_contents
if (config.includeContents() != null) {
builder.includeContents(config.includeContents());
}
// Set optional generateContentConfig
if (config.generateContentConfig() != null) {
builder.generateContentConfig(config.generateContentConfig());
}
// Resolve callbacks if configured
setCallbacksFromConfig(config, builder);
// Build and return the agent
LlmAgent agent = builder.build();
logger.info(
"Successfully created LlmAgent: {} with {} subagents",
agent.name(),
agent.subAgents() != null ? agent.subAgents().size() : 0);
return agent;
}
private static void setCallbacksFromConfig(LlmAgentConfig config, Builder builder)
throws ConfigurationException {
setCallbackFromConfig(
config.beforeAgentCallbacks(),
Callbacks.BeforeAgentCallbackBase.class,
"before_agent_callback",
builder::beforeAgentCallback);
setCallbackFromConfig(
config.afterAgentCallbacks(),
Callbacks.AfterAgentCallbackBase.class,
"after_agent_callback",
builder::afterAgentCallback);
setCallbackFromConfig(
config.beforeModelCallbacks(),
Callbacks.BeforeModelCallbackBase.class,
"before_model_callback",
builder::beforeModelCallback);
setCallbackFromConfig(
config.afterModelCallbacks(),
Callbacks.AfterModelCallbackBase.class,
"after_model_callback",
builder::afterModelCallback);
setCallbackFromConfig(
config.beforeToolCallbacks(),
Callbacks.BeforeToolCallbackBase.class,
"before_tool_callback",
builder::beforeToolCallback);
setCallbackFromConfig(
config.afterToolCallbacks(),
Callbacks.AfterToolCallbackBase.class,
"after_tool_callback",
builder::afterToolCallback);
}
private static <T> void setCallbackFromConfig(
@Nullable List<LlmAgentConfig.CallbackRef> refs,
Class<T> callbackBaseClass,
String callbackTypeName,
Consumer<ImmutableList<T>> builderSetter)
throws ConfigurationException {
if (refs != null) {
ImmutableList.Builder<T> list = ImmutableList.builder();
for (LlmAgentConfig.CallbackRef ref : refs) {
list.add(
ComponentRegistry.getInstance()
.get(ref.name(), callbackBaseClass)
.orElseThrow(
() ->
new ConfigurationException(
"Invalid " + callbackTypeName + ": " + ref.name())));
}
builderSetter.accept(list.build());
}
}
}
|
googleapis/google-cloud-java | 37,396 | java-chat/proto-google-cloud-chat-v1/src/main/java/com/google/chat/v1/ListMembershipsResponse.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/membership.proto
// Protobuf Java Version: 3.25.8
package com.google.chat.v1;
/**
*
*
* <pre>
* Response to list memberships of the space.
* </pre>
*
* Protobuf type {@code google.chat.v1.ListMembershipsResponse}
*/
public final class ListMembershipsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.chat.v1.ListMembershipsResponse)
ListMembershipsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListMembershipsResponse.newBuilder() to construct.
private ListMembershipsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListMembershipsResponse() {
memberships_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListMembershipsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.chat.v1.MembershipProto
.internal_static_google_chat_v1_ListMembershipsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.chat.v1.MembershipProto
.internal_static_google_chat_v1_ListMembershipsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.chat.v1.ListMembershipsResponse.class,
com.google.chat.v1.ListMembershipsResponse.Builder.class);
}
public static final int MEMBERSHIPS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.chat.v1.Membership> memberships_;
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
@java.lang.Override
public java.util.List<com.google.chat.v1.Membership> getMembershipsList() {
return memberships_;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
@java.lang.Override
public java.util.List<? extends com.google.chat.v1.MembershipOrBuilder>
getMembershipsOrBuilderList() {
return memberships_;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
@java.lang.Override
public int getMembershipsCount() {
return memberships_.size();
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
@java.lang.Override
public com.google.chat.v1.Membership getMemberships(int index) {
return memberships_.get(index);
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
@java.lang.Override
public com.google.chat.v1.MembershipOrBuilder getMembershipsOrBuilder(int index) {
return memberships_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, 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 < memberships_.size(); i++) {
output.writeMessage(1, memberships_.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 < memberships_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, memberships_.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.chat.v1.ListMembershipsResponse)) {
return super.equals(obj);
}
com.google.chat.v1.ListMembershipsResponse other =
(com.google.chat.v1.ListMembershipsResponse) obj;
if (!getMembershipsList().equals(other.getMembershipsList())) 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 (getMembershipsCount() > 0) {
hash = (37 * hash) + MEMBERSHIPS_FIELD_NUMBER;
hash = (53 * hash) + getMembershipsList().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.chat.v1.ListMembershipsResponse parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.chat.v1.ListMembershipsResponse 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.ListMembershipsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.chat.v1.ListMembershipsResponse 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.ListMembershipsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.chat.v1.ListMembershipsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.chat.v1.ListMembershipsResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.chat.v1.ListMembershipsResponse 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.ListMembershipsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.chat.v1.ListMembershipsResponse 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.ListMembershipsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.chat.v1.ListMembershipsResponse 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.ListMembershipsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response to list memberships of the space.
* </pre>
*
* Protobuf type {@code google.chat.v1.ListMembershipsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.chat.v1.ListMembershipsResponse)
com.google.chat.v1.ListMembershipsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.chat.v1.MembershipProto
.internal_static_google_chat_v1_ListMembershipsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.chat.v1.MembershipProto
.internal_static_google_chat_v1_ListMembershipsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.chat.v1.ListMembershipsResponse.class,
com.google.chat.v1.ListMembershipsResponse.Builder.class);
}
// Construct using com.google.chat.v1.ListMembershipsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (membershipsBuilder_ == null) {
memberships_ = java.util.Collections.emptyList();
} else {
memberships_ = null;
membershipsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.chat.v1.MembershipProto
.internal_static_google_chat_v1_ListMembershipsResponse_descriptor;
}
@java.lang.Override
public com.google.chat.v1.ListMembershipsResponse getDefaultInstanceForType() {
return com.google.chat.v1.ListMembershipsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.chat.v1.ListMembershipsResponse build() {
com.google.chat.v1.ListMembershipsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.chat.v1.ListMembershipsResponse buildPartial() {
com.google.chat.v1.ListMembershipsResponse result =
new com.google.chat.v1.ListMembershipsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.chat.v1.ListMembershipsResponse result) {
if (membershipsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
memberships_ = java.util.Collections.unmodifiableList(memberships_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.memberships_ = memberships_;
} else {
result.memberships_ = membershipsBuilder_.build();
}
}
private void buildPartial0(com.google.chat.v1.ListMembershipsResponse 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.chat.v1.ListMembershipsResponse) {
return mergeFrom((com.google.chat.v1.ListMembershipsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.chat.v1.ListMembershipsResponse other) {
if (other == com.google.chat.v1.ListMembershipsResponse.getDefaultInstance()) return this;
if (membershipsBuilder_ == null) {
if (!other.memberships_.isEmpty()) {
if (memberships_.isEmpty()) {
memberships_ = other.memberships_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMembershipsIsMutable();
memberships_.addAll(other.memberships_);
}
onChanged();
}
} else {
if (!other.memberships_.isEmpty()) {
if (membershipsBuilder_.isEmpty()) {
membershipsBuilder_.dispose();
membershipsBuilder_ = null;
memberships_ = other.memberships_;
bitField0_ = (bitField0_ & ~0x00000001);
membershipsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMembershipsFieldBuilder()
: null;
} else {
membershipsBuilder_.addAllMessages(other.memberships_);
}
}
}
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.chat.v1.Membership m =
input.readMessage(com.google.chat.v1.Membership.parser(), extensionRegistry);
if (membershipsBuilder_ == null) {
ensureMembershipsIsMutable();
memberships_.add(m);
} else {
membershipsBuilder_.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.chat.v1.Membership> memberships_ =
java.util.Collections.emptyList();
private void ensureMembershipsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
memberships_ = new java.util.ArrayList<com.google.chat.v1.Membership>(memberships_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.chat.v1.Membership,
com.google.chat.v1.Membership.Builder,
com.google.chat.v1.MembershipOrBuilder>
membershipsBuilder_;
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public java.util.List<com.google.chat.v1.Membership> getMembershipsList() {
if (membershipsBuilder_ == null) {
return java.util.Collections.unmodifiableList(memberships_);
} else {
return membershipsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public int getMembershipsCount() {
if (membershipsBuilder_ == null) {
return memberships_.size();
} else {
return membershipsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public com.google.chat.v1.Membership getMemberships(int index) {
if (membershipsBuilder_ == null) {
return memberships_.get(index);
} else {
return membershipsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder setMemberships(int index, com.google.chat.v1.Membership value) {
if (membershipsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMembershipsIsMutable();
memberships_.set(index, value);
onChanged();
} else {
membershipsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder setMemberships(
int index, com.google.chat.v1.Membership.Builder builderForValue) {
if (membershipsBuilder_ == null) {
ensureMembershipsIsMutable();
memberships_.set(index, builderForValue.build());
onChanged();
} else {
membershipsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder addMemberships(com.google.chat.v1.Membership value) {
if (membershipsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMembershipsIsMutable();
memberships_.add(value);
onChanged();
} else {
membershipsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder addMemberships(int index, com.google.chat.v1.Membership value) {
if (membershipsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMembershipsIsMutable();
memberships_.add(index, value);
onChanged();
} else {
membershipsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder addMemberships(com.google.chat.v1.Membership.Builder builderForValue) {
if (membershipsBuilder_ == null) {
ensureMembershipsIsMutable();
memberships_.add(builderForValue.build());
onChanged();
} else {
membershipsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder addMemberships(
int index, com.google.chat.v1.Membership.Builder builderForValue) {
if (membershipsBuilder_ == null) {
ensureMembershipsIsMutable();
memberships_.add(index, builderForValue.build());
onChanged();
} else {
membershipsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder addAllMemberships(
java.lang.Iterable<? extends com.google.chat.v1.Membership> values) {
if (membershipsBuilder_ == null) {
ensureMembershipsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, memberships_);
onChanged();
} else {
membershipsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder clearMemberships() {
if (membershipsBuilder_ == null) {
memberships_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
membershipsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public Builder removeMemberships(int index) {
if (membershipsBuilder_ == null) {
ensureMembershipsIsMutable();
memberships_.remove(index);
onChanged();
} else {
membershipsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public com.google.chat.v1.Membership.Builder getMembershipsBuilder(int index) {
return getMembershipsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public com.google.chat.v1.MembershipOrBuilder getMembershipsOrBuilder(int index) {
if (membershipsBuilder_ == null) {
return memberships_.get(index);
} else {
return membershipsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public java.util.List<? extends com.google.chat.v1.MembershipOrBuilder>
getMembershipsOrBuilderList() {
if (membershipsBuilder_ != null) {
return membershipsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(memberships_);
}
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public com.google.chat.v1.Membership.Builder addMembershipsBuilder() {
return getMembershipsFieldBuilder()
.addBuilder(com.google.chat.v1.Membership.getDefaultInstance());
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public com.google.chat.v1.Membership.Builder addMembershipsBuilder(int index) {
return getMembershipsFieldBuilder()
.addBuilder(index, com.google.chat.v1.Membership.getDefaultInstance());
}
/**
*
*
* <pre>
* Unordered list. List of memberships in the requested (or first) page.
* </pre>
*
* <code>
* repeated .google.chat.v1.Membership memberships = 1 [(.google.api.field_behavior) = UNORDERED_LIST];
* </code>
*/
public java.util.List<com.google.chat.v1.Membership.Builder> getMembershipsBuilderList() {
return getMembershipsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.chat.v1.Membership,
com.google.chat.v1.Membership.Builder,
com.google.chat.v1.MembershipOrBuilder>
getMembershipsFieldBuilder() {
if (membershipsBuilder_ == null) {
membershipsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.chat.v1.Membership,
com.google.chat.v1.Membership.Builder,
com.google.chat.v1.MembershipOrBuilder>(
memberships_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
memberships_ = null;
}
return membershipsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that you can send as `pageToken` to retrieve the next page of
* results. If empty, 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.chat.v1.ListMembershipsResponse)
}
// @@protoc_insertion_point(class_scope:google.chat.v1.ListMembershipsResponse)
private static final com.google.chat.v1.ListMembershipsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.chat.v1.ListMembershipsResponse();
}
public static com.google.chat.v1.ListMembershipsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListMembershipsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListMembershipsResponse>() {
@java.lang.Override
public ListMembershipsResponse 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<ListMembershipsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListMembershipsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.chat.v1.ListMembershipsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ofbiz | 37,612 | framework/base/src/main/java/org/apache/ofbiz/base/util/string/UelFunctions.java | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.base.util.string;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.el.FunctionMapper;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.cyberneko.html.parsers.DOMParser;
import org.apache.ofbiz.base.location.FlexibleLocation;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.FileUtil;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilXml;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/** Implements Unified Expression Language functions.
* <p>Built-in functions are divided into a number of
* namespace prefixes:</p>
* <table border="1" summary="">
* <tr><td colspan="2"><b><code>date:</code> contains miscellaneous date/time functions</b></td></tr>
* <tr><td><code>date:second(Timestamp, TimeZone, Locale)</code></td><td>Returns the second value of <code>Timestamp</code> (0 - 59).</td></tr>
* <tr><td><code>date:minute(Timestamp, TimeZone, Locale)</code></td><td>Returns the minute value of <code>Timestamp</code> (0 - 59).</td></tr>
* <tr><td><code>date:hour(Timestamp, TimeZone, Locale)</code></td><td>Returns the hour value of <code>Timestamp</code> (0 - 23).</td></tr>
* <tr><td><code>date:dayOfMonth(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of month value of <code>Timestamp</code> (1 - 31).</td></tr>
* <tr><td><code>date:dayOfWeek(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of week value of <code>Timestamp</code> (Sunday = 1, Saturday = 7).</td></tr>
* <tr><td><code>date:dayOfYear(Timestamp, TimeZone, Locale)</code></td><td>Returns the day of year value of <code>Timestamp</code>.</td></tr>
* <tr><td><code>date:week(Timestamp, TimeZone, Locale)</code></td><td>Returns the week value of <code>Timestamp</code>.</td></tr>
* <tr><td><code>date:month(Timestamp, TimeZone, Locale)</code></td><td>Returns the month value of <code>Timestamp</code> (January = 0, December = 11).</td></tr>
* <tr><td><code>date:year(Timestamp, TimeZone, Locale)</code></td><td>Returns the year value of <code>Timestamp</code>.</td></tr>
* <tr><td><code>date:dayStart(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to start of day.</td></tr>
* <tr><td><code>date:dayEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of day.</td></tr>
* <tr><td><code>date:weekStart(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to start of week.</td></tr>
* <tr><td><code>date:weekEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of week.</td></tr>
* <tr><td><code>date:monthStart(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to start of month.</td></tr>
* <tr><td><code>date:monthEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of month.</td></tr>
* <tr><td><code>date:yearStart(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to start of year.</td></tr>
* <tr><td><code>date:yearEnd(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> set to end of year.</td></tr>
* <tr><td><code>date:dateStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date <code>String</code> (yyyy-mm-dd).</td></tr>
* <tr><td><code>date:localizedDateStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date <code>String</code> formatted according to the supplied locale.</td></tr>
* <tr><td><code>date:dateTimeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date-time <code>String</code> (yyyy-mm-dd hh:mm).</td></tr>
* <tr><td><code>date:localizedDateTimeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a date-time <code>String</code> formatted according to the supplied locale.</td></tr>
* <tr><td><code>date:timeStr(Timestamp, TimeZone, Locale)</code></td><td>Returns <code>Timestamp</code> as a time <code>String</code> (hh:mm).</td></tr>
* <tr><td><code>date:nowTimestamp()</code></td><td>Returns <code>Timestamp </code> for right now.</td></tr>
* <tr><td colspan="2"><b><code>math:</code> maps to <code>java.lang.Math</code></b></td></tr>
* <tr><td><code>math:absDouble(double)</code></td><td>Returns the absolute value of a <code>double</code> value.</td></tr>
* <tr><td><code>math:absFloat(float)</code></td><td>Returns the absolute value of a <code>float</code> value.</td></tr>
* <tr><td><code>math:absInt(int)</code></td><td>Returns the absolute value of an <code>int</code> value.</td></tr>
* <tr><td><code>math:absLong(long)</code></td><td>Returns the absolute value of a <code>long</code> value.</td></tr>
* <tr><td><code>math:acos(double)</code></td><td>Returns the arc cosine of an angle, in the range of 0.0 through <i>pi</i>.</td></tr>
* <tr><td><code>math:asin(double)</code></td><td>Returns the arc sine of an angle, in the range of -<i>pi</i>/2 through <i>pi</i>/2.</td></tr>
* <tr><td><code>math:atan(double)</code></td><td>Returns the arc tangent of an angle, in the range of -<i>pi</i>/2 through <i>pi</i>/2.</td></tr>
* <tr><td><code>math:atan2(double, double)</code></td><td>Converts rectangular coordinates (<code>x</code>, <code>y</code>) to polar (r, <i>theta</i>).</td></tr>
* <tr><td><code>math:cbrt(double)</code></td><td>Returns the cube root of a <code>double</code> value.</td></tr>
* <tr><td><code>math:ceil(double)</code></td><td>Returns the smallest (closest to negative infinity) <code>double</code> value that is greater than or equal to the argument and is equal to a mathematical integer.</td></tr>
* <tr><td><code>math:cos(double)</code></td><td>Returns the trigonometric cosine of an angle.</td></tr>
* <tr><td><code>math:cosh(double)</code></td><td>Returns the hyperbolic cosine of a <code>double</code> value.</td></tr>
* <tr><td><code>math:exp(double)</code></td><td>Returns Euler's number <i>e</i> raised to the power of a <code>double</code> value.</td></tr>
* <tr><td><code>math:expm1(double)</code></td><td>Returns <i>e</i><sup>x</sup> -1.</td></tr>
* <tr><td><code>math:floor(double)</code></td><td>Returns the largest (closest to positive infinity) <code>double</code> value that is less than or equal to the argument and is equal to a mathematical integer.</td></tr>
* <tr><td><code>math:hypot(double, double)</code></td><td>Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) without intermediate overflow or underflow.</td></tr>
* <tr><td><code>math:IEEEremainder(double, double)</code></td><td>Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.</td></tr>
* <tr><td><code>math:log(double)</code></td><td>Returns the natural logarithm (base <i>e</i>) of a <code>double</code> value.</td></tr>
* <tr><td><code>math:log10(double)</code></td><td>Returns the base 10 logarithm of a <code>double</code> value.</td></tr>
* <tr><td><code>math:log1p(double)</code></td><td>Returns the natural logarithm of the sum of the argument and 1.</td></tr>
* <tr><td><code>math:maxDouble(double, double)</code></td><td>Returns the greater of two <code>double</code> values.</td></tr>
* <tr><td><code>math:maxFloat(float, float)</code></td><td>Returns the greater of two <code>float</code> values.</td></tr>
* <tr><td><code>math:maxInt(int, int)</code></td><td>Returns the greater of two <code>int</code> values.</td></tr>
* <tr><td><code>math:maxLong(long, long)</code></td><td>Returns the greater of two <code>long</code> values.</td></tr>
* <tr><td><code>math:minDouble(double, double)</code></td><td>Returns the smaller of two <code>double</code> values.</td></tr>
* <tr><td><code>math:minFloat(float, float)</code></td><td>Returns the smaller of two <code>float</code> values.</td></tr>
* <tr><td><code>math:minInt(int, int)</code></td><td>Returns the smaller of two <code>int</code> values.</td></tr>
* <tr><td><code>math:minLong(long, long)</code></td><td>Returns the smaller of two <code>long</code> values.</td></tr>
* <tr><td><code>math:pow(double, double)</code></td><td>Returns the value of the first argument raised to the power of the second argument.</td></tr>
* <tr><td><code>math:random()</code></td><td>Returns a <code>double</code> value with a positive sign, greater than or equal to <code>0.0</code> and less than <code>1.0</code>.</td></tr>
* <tr><td><code>math:rint(double)</code></td><td>Returns the <code>double</code> value that is closest in value to the argument and is equal to a mathematical integer.</td></tr>
* <tr><td><code>math:roundDouble(double)</code></td><td>Returns the closest <code>long</code> to the argument.</td></tr>
* <tr><td><code>math:roundFloat(float)</code></td><td>Returns the closest <code>int</code> to the argument.</td></tr>
* <tr><td><code>math:signumDouble(double)</code></td><td>Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.</td></tr>
* <tr><td><code>math:signumFloat(float)</code></td><td>Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.</td></tr>
* <tr><td><code>math:sin(double)</code></td><td>Returns the trigonometric sine of an angle.</td></tr>
* <tr><td><code>math:sinh(double)</code></td><td>Returns the hyperbolic sine of a <code>double</code> value.</td></tr>
* <tr><td><code>math:sqrt(double)</code></td><td>Returns the correctly rounded positive square root of a <code>double</code> value.</td></tr>
* <tr><td><code>math:tan(double)</code></td><td>Returns the trigonometric tangent of an angle.</td></tr>
* <tr><td><code>math:tanh(double)</code></td><td>Returns the hyperbolic tangent of a <code>double</code> value.</td></tr>
* <tr><td><code>math:toDegrees(double)</code></td><td>Converts an angle measured in radians to an approximately equivalent angle measured in degrees.</td></tr>
* <tr><td><code>math:toRadians(double)</code></td><td>Converts an angle measured in degrees to an approximately equivalent angle measured in radians.</td></tr>
* <tr><td><code>math:ulpDouble(double)</code></td><td>Returns the size of an ulp (units in the last place) of the argument.</td></tr>
* <tr><td><code>math:ulpFloat(float)</code></td><td>Returns the size of an ulp (units in the last place) of the argument.</td></tr>
* <tr><td colspan="2"><b><code>str:</code> maps to <code>java.lang.String</code></b></td></tr>
* <tr><td><code>str:endsWith(String, String)</code></td><td>Returns <code>true</code> if this string ends with the specified suffix.</td></tr>
* <tr><td><code>str:indexOf(String, String)</code></td><td>Returns the index within this string of the first occurrence of the specified substring.</td></tr>
* <tr><td><code>str:lastIndexOf(String, String)</code></td><td>Returns the index within this string of the last occurrence of the specified character.</td></tr>
* <tr><td><code>str:length(String)</code></td><td>Returns the length of this string.</td></tr>
* <tr><td><code>str:replace(String, String, String)</code></td><td>Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.</td></tr>
* <tr><td><code>str:replaceAll(String, String, String)</code></td><td>Replaces each substring of this string that matches the given regular expression with the given replacement.</td></tr>
* <tr><td><code>str:replaceFirst(String, String, String)</code></td><td>Replaces the first substring of this string that matches the given regular expression with the given replacement.</td></tr>
* <tr><td><code>str:startsWith(String, String)</code></td><td>Returns <code>true</code> if this string starts with the specified prefix.</td></tr>
* <tr><td><code>str:endstring(String, int)</code></td><td>Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.</td></tr>
* <tr><td><code>str:substring(String, int, int)</code></td><td>Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.</td></tr>
* <tr><td><code>str:toLowerCase(String)</code></td><td>Converts all of the characters in this String to lower case using the rules of the default locale.</td></tr>
* <tr><td><code>str:toString(Object)</code></td><td>Converts <code>Object</code> to a <code>String</code> - bypassing localization.</td></tr>
* <tr><td><code>str:toUpperCase(String)</code></td><td>Converts all of the characters in this String to upper case using the rules of the default locale.</td></tr>
* <tr><td><code>str:trim(String)</code></td><td>Returns a copy of the string, with leading and trailing whitespace omitted.</td></tr>
* <tr><td colspan="2"><b><code>sys:</code> maps to <code>java.lang.System</code></b></td></tr>
* <tr><td><code>sys:getenv(String)</code></td><td>Gets the value of the specified environment variable.</td></tr>
* <tr><td><code>sys:getProperty(String)</code></td><td>Gets the system property indicated by the specified key.</td></tr>
* <tr><td colspan="2"><b><code>util:</code> contains miscellaneous utility functions</b></td></tr>
* <tr><td><code>util:defaultLocale()</code></td><td>Returns the default <code>Locale</code>.</td></tr>
* <tr><td><code>util:defaultTimeZone()</code></td><td>Returns the default <code>TimeZone</code>.</td></tr>
* <tr><td><code>util:size(Object)</code></td><td>Returns the size of <code>Maps</code>,
* <code>Collections</code>, and <code>Strings</code>. Invalid <code>Object</code> types return -1.</td></tr>
* <tr><td><code>util:urlExists(String)</code></td><td>Returns <code>true</code> if the specified URL exists.</td></tr>
* <tr><td colspan="2"><b><code>dom:</code> contains <code>org.w3c.dom.*</code> functions</b></td></tr>
* <tr><td><code>dom:readHtmlDocument(String)</code></td><td>Reads an HTML file and returns a <code>org.w3c.dom.Document</code> instance.</td></tr>
* <tr><td><code>dom:readXmlDocument(String)</code></td><td>Reads an XML file and returns a <code>org.w3c.dom.Document</code> instance.</td></tr>
* <tr><td><code>dom:toHtmlString(Node, String encoding, boolean indent, int indentAmount)</code></td><td>Returns a <code>org.w3c.dom.Node</code> as an HTML <code>String</code>.</td></tr>
* <tr><td><code>dom:toXmlString(Node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount)</code></td><td>Returns a <code>org.w3c.dom.Node</code> as an XML <code>String</code>.</td></tr>
* <tr><td><code>dom:writeXmlDocument(String, Node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount)</code></td><td>Writes a <code>org.w3c.dom.Node</code> to an XML file and returns <code>true</code> if successful.</td></tr>
* </table>
*/
public class UelFunctions {
public static final String module = UelFunctions.class.getName();
protected static final Functions functionMapper = new Functions();
/** Returns a <code>FunctionMapper</code> instance.
* @return <code>FunctionMapper</code> instance
*/
public static FunctionMapper getFunctionMapper() {
return functionMapper;
}
protected static class Functions extends FunctionMapper {
protected final Map<String, Method> functionMap = new HashMap<String, Method>();
public Functions() {
try {
this.functionMap.put("date:second", UtilDateTime.class.getMethod("getSecond", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:minute", UtilDateTime.class.getMethod("getMinute", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:hour", UtilDateTime.class.getMethod("getHour", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:dayOfMonth", UtilDateTime.class.getMethod("getDayOfMonth", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:dayOfWeek", UtilDateTime.class.getMethod("getDayOfWeek", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:dayOfYear", UtilDateTime.class.getMethod("getDayOfYear", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:week", UtilDateTime.class.getMethod("getWeek", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:month", UtilDateTime.class.getMethod("getMonth", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:year", UtilDateTime.class.getMethod("getYear", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:dayStart", UtilDateTime.class.getMethod("getDayStart", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:dayEnd", UtilDateTime.class.getMethod("getDayEnd", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:weekStart", UtilDateTime.class.getMethod("getWeekStart", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:weekEnd", UtilDateTime.class.getMethod("getWeekEnd", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:monthStart", UtilDateTime.class.getMethod("getMonthStart", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:monthEnd", UtilDateTime.class.getMethod("getMonthEnd", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:yearStart", UtilDateTime.class.getMethod("getYearStart", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:yearEnd", UtilDateTime.class.getMethod("getYearEnd", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:dateStr", UelFunctions.class.getMethod("dateString", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:localizedDateStr", UelFunctions.class.getMethod("localizedDateString", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:localizedDateTimeStr", UelFunctions.class.getMethod("localizedDateTimeString", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:timeStr", UelFunctions.class.getMethod("timeString", Timestamp.class, TimeZone.class, Locale.class));
this.functionMap.put("date:nowTimestamp", UtilDateTime.class.getMethod("nowTimestamp"));
this.functionMap.put("math:absDouble", Math.class.getMethod("abs", double.class));
this.functionMap.put("math:absFloat", Math.class.getMethod("abs", float.class));
this.functionMap.put("math:absInt", Math.class.getMethod("abs", int.class));
this.functionMap.put("math:absLong", Math.class.getMethod("abs", long.class));
this.functionMap.put("math:acos", Math.class.getMethod("abs", double.class));
this.functionMap.put("math:asin", Math.class.getMethod("asin", double.class));
this.functionMap.put("math:atan", Math.class.getMethod("atan", double.class));
this.functionMap.put("math:atan2", Math.class.getMethod("max", double.class, double.class));
this.functionMap.put("math:cbrt", Math.class.getMethod("cbrt", double.class));
this.functionMap.put("math:ceil", Math.class.getMethod("ceil", double.class));
this.functionMap.put("math:cos", Math.class.getMethod("cos", double.class));
this.functionMap.put("math:cosh", Math.class.getMethod("cosh", double.class));
this.functionMap.put("math:exp", Math.class.getMethod("exp", double.class));
this.functionMap.put("math:expm1", Math.class.getMethod("expm1", double.class));
this.functionMap.put("math:floor", Math.class.getMethod("floor", double.class));
this.functionMap.put("math:hypot", Math.class.getMethod("hypot", double.class, double.class));
this.functionMap.put("math:IEEEremainder", Math.class.getMethod("IEEEremainder", double.class, double.class));
this.functionMap.put("math:log", Math.class.getMethod("log", double.class));
this.functionMap.put("math:log10", Math.class.getMethod("log10", double.class));
this.functionMap.put("math:log1p", Math.class.getMethod("log1p", double.class));
this.functionMap.put("math:maxDouble", Math.class.getMethod("max", double.class, double.class));
this.functionMap.put("math:maxFloat", Math.class.getMethod("max", float.class, float.class));
this.functionMap.put("math:maxInt", Math.class.getMethod("max", int.class, int.class));
this.functionMap.put("math:maxLong", Math.class.getMethod("max", long.class, long.class));
this.functionMap.put("math:minDouble", Math.class.getMethod("min", double.class, double.class));
this.functionMap.put("math:minFloat", Math.class.getMethod("min", float.class, float.class));
this.functionMap.put("math:minInt", Math.class.getMethod("min", int.class, int.class));
this.functionMap.put("math:minLong", Math.class.getMethod("min", long.class, long.class));
this.functionMap.put("math:pow", Math.class.getMethod("pow", double.class, double.class));
this.functionMap.put("math:random", Math.class.getMethod("random"));
this.functionMap.put("math:rint", Math.class.getMethod("rint", double.class));
this.functionMap.put("math:roundDouble", Math.class.getMethod("round", double.class));
this.functionMap.put("math:roundFloat", Math.class.getMethod("round", float.class));
this.functionMap.put("math:signumDouble", Math.class.getMethod("signum", double.class));
this.functionMap.put("math:signumFloat", Math.class.getMethod("signum", float.class));
this.functionMap.put("math:sin", Math.class.getMethod("sin", double.class));
this.functionMap.put("math:sinh", Math.class.getMethod("sinh", double.class));
this.functionMap.put("math:sqrt", Math.class.getMethod("sqrt", double.class));
this.functionMap.put("math:tan", Math.class.getMethod("tan", double.class));
this.functionMap.put("math:tanh", Math.class.getMethod("tanh", double.class));
this.functionMap.put("math:toDegrees", Math.class.getMethod("toDegrees", double.class));
this.functionMap.put("math:toRadians", Math.class.getMethod("toRadians", double.class));
this.functionMap.put("math:ulpDouble", Math.class.getMethod("ulp", double.class));
this.functionMap.put("math:ulpFloat", Math.class.getMethod("ulp", float.class));
this.functionMap.put("str:endsWith", UelFunctions.class.getMethod("endsWith", String.class, String.class));
this.functionMap.put("str:indexOf", UelFunctions.class.getMethod("indexOf", String.class, String.class));
this.functionMap.put("str:lastIndexOf", UelFunctions.class.getMethod("lastIndexOf", String.class, String.class));
this.functionMap.put("str:length", UelFunctions.class.getMethod("length", String.class));
this.functionMap.put("str:replace", UelFunctions.class.getMethod("replace", String.class, String.class, String.class));
this.functionMap.put("str:replaceAll", UelFunctions.class.getMethod("replaceAll", String.class, String.class, String.class));
this.functionMap.put("str:replaceFirst", UelFunctions.class.getMethod("replaceFirst", String.class, String.class, String.class));
this.functionMap.put("str:startsWith", UelFunctions.class.getMethod("startsWith", String.class, String.class));
this.functionMap.put("str:endstring", UelFunctions.class.getMethod("endString", String.class, int.class));
this.functionMap.put("str:substring", UelFunctions.class.getMethod("subString", String.class, int.class, int.class));
this.functionMap.put("str:toString", UelFunctions.class.getMethod("toString", Object.class));
this.functionMap.put("str:toLowerCase", UelFunctions.class.getMethod("toLowerCase", String.class));
this.functionMap.put("str:toUpperCase", UelFunctions.class.getMethod("toUpperCase", String.class));
this.functionMap.put("str:trim", UelFunctions.class.getMethod("trim", String.class));
this.functionMap.put("sys:getenv", UelFunctions.class.getMethod("sysGetEnv", String.class));
this.functionMap.put("sys:getProperty", UelFunctions.class.getMethod("sysGetProp", String.class));
this.functionMap.put("util:size", UelFunctions.class.getMethod("getSize", Object.class));
this.functionMap.put("util:defaultLocale", Locale.class.getMethod("getDefault"));
this.functionMap.put("util:defaultTimeZone", TimeZone.class.getMethod("getDefault"));
this.functionMap.put("util:urlExists", UelFunctions.class.getMethod("urlExists", String.class));
this.functionMap.put("dom:readHtmlDocument", UelFunctions.class.getMethod("readHtmlDocument", String.class));
this.functionMap.put("dom:readXmlDocument", UelFunctions.class.getMethod("readXmlDocument", String.class));
this.functionMap.put("dom:toHtmlString", UelFunctions.class.getMethod("toHtmlString", Node.class, String.class, boolean.class, int.class));
this.functionMap.put("dom:toXmlString", UelFunctions.class.getMethod("toXmlString", Node.class, String.class, boolean.class, boolean.class, int.class));
this.functionMap.put("dom:writeXmlDocument", UelFunctions.class.getMethod("writeXmlDocument", String.class, Node.class, String.class, boolean.class, boolean.class, int.class));
} catch (Exception e) {
Debug.logError(e, "Error while initializing UelFunctions.Functions instance", module);
}
Debug.logVerbose("UelFunctions.Functions loaded " + this.functionMap.size() + " functions", module);
}
@Override
public Method resolveFunction(String prefix, String localName) {
return functionMap.get(prefix + ":" + localName);
}
}
/** Add a function to OFBiz's built-in UEL functions. */
public static synchronized void setFunction(String prefix, String localName, Method method) {
functionMapper.functionMap.put(prefix + ":" + localName, method);
}
public static String dateString(Timestamp stamp, TimeZone timeZone, Locale locale) {
DateFormat dateFormat = UtilDateTime.toDateFormat(UtilDateTime.getDateFormat(), timeZone, locale);
dateFormat.setTimeZone(timeZone);
return dateFormat.format(stamp);
}
public static String localizedDateString(Timestamp stamp, TimeZone timeZone, Locale locale) {
DateFormat dateFormat = UtilDateTime.toDateFormat(null, timeZone, locale);
dateFormat.setTimeZone(timeZone);
return dateFormat.format(stamp);
}
public static String dateTimeString(Timestamp stamp, TimeZone timeZone, Locale locale) {
DateFormat dateFormat = UtilDateTime.toDateTimeFormat("yyyy-MM-dd HH:mm", timeZone, locale);
dateFormat.setTimeZone(timeZone);
return dateFormat.format(stamp);
}
public static String localizedDateTimeString(Timestamp stamp, TimeZone timeZone, Locale locale) {
DateFormat dateFormat = UtilDateTime.toDateTimeFormat(null, timeZone, locale);
dateFormat.setTimeZone(timeZone);
return dateFormat.format(stamp);
}
public static String timeString(Timestamp stamp, TimeZone timeZone, Locale locale) {
DateFormat dateFormat = UtilDateTime.toTimeFormat(UtilDateTime.getTimeFormat(), timeZone, locale);
dateFormat.setTimeZone(timeZone);
return dateFormat.format(stamp);
}
@SuppressWarnings("rawtypes")
public static int getSize(Object obj) {
try {
Map map = (Map) obj;
return map.size();
} catch (Exception e) {}
try {
Collection coll = (Collection) obj;
return coll.size();
} catch (Exception e) {}
try {
String str = (String) obj;
return str.length();
} catch (Exception e) {}
return -1;
}
public static boolean endsWith(String str1, String str2) {
try {
return str1.endsWith(str2);
} catch (Exception e) {}
return false;
}
public static int indexOf(String str1, String str2) {
try {
return str1.indexOf(str2);
} catch (Exception e) {}
return -1;
}
public static int lastIndexOf(String str1, String str2) {
try {
return str1.lastIndexOf(str2);
} catch (Exception e) {}
return -1;
}
public static int length(String str1) {
try {
return str1.length();
} catch (Exception e) {}
return -1;
}
public static String replace(String str1, String str2, String str3) {
try {
return str1.replace(str2, str3);
} catch (Exception e) {}
return null;
}
public static String replaceAll(String str1, String str2, String str3) {
try {
return str1.replaceAll(str2, str3);
} catch (Exception e) {}
return null;
}
public static String replaceFirst(String str1, String str2, String str3) {
try {
return str1.replaceFirst(str2, str3);
} catch (Exception e) {}
return null;
}
public static boolean startsWith(String str1, String str2) {
try {
return str1.startsWith(str2);
} catch (Exception e) {}
return false;
}
public static String endString(String str, int index) {
try {
return str.substring(index);
} catch (Exception e) {}
return null;
}
public static String subString(String str, int beginIndex, int endIndex) {
try {
return str.substring(beginIndex, endIndex);
} catch (Exception e) {}
return null;
}
public static String trim(String str) {
try {
return str.trim();
} catch (Exception e) {}
return null;
}
public static String toLowerCase(String str) {
try {
return str.toLowerCase();
} catch (Exception e) {}
return null;
}
public static String toUpperCase(String str) {
try {
return str.toUpperCase();
} catch (Exception e) {}
return null;
}
public static String toString(Object obj) {
return obj.toString();
}
public static String sysGetEnv(String str) {
try {
return System.getenv(str);
} catch (Exception e) {}
return null;
}
public static String sysGetProp(String str) {
try {
return System.getProperty(str);
} catch (Exception e) {}
return null;
}
public static boolean urlExists(String str) {
boolean result = false;
try {
URL url = FlexibleLocation.resolveLocation(str);
if (url != null) {
InputStream is = url.openStream();
result = true;
is.close();
}
} catch (Exception e) {}
return result;
}
public static Document readHtmlDocument(String str) {
Document document = null;
try {
URL url = FlexibleLocation.resolveLocation(str);
if (url != null) {
DOMParser parser = new DOMParser();
parser.setFeature("http://xml.org/sax/features/namespaces", false);
parser.parse(url.toExternalForm());
document = parser.getDocument();
} else {
Debug.logError("Unable to locate HTML document " + str, module);
}
} catch (Exception e) {
Debug.logError(e, "Error while reading HTML document " + str, module);
}
return document;
}
public static Document readXmlDocument(String str) {
Document document = null;
try {
URL url = FlexibleLocation.resolveLocation(str);
if (url != null) {
InputStream is = url.openStream();
document = UtilXml.readXmlDocument(is, str);
is.close();
} else {
Debug.logError("Unable to locate XML document " + str, module);
}
} catch (Exception e) {
Debug.logError(e, "Error while reading XML document " + str, module);
}
return document;
}
public static boolean writeXmlDocument(String str, Node node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount) {
try {
File file = FileUtil.getFile(str);
if (file != null) {
FileOutputStream os = new FileOutputStream(file);
UtilXml.writeXmlDocument(node, os, encoding, omitXmlDeclaration, indent, indentAmount);
os.close();
return true;
} else {
Debug.logError("Unable to create XML document " + str, module);
}
} catch (Exception e) {
Debug.logError(e, "Error while writing XML document " + str, module);
}
return false;
}
public static String toHtmlString(Node node, String encoding, boolean indent, int indentAmount) {
try {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xalan=\"http://xml.apache.org/xslt\" version=\"1.0\">\n");
sb.append("<xsl:output method=\"html\" encoding=\"");
sb.append(encoding == null ? "UTF-8" : encoding);
sb.append("\"");
sb.append(" indent=\"");
sb.append(indent ? "yes" : "no");
sb.append("\"");
if (indent) {
sb.append(" xalan:indent-amount=\"");
sb.append(indentAmount <= 0 ? 4 : indentAmount);
sb.append("\"");
}
sb.append("/>\n<xsl:template match=\"@*|node()\">\n");
sb.append("<xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy>\n");
sb.append("</xsl:template>\n</xsl:stylesheet>\n");
ByteArrayInputStream bis = new ByteArrayInputStream(sb.toString().getBytes());
TransformerFactory transformerFactory = TransformerFactory.newInstance();
ByteArrayOutputStream os = new ByteArrayOutputStream();
UtilXml.transformDomDocument(transformerFactory.newTransformer(new StreamSource(bis)), node, os);
os.close();
return os.toString();
} catch (Exception e) {
Debug.logError(e, "Error while creating HTML String ", module);
}
return null;
}
public static String toXmlString(Node node, String encoding, boolean omitXmlDeclaration, boolean indent, int indentAmount) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
UtilXml.writeXmlDocument(node, os, encoding, omitXmlDeclaration, indent, indentAmount);
os.close();
return os.toString();
} catch (Exception e) {
Debug.logError(e, "Error while creating XML String ", module);
}
return null;
}
}
|
googleapis/google-cloud-java | 37,425 | java-iap/proto-google-cloud-iap-v1/src/main/java/com/google/cloud/iap/v1/ListTunnelDestGroupsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/iap/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.iap.v1;
/**
*
*
* <pre>
* The response from ListTunnelDestGroups.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.ListTunnelDestGroupsResponse}
*/
public final class ListTunnelDestGroupsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iap.v1.ListTunnelDestGroupsResponse)
ListTunnelDestGroupsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTunnelDestGroupsResponse.newBuilder() to construct.
private ListTunnelDestGroupsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTunnelDestGroupsResponse() {
tunnelDestGroups_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTunnelDestGroupsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_ListTunnelDestGroupsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_ListTunnelDestGroupsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.class,
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.Builder.class);
}
public static final int TUNNEL_DEST_GROUPS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.iap.v1.TunnelDestGroup> tunnelDestGroups_;
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.iap.v1.TunnelDestGroup> getTunnelDestGroupsList() {
return tunnelDestGroups_;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.iap.v1.TunnelDestGroupOrBuilder>
getTunnelDestGroupsOrBuilderList() {
return tunnelDestGroups_;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
@java.lang.Override
public int getTunnelDestGroupsCount() {
return tunnelDestGroups_.size();
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
@java.lang.Override
public com.google.cloud.iap.v1.TunnelDestGroup getTunnelDestGroups(int index) {
return tunnelDestGroups_.get(index);
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
@java.lang.Override
public com.google.cloud.iap.v1.TunnelDestGroupOrBuilder getTunnelDestGroupsOrBuilder(int index) {
return tunnelDestGroups_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that you can send as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that you can send 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 < tunnelDestGroups_.size(); i++) {
output.writeMessage(1, tunnelDestGroups_.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 < tunnelDestGroups_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, tunnelDestGroups_.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.iap.v1.ListTunnelDestGroupsResponse)) {
return super.equals(obj);
}
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse other =
(com.google.cloud.iap.v1.ListTunnelDestGroupsResponse) obj;
if (!getTunnelDestGroupsList().equals(other.getTunnelDestGroupsList())) 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 (getTunnelDestGroupsCount() > 0) {
hash = (37 * hash) + TUNNEL_DEST_GROUPS_FIELD_NUMBER;
hash = (53 * hash) + getTunnelDestGroupsList().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.iap.v1.ListTunnelDestGroupsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.iap.v1.ListTunnelDestGroupsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response from ListTunnelDestGroups.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.ListTunnelDestGroupsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iap.v1.ListTunnelDestGroupsResponse)
com.google.cloud.iap.v1.ListTunnelDestGroupsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_ListTunnelDestGroupsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_ListTunnelDestGroupsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.class,
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.Builder.class);
}
// Construct using com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (tunnelDestGroupsBuilder_ == null) {
tunnelDestGroups_ = java.util.Collections.emptyList();
} else {
tunnelDestGroups_ = null;
tunnelDestGroupsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_ListTunnelDestGroupsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.iap.v1.ListTunnelDestGroupsResponse getDefaultInstanceForType() {
return com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iap.v1.ListTunnelDestGroupsResponse build() {
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iap.v1.ListTunnelDestGroupsResponse buildPartial() {
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse result =
new com.google.cloud.iap.v1.ListTunnelDestGroupsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.iap.v1.ListTunnelDestGroupsResponse result) {
if (tunnelDestGroupsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
tunnelDestGroups_ = java.util.Collections.unmodifiableList(tunnelDestGroups_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.tunnelDestGroups_ = tunnelDestGroups_;
} else {
result.tunnelDestGroups_ = tunnelDestGroupsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.iap.v1.ListTunnelDestGroupsResponse 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.iap.v1.ListTunnelDestGroupsResponse) {
return mergeFrom((com.google.cloud.iap.v1.ListTunnelDestGroupsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iap.v1.ListTunnelDestGroupsResponse other) {
if (other == com.google.cloud.iap.v1.ListTunnelDestGroupsResponse.getDefaultInstance())
return this;
if (tunnelDestGroupsBuilder_ == null) {
if (!other.tunnelDestGroups_.isEmpty()) {
if (tunnelDestGroups_.isEmpty()) {
tunnelDestGroups_ = other.tunnelDestGroups_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.addAll(other.tunnelDestGroups_);
}
onChanged();
}
} else {
if (!other.tunnelDestGroups_.isEmpty()) {
if (tunnelDestGroupsBuilder_.isEmpty()) {
tunnelDestGroupsBuilder_.dispose();
tunnelDestGroupsBuilder_ = null;
tunnelDestGroups_ = other.tunnelDestGroups_;
bitField0_ = (bitField0_ & ~0x00000001);
tunnelDestGroupsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getTunnelDestGroupsFieldBuilder()
: null;
} else {
tunnelDestGroupsBuilder_.addAllMessages(other.tunnelDestGroups_);
}
}
}
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.iap.v1.TunnelDestGroup m =
input.readMessage(
com.google.cloud.iap.v1.TunnelDestGroup.parser(), extensionRegistry);
if (tunnelDestGroupsBuilder_ == null) {
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.add(m);
} else {
tunnelDestGroupsBuilder_.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.iap.v1.TunnelDestGroup> tunnelDestGroups_ =
java.util.Collections.emptyList();
private void ensureTunnelDestGroupsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
tunnelDestGroups_ =
new java.util.ArrayList<com.google.cloud.iap.v1.TunnelDestGroup>(tunnelDestGroups_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.iap.v1.TunnelDestGroup,
com.google.cloud.iap.v1.TunnelDestGroup.Builder,
com.google.cloud.iap.v1.TunnelDestGroupOrBuilder>
tunnelDestGroupsBuilder_;
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public java.util.List<com.google.cloud.iap.v1.TunnelDestGroup> getTunnelDestGroupsList() {
if (tunnelDestGroupsBuilder_ == null) {
return java.util.Collections.unmodifiableList(tunnelDestGroups_);
} else {
return tunnelDestGroupsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public int getTunnelDestGroupsCount() {
if (tunnelDestGroupsBuilder_ == null) {
return tunnelDestGroups_.size();
} else {
return tunnelDestGroupsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public com.google.cloud.iap.v1.TunnelDestGroup getTunnelDestGroups(int index) {
if (tunnelDestGroupsBuilder_ == null) {
return tunnelDestGroups_.get(index);
} else {
return tunnelDestGroupsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder setTunnelDestGroups(int index, com.google.cloud.iap.v1.TunnelDestGroup value) {
if (tunnelDestGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.set(index, value);
onChanged();
} else {
tunnelDestGroupsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder setTunnelDestGroups(
int index, com.google.cloud.iap.v1.TunnelDestGroup.Builder builderForValue) {
if (tunnelDestGroupsBuilder_ == null) {
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.set(index, builderForValue.build());
onChanged();
} else {
tunnelDestGroupsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder addTunnelDestGroups(com.google.cloud.iap.v1.TunnelDestGroup value) {
if (tunnelDestGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.add(value);
onChanged();
} else {
tunnelDestGroupsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder addTunnelDestGroups(int index, com.google.cloud.iap.v1.TunnelDestGroup value) {
if (tunnelDestGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.add(index, value);
onChanged();
} else {
tunnelDestGroupsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder addTunnelDestGroups(
com.google.cloud.iap.v1.TunnelDestGroup.Builder builderForValue) {
if (tunnelDestGroupsBuilder_ == null) {
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.add(builderForValue.build());
onChanged();
} else {
tunnelDestGroupsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder addTunnelDestGroups(
int index, com.google.cloud.iap.v1.TunnelDestGroup.Builder builderForValue) {
if (tunnelDestGroupsBuilder_ == null) {
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.add(index, builderForValue.build());
onChanged();
} else {
tunnelDestGroupsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder addAllTunnelDestGroups(
java.lang.Iterable<? extends com.google.cloud.iap.v1.TunnelDestGroup> values) {
if (tunnelDestGroupsBuilder_ == null) {
ensureTunnelDestGroupsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tunnelDestGroups_);
onChanged();
} else {
tunnelDestGroupsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder clearTunnelDestGroups() {
if (tunnelDestGroupsBuilder_ == null) {
tunnelDestGroups_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
tunnelDestGroupsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public Builder removeTunnelDestGroups(int index) {
if (tunnelDestGroupsBuilder_ == null) {
ensureTunnelDestGroupsIsMutable();
tunnelDestGroups_.remove(index);
onChanged();
} else {
tunnelDestGroupsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public com.google.cloud.iap.v1.TunnelDestGroup.Builder getTunnelDestGroupsBuilder(int index) {
return getTunnelDestGroupsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public com.google.cloud.iap.v1.TunnelDestGroupOrBuilder getTunnelDestGroupsOrBuilder(
int index) {
if (tunnelDestGroupsBuilder_ == null) {
return tunnelDestGroups_.get(index);
} else {
return tunnelDestGroupsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public java.util.List<? extends com.google.cloud.iap.v1.TunnelDestGroupOrBuilder>
getTunnelDestGroupsOrBuilderList() {
if (tunnelDestGroupsBuilder_ != null) {
return tunnelDestGroupsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(tunnelDestGroups_);
}
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public com.google.cloud.iap.v1.TunnelDestGroup.Builder addTunnelDestGroupsBuilder() {
return getTunnelDestGroupsFieldBuilder()
.addBuilder(com.google.cloud.iap.v1.TunnelDestGroup.getDefaultInstance());
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public com.google.cloud.iap.v1.TunnelDestGroup.Builder addTunnelDestGroupsBuilder(int index) {
return getTunnelDestGroupsFieldBuilder()
.addBuilder(index, com.google.cloud.iap.v1.TunnelDestGroup.getDefaultInstance());
}
/**
*
*
* <pre>
* TunnelDestGroup existing in the project.
* </pre>
*
* <code>repeated .google.cloud.iap.v1.TunnelDestGroup tunnel_dest_groups = 1;</code>
*/
public java.util.List<com.google.cloud.iap.v1.TunnelDestGroup.Builder>
getTunnelDestGroupsBuilderList() {
return getTunnelDestGroupsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.iap.v1.TunnelDestGroup,
com.google.cloud.iap.v1.TunnelDestGroup.Builder,
com.google.cloud.iap.v1.TunnelDestGroupOrBuilder>
getTunnelDestGroupsFieldBuilder() {
if (tunnelDestGroupsBuilder_ == null) {
tunnelDestGroupsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.iap.v1.TunnelDestGroup,
com.google.cloud.iap.v1.TunnelDestGroup.Builder,
com.google.cloud.iap.v1.TunnelDestGroupOrBuilder>(
tunnelDestGroups_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
tunnelDestGroups_ = null;
}
return tunnelDestGroupsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that you can send as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that you can send as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that you can send as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that you can send as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that you can send 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.iap.v1.ListTunnelDestGroupsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.iap.v1.ListTunnelDestGroupsResponse)
private static final com.google.cloud.iap.v1.ListTunnelDestGroupsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iap.v1.ListTunnelDestGroupsResponse();
}
public static com.google.cloud.iap.v1.ListTunnelDestGroupsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTunnelDestGroupsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListTunnelDestGroupsResponse>() {
@java.lang.Override
public ListTunnelDestGroupsResponse 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<ListTunnelDestGroupsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTunnelDestGroupsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iap.v1.ListTunnelDestGroupsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 37,554 | jdk/src/share/classes/javax/swing/plaf/basic/BasicSplitPaneDivider.java | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.basic;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.border.Border;
import java.beans.*;
import sun.swing.DefaultLookup;
/**
* Divider used by BasicSplitPaneUI. Subclassers may wish to override
* paint to do something more interesting.
* The border effect is drawn in BasicSplitPaneUI, so if you don't like
* that border, reset it there.
* To conditionally drag from certain areas subclass mousePressed and
* call super when you wish the dragging to begin.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Scott Violet
*/
public class BasicSplitPaneDivider extends Container
implements PropertyChangeListener
{
/**
* Width or height of the divider based on orientation
* BasicSplitPaneUI adds two to this.
*/
protected static final int ONE_TOUCH_SIZE = 6;
protected static final int ONE_TOUCH_OFFSET = 2;
/**
* Handles mouse dragging message to do the actual dragging.
*/
protected DragController dragger;
/**
* UI this instance was created from.
*/
protected BasicSplitPaneUI splitPaneUI;
/**
* Size of the divider.
*/
protected int dividerSize = 0; // default - SET TO 0???
/**
* Divider that is used for noncontinuous layout mode.
*/
protected Component hiddenDivider;
/**
* JSplitPane the receiver is contained in.
*/
protected JSplitPane splitPane;
/**
* Handles mouse events from both this class, and the split pane.
* Mouse events are handled for the splitpane since you want to be able
* to drag when clicking on the border of the divider, which is not
* drawn by the divider.
*/
protected MouseHandler mouseHandler;
/**
* Orientation of the JSplitPane.
*/
protected int orientation;
/**
* Button for quickly toggling the left component.
*/
protected JButton leftButton;
/**
* Button for quickly toggling the right component.
*/
protected JButton rightButton;
/** Border. */
private Border border;
/**
* Is the mouse over the divider?
*/
private boolean mouseOver;
private int oneTouchSize;
private int oneTouchOffset;
/**
* If true the one touch buttons are centered on the divider.
*/
private boolean centerOneTouchButtons;
/**
* Creates an instance of BasicSplitPaneDivider. Registers this
* instance for mouse events and mouse dragged events.
*/
public BasicSplitPaneDivider(BasicSplitPaneUI ui) {
oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui,
"SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE);
oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui,
"SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET);
centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(),
ui, "SplitPane.centerOneTouchButtons", true);
setLayout(new DividerLayout());
setBasicSplitPaneUI(ui);
orientation = splitPane.getOrientation();
setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ?
Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) :
Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
setBackground(UIManager.getColor("SplitPane.background"));
}
private void revalidateSplitPane() {
invalidate();
if (splitPane != null) {
splitPane.revalidate();
}
}
/**
* Sets the SplitPaneUI that is using the receiver.
*/
public void setBasicSplitPaneUI(BasicSplitPaneUI newUI) {
if (splitPane != null) {
splitPane.removePropertyChangeListener(this);
if (mouseHandler != null) {
splitPane.removeMouseListener(mouseHandler);
splitPane.removeMouseMotionListener(mouseHandler);
removeMouseListener(mouseHandler);
removeMouseMotionListener(mouseHandler);
mouseHandler = null;
}
}
splitPaneUI = newUI;
if (newUI != null) {
splitPane = newUI.getSplitPane();
if (splitPane != null) {
if (mouseHandler == null) mouseHandler = new MouseHandler();
splitPane.addMouseListener(mouseHandler);
splitPane.addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
splitPane.addPropertyChangeListener(this);
if (splitPane.isOneTouchExpandable()) {
oneTouchExpandableChanged();
}
}
}
else {
splitPane = null;
}
}
/**
* Returns the <code>SplitPaneUI</code> the receiver is currently
* in.
*/
public BasicSplitPaneUI getBasicSplitPaneUI() {
return splitPaneUI;
}
/**
* Sets the size of the divider to <code>newSize</code>. That is
* the width if the splitpane is <code>HORIZONTAL_SPLIT</code>, or
* the height of <code>VERTICAL_SPLIT</code>.
*/
public void setDividerSize(int newSize) {
dividerSize = newSize;
}
/**
* Returns the size of the divider, that is the width if the splitpane
* is HORIZONTAL_SPLIT, or the height of VERTICAL_SPLIT.
*/
public int getDividerSize() {
return dividerSize;
}
/**
* Sets the border of this component.
* @since 1.3
*/
public void setBorder(Border border) {
Border oldBorder = this.border;
this.border = border;
}
/**
* Returns the border of this component or null if no border is
* currently set.
*
* @return the border object for this component
* @see #setBorder
* @since 1.3
*/
public Border getBorder() {
return border;
}
/**
* If a border has been set on this component, returns the
* border's insets, else calls super.getInsets.
*
* @return the value of the insets property.
* @see #setBorder
*/
public Insets getInsets() {
Border border = getBorder();
if (border != null) {
return border.getBorderInsets(this);
}
return super.getInsets();
}
/**
* Sets whether or not the mouse is currently over the divider.
*
* @param mouseOver whether or not the mouse is currently over the divider
* @since 1.5
*/
protected void setMouseOver(boolean mouseOver) {
this.mouseOver = mouseOver;
}
/**
* Returns whether or not the mouse is currently over the divider
*
* @return whether or not the mouse is currently over the divider
* @since 1.5
*/
public boolean isMouseOver() {
return mouseOver;
}
/**
* Returns dividerSize x dividerSize
*/
public Dimension getPreferredSize() {
// Ideally this would return the size from the layout manager,
// but that could result in the layed out size being different from
// the dividerSize, which may break developers as well as
// BasicSplitPaneUI.
if (orientation == JSplitPane.HORIZONTAL_SPLIT) {
return new Dimension(getDividerSize(), 1);
}
return new Dimension(1, getDividerSize());
}
/**
* Returns dividerSize x dividerSize
*/
public Dimension getMinimumSize() {
return getPreferredSize();
}
/**
* Property change event, presumably from the JSplitPane, will message
* updateOrientation if necessary.
*/
public void propertyChange(PropertyChangeEvent e) {
if (e.getSource() == splitPane) {
if (e.getPropertyName() == JSplitPane.ORIENTATION_PROPERTY) {
orientation = splitPane.getOrientation();
setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ?
Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) :
Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
revalidateSplitPane();
}
else if (e.getPropertyName() == JSplitPane.
ONE_TOUCH_EXPANDABLE_PROPERTY) {
oneTouchExpandableChanged();
}
}
}
/**
* Paints the divider.
*/
public void paint(Graphics g) {
super.paint(g);
// Paint the border.
Border border = getBorder();
if (border != null) {
Dimension size = getSize();
border.paintBorder(this, g, 0, 0, size.width, size.height);
}
}
/**
* Messaged when the oneTouchExpandable value of the JSplitPane the
* receiver is contained in changes. Will create the
* <code>leftButton</code> and <code>rightButton</code> if they
* are null. invalidates the receiver as well.
*/
protected void oneTouchExpandableChanged() {
if (!DefaultLookup.getBoolean(splitPane, splitPaneUI,
"SplitPane.supportsOneTouchButtons", true)) {
// Look and feel doesn't want to support one touch buttons, bail.
return;
}
if (splitPane.isOneTouchExpandable() &&
leftButton == null &&
rightButton == null) {
/* Create the left button and add an action listener to
expand/collapse it. */
leftButton = createLeftOneTouchButton();
if (leftButton != null)
leftButton.addActionListener(new OneTouchActionHandler(true));
/* Create the right button and add an action listener to
expand/collapse it. */
rightButton = createRightOneTouchButton();
if (rightButton != null)
rightButton.addActionListener(new OneTouchActionHandler
(false));
if (leftButton != null && rightButton != null) {
add(leftButton);
add(rightButton);
}
}
revalidateSplitPane();
}
/**
* Creates and return an instance of JButton that can be used to
* collapse the left component in the split pane.
*/
protected JButton createLeftOneTouchButton() {
JButton b = new JButton() {
public void setBorder(Border b) {
}
public void paint(Graphics g) {
if (splitPane != null) {
int[] xs = new int[3];
int[] ys = new int[3];
int blockSize;
// Fill the background first ...
g.setColor(this.getBackground());
g.fillRect(0, 0, this.getWidth(),
this.getHeight());
// ... then draw the arrow.
g.setColor(Color.black);
if (orientation == JSplitPane.VERTICAL_SPLIT) {
blockSize = Math.min(getHeight(), oneTouchSize);
xs[0] = blockSize;
xs[1] = 0;
xs[2] = blockSize << 1;
ys[0] = 0;
ys[1] = ys[2] = blockSize;
g.drawPolygon(xs, ys, 3); // Little trick to make the
// arrows of equal size
}
else {
blockSize = Math.min(getWidth(), oneTouchSize);
xs[0] = xs[2] = blockSize;
xs[1] = 0;
ys[0] = 0;
ys[1] = blockSize;
ys[2] = blockSize << 1;
}
g.fillPolygon(xs, ys, 3);
}
}
// Don't want the button to participate in focus traversable.
public boolean isFocusTraversable() {
return false;
}
};
b.setMinimumSize(new Dimension(oneTouchSize, oneTouchSize));
b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
b.setFocusPainted(false);
b.setBorderPainted(false);
b.setRequestFocusEnabled(false);
return b;
}
/**
* Creates and return an instance of JButton that can be used to
* collapse the right component in the split pane.
*/
protected JButton createRightOneTouchButton() {
JButton b = new JButton() {
public void setBorder(Border border) {
}
public void paint(Graphics g) {
if (splitPane != null) {
int[] xs = new int[3];
int[] ys = new int[3];
int blockSize;
// Fill the background first ...
g.setColor(this.getBackground());
g.fillRect(0, 0, this.getWidth(),
this.getHeight());
// ... then draw the arrow.
if (orientation == JSplitPane.VERTICAL_SPLIT) {
blockSize = Math.min(getHeight(), oneTouchSize);
xs[0] = blockSize;
xs[1] = blockSize << 1;
xs[2] = 0;
ys[0] = blockSize;
ys[1] = ys[2] = 0;
}
else {
blockSize = Math.min(getWidth(), oneTouchSize);
xs[0] = xs[2] = 0;
xs[1] = blockSize;
ys[0] = 0;
ys[1] = blockSize;
ys[2] = blockSize << 1;
}
g.setColor(Color.black);
g.fillPolygon(xs, ys, 3);
}
}
// Don't want the button to participate in focus traversable.
public boolean isFocusTraversable() {
return false;
}
};
b.setMinimumSize(new Dimension(oneTouchSize, oneTouchSize));
b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
b.setFocusPainted(false);
b.setBorderPainted(false);
b.setRequestFocusEnabled(false);
return b;
}
/**
* Message to prepare for dragging. This messages the BasicSplitPaneUI
* with startDragging.
*/
protected void prepareForDragging() {
splitPaneUI.startDragging();
}
/**
* Messages the BasicSplitPaneUI with dragDividerTo that this instance
* is contained in.
*/
protected void dragDividerTo(int location) {
splitPaneUI.dragDividerTo(location);
}
/**
* Messages the BasicSplitPaneUI with finishDraggingTo that this instance
* is contained in.
*/
protected void finishDraggingTo(int location) {
splitPaneUI.finishDraggingTo(location);
}
/**
* MouseHandler is responsible for converting mouse events
* (released, dragged...) into the appropriate DragController
* methods.
*
*/
protected class MouseHandler extends MouseAdapter
implements MouseMotionListener
{
/**
* Starts the dragging session by creating the appropriate instance
* of DragController.
*/
public void mousePressed(MouseEvent e) {
if ((e.getSource() == BasicSplitPaneDivider.this ||
e.getSource() == splitPane) &&
dragger == null &&splitPane.isEnabled()) {
Component newHiddenDivider = splitPaneUI.
getNonContinuousLayoutDivider();
if (hiddenDivider != newHiddenDivider) {
if (hiddenDivider != null) {
hiddenDivider.removeMouseListener(this);
hiddenDivider.removeMouseMotionListener(this);
}
hiddenDivider = newHiddenDivider;
if (hiddenDivider != null) {
hiddenDivider.addMouseMotionListener(this);
hiddenDivider.addMouseListener(this);
}
}
if (splitPane.getLeftComponent() != null &&
splitPane.getRightComponent() != null) {
if (orientation == JSplitPane.HORIZONTAL_SPLIT) {
dragger = new DragController(e);
}
else {
dragger = new VerticalDragController(e);
}
if (!dragger.isValid()) {
dragger = null;
}
else {
prepareForDragging();
dragger.continueDrag(e);
}
}
e.consume();
}
}
/**
* If dragger is not null it is messaged with completeDrag.
*/
public void mouseReleased(MouseEvent e) {
if (dragger != null) {
if (e.getSource() == splitPane) {
dragger.completeDrag(e.getX(), e.getY());
}
else if (e.getSource() == BasicSplitPaneDivider.this) {
Point ourLoc = getLocation();
dragger.completeDrag(e.getX() + ourLoc.x,
e.getY() + ourLoc.y);
}
else if (e.getSource() == hiddenDivider) {
Point hDividerLoc = hiddenDivider.getLocation();
int ourX = e.getX() + hDividerLoc.x;
int ourY = e.getY() + hDividerLoc.y;
dragger.completeDrag(ourX, ourY);
}
dragger = null;
e.consume();
}
}
//
// MouseMotionListener
//
/**
* If dragger is not null it is messaged with continueDrag.
*/
public void mouseDragged(MouseEvent e) {
if (dragger != null) {
if (e.getSource() == splitPane) {
dragger.continueDrag(e.getX(), e.getY());
}
else if (e.getSource() == BasicSplitPaneDivider.this) {
Point ourLoc = getLocation();
dragger.continueDrag(e.getX() + ourLoc.x,
e.getY() + ourLoc.y);
}
else if (e.getSource() == hiddenDivider) {
Point hDividerLoc = hiddenDivider.getLocation();
int ourX = e.getX() + hDividerLoc.x;
int ourY = e.getY() + hDividerLoc.y;
dragger.continueDrag(ourX, ourY);
}
e.consume();
}
}
/**
* Resets the cursor based on the orientation.
*/
public void mouseMoved(MouseEvent e) {
}
/**
* Invoked when the mouse enters a component.
*
* @param e MouseEvent describing the details of the enter event.
* @since 1.5
*/
public void mouseEntered(MouseEvent e) {
if (e.getSource() == BasicSplitPaneDivider.this) {
setMouseOver(true);
}
}
/**
* Invoked when the mouse exits a component.
*
* @param e MouseEvent describing the details of the exit event.
* @since 1.5
*/
public void mouseExited(MouseEvent e) {
if (e.getSource() == BasicSplitPaneDivider.this) {
setMouseOver(false);
}
}
}
/**
* Handles the events during a dragging session for a
* HORIZONTAL_SPLIT oriented split pane. This continually
* messages <code>dragDividerTo</code> and then when done messages
* <code>finishDraggingTo</code>. When an instance is created it should be
* messaged with <code>isValid</code> to insure that dragging can happen
* (dragging won't be allowed if the two views can not be resized).
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class DragController
{
/**
* Initial location of the divider.
*/
int initialX;
/**
* Maximum and minimum positions to drag to.
*/
int maxX, minX;
/**
* Initial location the mouse down happened at.
*/
int offset;
protected DragController(MouseEvent e) {
JSplitPane splitPane = splitPaneUI.getSplitPane();
Component leftC = splitPane.getLeftComponent();
Component rightC = splitPane.getRightComponent();
initialX = getLocation().x;
if (e.getSource() == BasicSplitPaneDivider.this) {
offset = e.getX();
}
else { // splitPane
offset = e.getX() - initialX;
}
if (leftC == null || rightC == null || offset < -1 ||
offset >= getSize().width) {
// Don't allow dragging.
maxX = -1;
}
else {
Insets insets = splitPane.getInsets();
if (leftC.isVisible()) {
minX = leftC.getMinimumSize().width;
if (insets != null) {
minX += insets.left;
}
}
else {
minX = 0;
}
if (rightC.isVisible()) {
int right = (insets != null) ? insets.right : 0;
maxX = Math.max(0, splitPane.getSize().width -
(getSize().width + right) -
rightC.getMinimumSize().width);
}
else {
int right = (insets != null) ? insets.right : 0;
maxX = Math.max(0, splitPane.getSize().width -
(getSize().width + right));
}
if (maxX < minX) minX = maxX = 0;
}
}
/**
* Returns true if the dragging session is valid.
*/
protected boolean isValid() {
return (maxX > 0);
}
/**
* Returns the new position to put the divider at based on
* the passed in MouseEvent.
*/
protected int positionForMouseEvent(MouseEvent e) {
int newX = (e.getSource() == BasicSplitPaneDivider.this) ?
(e.getX() + getLocation().x) : e.getX();
newX = Math.min(maxX, Math.max(minX, newX - offset));
return newX;
}
/**
* Returns the x argument, since this is used for horizontal
* splits.
*/
protected int getNeededLocation(int x, int y) {
int newX;
newX = Math.min(maxX, Math.max(minX, x - offset));
return newX;
}
protected void continueDrag(int newX, int newY) {
dragDividerTo(getNeededLocation(newX, newY));
}
/**
* Messages dragDividerTo with the new location for the mouse
* event.
*/
protected void continueDrag(MouseEvent e) {
dragDividerTo(positionForMouseEvent(e));
}
protected void completeDrag(int x, int y) {
finishDraggingTo(getNeededLocation(x, y));
}
/**
* Messages finishDraggingTo with the new location for the mouse
* event.
*/
protected void completeDrag(MouseEvent e) {
finishDraggingTo(positionForMouseEvent(e));
}
} // End of BasicSplitPaneDivider.DragController
/**
* Handles the events during a dragging session for a
* VERTICAL_SPLIT oriented split pane. This continually
* messages <code>dragDividerTo</code> and then when done messages
* <code>finishDraggingTo</code>. When an instance is created it should be
* messaged with <code>isValid</code> to insure that dragging can happen
* (dragging won't be allowed if the two views can not be resized).
*/
protected class VerticalDragController extends DragController
{
/* DragControllers ivars are now in terms of y, not x. */
protected VerticalDragController(MouseEvent e) {
super(e);
JSplitPane splitPane = splitPaneUI.getSplitPane();
Component leftC = splitPane.getLeftComponent();
Component rightC = splitPane.getRightComponent();
initialX = getLocation().y;
if (e.getSource() == BasicSplitPaneDivider.this) {
offset = e.getY();
}
else {
offset = e.getY() - initialX;
}
if (leftC == null || rightC == null || offset < -1 ||
offset > getSize().height) {
// Don't allow dragging.
maxX = -1;
}
else {
Insets insets = splitPane.getInsets();
if (leftC.isVisible()) {
minX = leftC.getMinimumSize().height;
if (insets != null) {
minX += insets.top;
}
}
else {
minX = 0;
}
if (rightC.isVisible()) {
int bottom = (insets != null) ? insets.bottom : 0;
maxX = Math.max(0, splitPane.getSize().height -
(getSize().height + bottom) -
rightC.getMinimumSize().height);
}
else {
int bottom = (insets != null) ? insets.bottom : 0;
maxX = Math.max(0, splitPane.getSize().height -
(getSize().height + bottom));
}
if (maxX < minX) minX = maxX = 0;
}
}
/**
* Returns the y argument, since this is used for vertical
* splits.
*/
protected int getNeededLocation(int x, int y) {
int newY;
newY = Math.min(maxX, Math.max(minX, y - offset));
return newY;
}
/**
* Returns the new position to put the divider at based on
* the passed in MouseEvent.
*/
protected int positionForMouseEvent(MouseEvent e) {
int newY = (e.getSource() == BasicSplitPaneDivider.this) ?
(e.getY() + getLocation().y) : e.getY();
newY = Math.min(maxX, Math.max(minX, newY - offset));
return newY;
}
} // End of BasicSplitPaneDividier.VerticalDragController
/**
* Used to layout a <code>BasicSplitPaneDivider</code>.
* Layout for the divider
* involves appropriately moving the left/right buttons around.
*
*/
protected class DividerLayout implements LayoutManager
{
public void layoutContainer(Container c) {
if (leftButton != null && rightButton != null &&
c == BasicSplitPaneDivider.this) {
if (splitPane.isOneTouchExpandable()) {
Insets insets = getInsets();
if (orientation == JSplitPane.VERTICAL_SPLIT) {
int extraX = (insets != null) ? insets.left : 0;
int blockSize = getHeight();
if (insets != null) {
blockSize -= (insets.top + insets.bottom);
blockSize = Math.max(blockSize, 0);
}
blockSize = Math.min(blockSize, oneTouchSize);
int y = (c.getSize().height - blockSize) / 2;
if (!centerOneTouchButtons) {
y = (insets != null) ? insets.top : 0;
extraX = 0;
}
leftButton.setBounds(extraX + oneTouchOffset, y,
blockSize * 2, blockSize);
rightButton.setBounds(extraX + oneTouchOffset +
oneTouchSize * 2, y,
blockSize * 2, blockSize);
}
else {
int extraY = (insets != null) ? insets.top : 0;
int blockSize = getWidth();
if (insets != null) {
blockSize -= (insets.left + insets.right);
blockSize = Math.max(blockSize, 0);
}
blockSize = Math.min(blockSize, oneTouchSize);
int x = (c.getSize().width - blockSize) / 2;
if (!centerOneTouchButtons) {
x = (insets != null) ? insets.left : 0;
extraY = 0;
}
leftButton.setBounds(x, extraY + oneTouchOffset,
blockSize, blockSize * 2);
rightButton.setBounds(x, extraY + oneTouchOffset +
oneTouchSize * 2, blockSize,
blockSize * 2);
}
}
else {
leftButton.setBounds(-5, -5, 1, 1);
rightButton.setBounds(-5, -5, 1, 1);
}
}
}
public Dimension minimumLayoutSize(Container c) {
// NOTE: This isn't really used, refer to
// BasicSplitPaneDivider.getPreferredSize for the reason.
// I leave it in hopes of having this used at some point.
if (c != BasicSplitPaneDivider.this || splitPane == null) {
return new Dimension(0,0);
}
Dimension buttonMinSize = null;
if (splitPane.isOneTouchExpandable() && leftButton != null) {
buttonMinSize = leftButton.getMinimumSize();
}
Insets insets = getInsets();
int width = getDividerSize();
int height = width;
if (orientation == JSplitPane.VERTICAL_SPLIT) {
if (buttonMinSize != null) {
int size = buttonMinSize.height;
if (insets != null) {
size += insets.top + insets.bottom;
}
height = Math.max(height, size);
}
width = 1;
}
else {
if (buttonMinSize != null) {
int size = buttonMinSize.width;
if (insets != null) {
size += insets.left + insets.right;
}
width = Math.max(width, size);
}
height = 1;
}
return new Dimension(width, height);
}
public Dimension preferredLayoutSize(Container c) {
return minimumLayoutSize(c);
}
public void removeLayoutComponent(Component c) {}
public void addLayoutComponent(String string, Component c) {}
} // End of class BasicSplitPaneDivider.DividerLayout
/**
* Listeners installed on the one touch expandable buttons.
*/
private class OneTouchActionHandler implements ActionListener {
/** True indicates the resize should go the minimum (top or left)
* vs false which indicates the resize should go to the maximum.
*/
private boolean toMinimum;
OneTouchActionHandler(boolean toMinimum) {
this.toMinimum = toMinimum;
}
public void actionPerformed(ActionEvent e) {
Insets insets = splitPane.getInsets();
int lastLoc = splitPane.getLastDividerLocation();
int currentLoc = splitPaneUI.getDividerLocation(splitPane);
int newLoc;
// We use the location from the UI directly, as the location the
// JSplitPane itself maintains is not necessarly correct.
if (toMinimum) {
if (orientation == JSplitPane.VERTICAL_SPLIT) {
if (currentLoc >= (splitPane.getHeight() -
insets.bottom - getHeight())) {
int maxLoc = splitPane.getMaximumDividerLocation();
newLoc = Math.min(lastLoc, maxLoc);
splitPaneUI.setKeepHidden(false);
}
else {
newLoc = insets.top;
splitPaneUI.setKeepHidden(true);
}
}
else {
if (currentLoc >= (splitPane.getWidth() -
insets.right - getWidth())) {
int maxLoc = splitPane.getMaximumDividerLocation();
newLoc = Math.min(lastLoc, maxLoc);
splitPaneUI.setKeepHidden(false);
}
else {
newLoc = insets.left;
splitPaneUI.setKeepHidden(true);
}
}
}
else {
if (orientation == JSplitPane.VERTICAL_SPLIT) {
if (currentLoc == insets.top) {
int maxLoc = splitPane.getMaximumDividerLocation();
newLoc = Math.min(lastLoc, maxLoc);
splitPaneUI.setKeepHidden(false);
}
else {
newLoc = splitPane.getHeight() - getHeight() -
insets.top;
splitPaneUI.setKeepHidden(true);
}
}
else {
if (currentLoc == insets.left) {
int maxLoc = splitPane.getMaximumDividerLocation();
newLoc = Math.min(lastLoc, maxLoc);
splitPaneUI.setKeepHidden(false);
}
else {
newLoc = splitPane.getWidth() - getWidth() -
insets.left;
splitPaneUI.setKeepHidden(true);
}
}
}
if (currentLoc != newLoc) {
splitPane.setDividerLocation(newLoc);
// We do this in case the dividers notion of the location
// differs from the real location.
splitPane.setLastDividerLocation(currentLoc);
}
}
} // End of class BasicSplitPaneDivider.LeftActionListener
}
|
googleapis/google-cloud-java | 37,408 | java-workflows/proto-google-cloud-workflows-v1/src/main/java/com/google/cloud/workflows/v1/ListWorkflowRevisionsResponse.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/workflows/v1/workflows.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.workflows.v1;
/**
*
*
* <pre>
* Response for the
* [ListWorkflowRevisions][google.cloud.workflows.v1.Workflows.ListWorkflowRevisions]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.workflows.v1.ListWorkflowRevisionsResponse}
*/
public final class ListWorkflowRevisionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.workflows.v1.ListWorkflowRevisionsResponse)
ListWorkflowRevisionsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListWorkflowRevisionsResponse.newBuilder() to construct.
private ListWorkflowRevisionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListWorkflowRevisionsResponse() {
workflows_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListWorkflowRevisionsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.workflows.v1.WorkflowsProto
.internal_static_google_cloud_workflows_v1_ListWorkflowRevisionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.workflows.v1.WorkflowsProto
.internal_static_google_cloud_workflows_v1_ListWorkflowRevisionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.class,
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.Builder.class);
}
public static final int WORKFLOWS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.workflows.v1.Workflow> workflows_;
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.workflows.v1.Workflow> getWorkflowsList() {
return workflows_;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.workflows.v1.WorkflowOrBuilder>
getWorkflowsOrBuilderList() {
return workflows_;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
@java.lang.Override
public int getWorkflowsCount() {
return workflows_.size();
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
@java.lang.Override
public com.google.cloud.workflows.v1.Workflow getWorkflows(int index) {
return workflows_.get(index);
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
@java.lang.Override
public com.google.cloud.workflows.v1.WorkflowOrBuilder getWorkflowsOrBuilder(int index) {
return workflows_.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 < workflows_.size(); i++) {
output.writeMessage(1, workflows_.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 < workflows_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, workflows_.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.workflows.v1.ListWorkflowRevisionsResponse)) {
return super.equals(obj);
}
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse other =
(com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse) obj;
if (!getWorkflowsList().equals(other.getWorkflowsList())) 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 (getWorkflowsCount() > 0) {
hash = (37 * hash) + WORKFLOWS_FIELD_NUMBER;
hash = (53 * hash) + getWorkflowsList().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.workflows.v1.ListWorkflowRevisionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse 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.workflows.v1.ListWorkflowRevisionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse 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.workflows.v1.ListWorkflowRevisionsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse 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.workflows.v1.ListWorkflowRevisionsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse 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.workflows.v1.ListWorkflowRevisionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse 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.workflows.v1.ListWorkflowRevisionsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response for the
* [ListWorkflowRevisions][google.cloud.workflows.v1.Workflows.ListWorkflowRevisions]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.workflows.v1.ListWorkflowRevisionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.workflows.v1.ListWorkflowRevisionsResponse)
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.workflows.v1.WorkflowsProto
.internal_static_google_cloud_workflows_v1_ListWorkflowRevisionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.workflows.v1.WorkflowsProto
.internal_static_google_cloud_workflows_v1_ListWorkflowRevisionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.class,
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.Builder.class);
}
// Construct using com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (workflowsBuilder_ == null) {
workflows_ = java.util.Collections.emptyList();
} else {
workflows_ = null;
workflowsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.workflows.v1.WorkflowsProto
.internal_static_google_cloud_workflows_v1_ListWorkflowRevisionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse getDefaultInstanceForType() {
return com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse build() {
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse buildPartial() {
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse result =
new com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse result) {
if (workflowsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
workflows_ = java.util.Collections.unmodifiableList(workflows_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.workflows_ = workflows_;
} else {
result.workflows_ = workflowsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse 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.workflows.v1.ListWorkflowRevisionsResponse) {
return mergeFrom((com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse other) {
if (other == com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse.getDefaultInstance())
return this;
if (workflowsBuilder_ == null) {
if (!other.workflows_.isEmpty()) {
if (workflows_.isEmpty()) {
workflows_ = other.workflows_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureWorkflowsIsMutable();
workflows_.addAll(other.workflows_);
}
onChanged();
}
} else {
if (!other.workflows_.isEmpty()) {
if (workflowsBuilder_.isEmpty()) {
workflowsBuilder_.dispose();
workflowsBuilder_ = null;
workflows_ = other.workflows_;
bitField0_ = (bitField0_ & ~0x00000001);
workflowsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getWorkflowsFieldBuilder()
: null;
} else {
workflowsBuilder_.addAllMessages(other.workflows_);
}
}
}
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.workflows.v1.Workflow m =
input.readMessage(
com.google.cloud.workflows.v1.Workflow.parser(), extensionRegistry);
if (workflowsBuilder_ == null) {
ensureWorkflowsIsMutable();
workflows_.add(m);
} else {
workflowsBuilder_.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.workflows.v1.Workflow> workflows_ =
java.util.Collections.emptyList();
private void ensureWorkflowsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
workflows_ = new java.util.ArrayList<com.google.cloud.workflows.v1.Workflow>(workflows_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.workflows.v1.Workflow,
com.google.cloud.workflows.v1.Workflow.Builder,
com.google.cloud.workflows.v1.WorkflowOrBuilder>
workflowsBuilder_;
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public java.util.List<com.google.cloud.workflows.v1.Workflow> getWorkflowsList() {
if (workflowsBuilder_ == null) {
return java.util.Collections.unmodifiableList(workflows_);
} else {
return workflowsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public int getWorkflowsCount() {
if (workflowsBuilder_ == null) {
return workflows_.size();
} else {
return workflowsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public com.google.cloud.workflows.v1.Workflow getWorkflows(int index) {
if (workflowsBuilder_ == null) {
return workflows_.get(index);
} else {
return workflowsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder setWorkflows(int index, com.google.cloud.workflows.v1.Workflow value) {
if (workflowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWorkflowsIsMutable();
workflows_.set(index, value);
onChanged();
} else {
workflowsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder setWorkflows(
int index, com.google.cloud.workflows.v1.Workflow.Builder builderForValue) {
if (workflowsBuilder_ == null) {
ensureWorkflowsIsMutable();
workflows_.set(index, builderForValue.build());
onChanged();
} else {
workflowsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder addWorkflows(com.google.cloud.workflows.v1.Workflow value) {
if (workflowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWorkflowsIsMutable();
workflows_.add(value);
onChanged();
} else {
workflowsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder addWorkflows(int index, com.google.cloud.workflows.v1.Workflow value) {
if (workflowsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWorkflowsIsMutable();
workflows_.add(index, value);
onChanged();
} else {
workflowsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder addWorkflows(com.google.cloud.workflows.v1.Workflow.Builder builderForValue) {
if (workflowsBuilder_ == null) {
ensureWorkflowsIsMutable();
workflows_.add(builderForValue.build());
onChanged();
} else {
workflowsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder addWorkflows(
int index, com.google.cloud.workflows.v1.Workflow.Builder builderForValue) {
if (workflowsBuilder_ == null) {
ensureWorkflowsIsMutable();
workflows_.add(index, builderForValue.build());
onChanged();
} else {
workflowsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder addAllWorkflows(
java.lang.Iterable<? extends com.google.cloud.workflows.v1.Workflow> values) {
if (workflowsBuilder_ == null) {
ensureWorkflowsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, workflows_);
onChanged();
} else {
workflowsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder clearWorkflows() {
if (workflowsBuilder_ == null) {
workflows_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
workflowsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public Builder removeWorkflows(int index) {
if (workflowsBuilder_ == null) {
ensureWorkflowsIsMutable();
workflows_.remove(index);
onChanged();
} else {
workflowsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public com.google.cloud.workflows.v1.Workflow.Builder getWorkflowsBuilder(int index) {
return getWorkflowsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public com.google.cloud.workflows.v1.WorkflowOrBuilder getWorkflowsOrBuilder(int index) {
if (workflowsBuilder_ == null) {
return workflows_.get(index);
} else {
return workflowsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public java.util.List<? extends com.google.cloud.workflows.v1.WorkflowOrBuilder>
getWorkflowsOrBuilderList() {
if (workflowsBuilder_ != null) {
return workflowsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(workflows_);
}
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public com.google.cloud.workflows.v1.Workflow.Builder addWorkflowsBuilder() {
return getWorkflowsFieldBuilder()
.addBuilder(com.google.cloud.workflows.v1.Workflow.getDefaultInstance());
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public com.google.cloud.workflows.v1.Workflow.Builder addWorkflowsBuilder(int index) {
return getWorkflowsFieldBuilder()
.addBuilder(index, com.google.cloud.workflows.v1.Workflow.getDefaultInstance());
}
/**
*
*
* <pre>
* The revisions of the workflow, ordered in reverse chronological order.
* </pre>
*
* <code>repeated .google.cloud.workflows.v1.Workflow workflows = 1;</code>
*/
public java.util.List<com.google.cloud.workflows.v1.Workflow.Builder>
getWorkflowsBuilderList() {
return getWorkflowsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.workflows.v1.Workflow,
com.google.cloud.workflows.v1.Workflow.Builder,
com.google.cloud.workflows.v1.WorkflowOrBuilder>
getWorkflowsFieldBuilder() {
if (workflowsBuilder_ == null) {
workflowsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.workflows.v1.Workflow,
com.google.cloud.workflows.v1.Workflow.Builder,
com.google.cloud.workflows.v1.WorkflowOrBuilder>(
workflows_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
workflows_ = null;
}
return workflowsBuilder_;
}
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.workflows.v1.ListWorkflowRevisionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.workflows.v1.ListWorkflowRevisionsResponse)
private static final com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse();
}
public static com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListWorkflowRevisionsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListWorkflowRevisionsResponse>() {
@java.lang.Override
public ListWorkflowRevisionsResponse 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<ListWorkflowRevisionsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListWorkflowRevisionsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.workflows.v1.ListWorkflowRevisionsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,680 | java-recommender/google-cloud-recommender/src/main/java/com/google/cloud/recommender/v1/stub/RecommenderStubSettings.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.recommender.v1.stub;
import static com.google.cloud.recommender.v1.RecommenderClient.ListInsightsPagedResponse;
import static com.google.cloud.recommender.v1.RecommenderClient.ListRecommendationsPagedResponse;
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.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
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.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.recommender.v1.GetInsightRequest;
import com.google.cloud.recommender.v1.GetInsightTypeConfigRequest;
import com.google.cloud.recommender.v1.GetRecommendationRequest;
import com.google.cloud.recommender.v1.GetRecommenderConfigRequest;
import com.google.cloud.recommender.v1.Insight;
import com.google.cloud.recommender.v1.InsightTypeConfig;
import com.google.cloud.recommender.v1.ListInsightsRequest;
import com.google.cloud.recommender.v1.ListInsightsResponse;
import com.google.cloud.recommender.v1.ListRecommendationsRequest;
import com.google.cloud.recommender.v1.ListRecommendationsResponse;
import com.google.cloud.recommender.v1.MarkInsightAcceptedRequest;
import com.google.cloud.recommender.v1.MarkRecommendationClaimedRequest;
import com.google.cloud.recommender.v1.MarkRecommendationDismissedRequest;
import com.google.cloud.recommender.v1.MarkRecommendationFailedRequest;
import com.google.cloud.recommender.v1.MarkRecommendationSucceededRequest;
import com.google.cloud.recommender.v1.Recommendation;
import com.google.cloud.recommender.v1.RecommenderConfig;
import com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest;
import com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest;
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 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 RecommenderStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (recommender.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 getInsight:
*
* <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
* RecommenderStubSettings.Builder recommenderSettingsBuilder =
* RecommenderStubSettings.newBuilder();
* recommenderSettingsBuilder
* .getInsightSettings()
* .setRetrySettings(
* recommenderSettingsBuilder
* .getInsightSettings()
* .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());
* RecommenderStubSettings recommenderSettings = recommenderSettingsBuilder.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.
*/
@Generated("by gapic-generator-java")
public class RecommenderStubSettings extends StubSettings<RecommenderStubSettings> {
/** 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").build();
private final PagedCallSettings<
ListInsightsRequest, ListInsightsResponse, ListInsightsPagedResponse>
listInsightsSettings;
private final UnaryCallSettings<GetInsightRequest, Insight> getInsightSettings;
private final UnaryCallSettings<MarkInsightAcceptedRequest, Insight> markInsightAcceptedSettings;
private final PagedCallSettings<
ListRecommendationsRequest, ListRecommendationsResponse, ListRecommendationsPagedResponse>
listRecommendationsSettings;
private final UnaryCallSettings<GetRecommendationRequest, Recommendation>
getRecommendationSettings;
private final UnaryCallSettings<MarkRecommendationDismissedRequest, Recommendation>
markRecommendationDismissedSettings;
private final UnaryCallSettings<MarkRecommendationClaimedRequest, Recommendation>
markRecommendationClaimedSettings;
private final UnaryCallSettings<MarkRecommendationSucceededRequest, Recommendation>
markRecommendationSucceededSettings;
private final UnaryCallSettings<MarkRecommendationFailedRequest, Recommendation>
markRecommendationFailedSettings;
private final UnaryCallSettings<GetRecommenderConfigRequest, RecommenderConfig>
getRecommenderConfigSettings;
private final UnaryCallSettings<UpdateRecommenderConfigRequest, RecommenderConfig>
updateRecommenderConfigSettings;
private final UnaryCallSettings<GetInsightTypeConfigRequest, InsightTypeConfig>
getInsightTypeConfigSettings;
private final UnaryCallSettings<UpdateInsightTypeConfigRequest, InsightTypeConfig>
updateInsightTypeConfigSettings;
private static final PagedListDescriptor<ListInsightsRequest, ListInsightsResponse, Insight>
LIST_INSIGHTS_PAGE_STR_DESC =
new PagedListDescriptor<ListInsightsRequest, ListInsightsResponse, Insight>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListInsightsRequest injectToken(ListInsightsRequest payload, String token) {
return ListInsightsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListInsightsRequest injectPageSize(ListInsightsRequest payload, int pageSize) {
return ListInsightsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListInsightsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListInsightsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Insight> extractResources(ListInsightsResponse payload) {
return payload.getInsightsList();
}
};
private static final PagedListDescriptor<
ListRecommendationsRequest, ListRecommendationsResponse, Recommendation>
LIST_RECOMMENDATIONS_PAGE_STR_DESC =
new PagedListDescriptor<
ListRecommendationsRequest, ListRecommendationsResponse, Recommendation>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListRecommendationsRequest injectToken(
ListRecommendationsRequest payload, String token) {
return ListRecommendationsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListRecommendationsRequest injectPageSize(
ListRecommendationsRequest payload, int pageSize) {
return ListRecommendationsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListRecommendationsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListRecommendationsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Recommendation> extractResources(ListRecommendationsResponse payload) {
return payload.getRecommendationsList();
}
};
private static final PagedListResponseFactory<
ListInsightsRequest, ListInsightsResponse, ListInsightsPagedResponse>
LIST_INSIGHTS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListInsightsRequest, ListInsightsResponse, ListInsightsPagedResponse>() {
@Override
public ApiFuture<ListInsightsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListInsightsRequest, ListInsightsResponse> callable,
ListInsightsRequest request,
ApiCallContext context,
ApiFuture<ListInsightsResponse> futureResponse) {
PageContext<ListInsightsRequest, ListInsightsResponse, Insight> pageContext =
PageContext.create(callable, LIST_INSIGHTS_PAGE_STR_DESC, request, context);
return ListInsightsPagedResponse.createAsync(pageContext, futureResponse);
}
};
private static final PagedListResponseFactory<
ListRecommendationsRequest, ListRecommendationsResponse, ListRecommendationsPagedResponse>
LIST_RECOMMENDATIONS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListRecommendationsRequest,
ListRecommendationsResponse,
ListRecommendationsPagedResponse>() {
@Override
public ApiFuture<ListRecommendationsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListRecommendationsRequest, ListRecommendationsResponse> callable,
ListRecommendationsRequest request,
ApiCallContext context,
ApiFuture<ListRecommendationsResponse> futureResponse) {
PageContext<ListRecommendationsRequest, ListRecommendationsResponse, Recommendation>
pageContext =
PageContext.create(
callable, LIST_RECOMMENDATIONS_PAGE_STR_DESC, request, context);
return ListRecommendationsPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to listInsights. */
public PagedCallSettings<ListInsightsRequest, ListInsightsResponse, ListInsightsPagedResponse>
listInsightsSettings() {
return listInsightsSettings;
}
/** Returns the object with the settings used for calls to getInsight. */
public UnaryCallSettings<GetInsightRequest, Insight> getInsightSettings() {
return getInsightSettings;
}
/** Returns the object with the settings used for calls to markInsightAccepted. */
public UnaryCallSettings<MarkInsightAcceptedRequest, Insight> markInsightAcceptedSettings() {
return markInsightAcceptedSettings;
}
/** Returns the object with the settings used for calls to listRecommendations. */
public PagedCallSettings<
ListRecommendationsRequest, ListRecommendationsResponse, ListRecommendationsPagedResponse>
listRecommendationsSettings() {
return listRecommendationsSettings;
}
/** Returns the object with the settings used for calls to getRecommendation. */
public UnaryCallSettings<GetRecommendationRequest, Recommendation> getRecommendationSettings() {
return getRecommendationSettings;
}
/** Returns the object with the settings used for calls to markRecommendationDismissed. */
public UnaryCallSettings<MarkRecommendationDismissedRequest, Recommendation>
markRecommendationDismissedSettings() {
return markRecommendationDismissedSettings;
}
/** Returns the object with the settings used for calls to markRecommendationClaimed. */
public UnaryCallSettings<MarkRecommendationClaimedRequest, Recommendation>
markRecommendationClaimedSettings() {
return markRecommendationClaimedSettings;
}
/** Returns the object with the settings used for calls to markRecommendationSucceeded. */
public UnaryCallSettings<MarkRecommendationSucceededRequest, Recommendation>
markRecommendationSucceededSettings() {
return markRecommendationSucceededSettings;
}
/** Returns the object with the settings used for calls to markRecommendationFailed. */
public UnaryCallSettings<MarkRecommendationFailedRequest, Recommendation>
markRecommendationFailedSettings() {
return markRecommendationFailedSettings;
}
/** Returns the object with the settings used for calls to getRecommenderConfig. */
public UnaryCallSettings<GetRecommenderConfigRequest, RecommenderConfig>
getRecommenderConfigSettings() {
return getRecommenderConfigSettings;
}
/** Returns the object with the settings used for calls to updateRecommenderConfig. */
public UnaryCallSettings<UpdateRecommenderConfigRequest, RecommenderConfig>
updateRecommenderConfigSettings() {
return updateRecommenderConfigSettings;
}
/** Returns the object with the settings used for calls to getInsightTypeConfig. */
public UnaryCallSettings<GetInsightTypeConfigRequest, InsightTypeConfig>
getInsightTypeConfigSettings() {
return getInsightTypeConfigSettings;
}
/** Returns the object with the settings used for calls to updateInsightTypeConfig. */
public UnaryCallSettings<UpdateInsightTypeConfigRequest, InsightTypeConfig>
updateInsightTypeConfigSettings() {
return updateInsightTypeConfigSettings;
}
public RecommenderStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcRecommenderStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonRecommenderStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "recommender";
}
/** 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 "recommender.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "recommender.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(RecommenderStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(RecommenderStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return RecommenderStubSettings.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 RecommenderStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
listInsightsSettings = settingsBuilder.listInsightsSettings().build();
getInsightSettings = settingsBuilder.getInsightSettings().build();
markInsightAcceptedSettings = settingsBuilder.markInsightAcceptedSettings().build();
listRecommendationsSettings = settingsBuilder.listRecommendationsSettings().build();
getRecommendationSettings = settingsBuilder.getRecommendationSettings().build();
markRecommendationDismissedSettings =
settingsBuilder.markRecommendationDismissedSettings().build();
markRecommendationClaimedSettings = settingsBuilder.markRecommendationClaimedSettings().build();
markRecommendationSucceededSettings =
settingsBuilder.markRecommendationSucceededSettings().build();
markRecommendationFailedSettings = settingsBuilder.markRecommendationFailedSettings().build();
getRecommenderConfigSettings = settingsBuilder.getRecommenderConfigSettings().build();
updateRecommenderConfigSettings = settingsBuilder.updateRecommenderConfigSettings().build();
getInsightTypeConfigSettings = settingsBuilder.getInsightTypeConfigSettings().build();
updateInsightTypeConfigSettings = settingsBuilder.updateInsightTypeConfigSettings().build();
}
/** Builder for RecommenderStubSettings. */
public static class Builder extends StubSettings.Builder<RecommenderStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final PagedCallSettings.Builder<
ListInsightsRequest, ListInsightsResponse, ListInsightsPagedResponse>
listInsightsSettings;
private final UnaryCallSettings.Builder<GetInsightRequest, Insight> getInsightSettings;
private final UnaryCallSettings.Builder<MarkInsightAcceptedRequest, Insight>
markInsightAcceptedSettings;
private final PagedCallSettings.Builder<
ListRecommendationsRequest,
ListRecommendationsResponse,
ListRecommendationsPagedResponse>
listRecommendationsSettings;
private final UnaryCallSettings.Builder<GetRecommendationRequest, Recommendation>
getRecommendationSettings;
private final UnaryCallSettings.Builder<MarkRecommendationDismissedRequest, Recommendation>
markRecommendationDismissedSettings;
private final UnaryCallSettings.Builder<MarkRecommendationClaimedRequest, Recommendation>
markRecommendationClaimedSettings;
private final UnaryCallSettings.Builder<MarkRecommendationSucceededRequest, Recommendation>
markRecommendationSucceededSettings;
private final UnaryCallSettings.Builder<MarkRecommendationFailedRequest, Recommendation>
markRecommendationFailedSettings;
private final UnaryCallSettings.Builder<GetRecommenderConfigRequest, RecommenderConfig>
getRecommenderConfigSettings;
private final UnaryCallSettings.Builder<UpdateRecommenderConfigRequest, RecommenderConfig>
updateRecommenderConfigSettings;
private final UnaryCallSettings.Builder<GetInsightTypeConfigRequest, InsightTypeConfig>
getInsightTypeConfigSettings;
private final UnaryCallSettings.Builder<UpdateInsightTypeConfigRequest, InsightTypeConfig>
updateInsightTypeConfigSettings;
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.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
definitions.put(
"no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
definitions.put("no_retry_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(60000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("retry_policy_0_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("no_retry_1_params", settings);
settings = RetrySettings.newBuilder().setRpcTimeoutMultiplier(1.0).build();
definitions.put("no_retry_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
listInsightsSettings = PagedCallSettings.newBuilder(LIST_INSIGHTS_PAGE_STR_FACT);
getInsightSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
markInsightAcceptedSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listRecommendationsSettings =
PagedCallSettings.newBuilder(LIST_RECOMMENDATIONS_PAGE_STR_FACT);
getRecommendationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
markRecommendationDismissedSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
markRecommendationClaimedSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
markRecommendationSucceededSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
markRecommendationFailedSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
getRecommenderConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateRecommenderConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
getInsightTypeConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateInsightTypeConfigSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listInsightsSettings,
getInsightSettings,
markInsightAcceptedSettings,
listRecommendationsSettings,
getRecommendationSettings,
markRecommendationDismissedSettings,
markRecommendationClaimedSettings,
markRecommendationSucceededSettings,
markRecommendationFailedSettings,
getRecommenderConfigSettings,
updateRecommenderConfigSettings,
getInsightTypeConfigSettings,
updateInsightTypeConfigSettings);
initDefaults(this);
}
protected Builder(RecommenderStubSettings settings) {
super(settings);
listInsightsSettings = settings.listInsightsSettings.toBuilder();
getInsightSettings = settings.getInsightSettings.toBuilder();
markInsightAcceptedSettings = settings.markInsightAcceptedSettings.toBuilder();
listRecommendationsSettings = settings.listRecommendationsSettings.toBuilder();
getRecommendationSettings = settings.getRecommendationSettings.toBuilder();
markRecommendationDismissedSettings =
settings.markRecommendationDismissedSettings.toBuilder();
markRecommendationClaimedSettings = settings.markRecommendationClaimedSettings.toBuilder();
markRecommendationSucceededSettings =
settings.markRecommendationSucceededSettings.toBuilder();
markRecommendationFailedSettings = settings.markRecommendationFailedSettings.toBuilder();
getRecommenderConfigSettings = settings.getRecommenderConfigSettings.toBuilder();
updateRecommenderConfigSettings = settings.updateRecommenderConfigSettings.toBuilder();
getInsightTypeConfigSettings = settings.getInsightTypeConfigSettings.toBuilder();
updateInsightTypeConfigSettings = settings.updateInsightTypeConfigSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listInsightsSettings,
getInsightSettings,
markInsightAcceptedSettings,
listRecommendationsSettings,
getRecommendationSettings,
markRecommendationDismissedSettings,
markRecommendationClaimedSettings,
markRecommendationSucceededSettings,
markRecommendationFailedSettings,
getRecommenderConfigSettings,
updateRecommenderConfigSettings,
getInsightTypeConfigSettings,
updateInsightTypeConfigSettings);
}
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
.listInsightsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.getInsightSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.markInsightAcceptedSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.listRecommendationsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.getRecommendationSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.markRecommendationDismissedSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.markRecommendationClaimedSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.markRecommendationSucceededSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.markRecommendationFailedSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.getRecommenderConfigSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.updateRecommenderConfigSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.getInsightTypeConfigSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.updateInsightTypeConfigSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
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 listInsights. */
public PagedCallSettings.Builder<
ListInsightsRequest, ListInsightsResponse, ListInsightsPagedResponse>
listInsightsSettings() {
return listInsightsSettings;
}
/** Returns the builder for the settings used for calls to getInsight. */
public UnaryCallSettings.Builder<GetInsightRequest, Insight> getInsightSettings() {
return getInsightSettings;
}
/** Returns the builder for the settings used for calls to markInsightAccepted. */
public UnaryCallSettings.Builder<MarkInsightAcceptedRequest, Insight>
markInsightAcceptedSettings() {
return markInsightAcceptedSettings;
}
/** Returns the builder for the settings used for calls to listRecommendations. */
public PagedCallSettings.Builder<
ListRecommendationsRequest,
ListRecommendationsResponse,
ListRecommendationsPagedResponse>
listRecommendationsSettings() {
return listRecommendationsSettings;
}
/** Returns the builder for the settings used for calls to getRecommendation. */
public UnaryCallSettings.Builder<GetRecommendationRequest, Recommendation>
getRecommendationSettings() {
return getRecommendationSettings;
}
/** Returns the builder for the settings used for calls to markRecommendationDismissed. */
public UnaryCallSettings.Builder<MarkRecommendationDismissedRequest, Recommendation>
markRecommendationDismissedSettings() {
return markRecommendationDismissedSettings;
}
/** Returns the builder for the settings used for calls to markRecommendationClaimed. */
public UnaryCallSettings.Builder<MarkRecommendationClaimedRequest, Recommendation>
markRecommendationClaimedSettings() {
return markRecommendationClaimedSettings;
}
/** Returns the builder for the settings used for calls to markRecommendationSucceeded. */
public UnaryCallSettings.Builder<MarkRecommendationSucceededRequest, Recommendation>
markRecommendationSucceededSettings() {
return markRecommendationSucceededSettings;
}
/** Returns the builder for the settings used for calls to markRecommendationFailed. */
public UnaryCallSettings.Builder<MarkRecommendationFailedRequest, Recommendation>
markRecommendationFailedSettings() {
return markRecommendationFailedSettings;
}
/** Returns the builder for the settings used for calls to getRecommenderConfig. */
public UnaryCallSettings.Builder<GetRecommenderConfigRequest, RecommenderConfig>
getRecommenderConfigSettings() {
return getRecommenderConfigSettings;
}
/** Returns the builder for the settings used for calls to updateRecommenderConfig. */
public UnaryCallSettings.Builder<UpdateRecommenderConfigRequest, RecommenderConfig>
updateRecommenderConfigSettings() {
return updateRecommenderConfigSettings;
}
/** Returns the builder for the settings used for calls to getInsightTypeConfig. */
public UnaryCallSettings.Builder<GetInsightTypeConfigRequest, InsightTypeConfig>
getInsightTypeConfigSettings() {
return getInsightTypeConfigSettings;
}
/** Returns the builder for the settings used for calls to updateInsightTypeConfig. */
public UnaryCallSettings.Builder<UpdateInsightTypeConfigRequest, InsightTypeConfig>
updateInsightTypeConfigSettings() {
return updateInsightTypeConfigSettings;
}
@Override
public RecommenderStubSettings build() throws IOException {
return new RecommenderStubSettings(this);
}
}
}
|
apache/hop | 37,671 | plugins/tech/neo4j/src/main/java/org/apache/hop/neo4j/shared/NeoConnectionEditor.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.neo4j.shared;
import org.apache.hop.core.Const;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.ui.core.PropsUi;
import org.apache.hop.ui.core.dialog.ErrorDialog;
import org.apache.hop.ui.core.dialog.MessageBox;
import org.apache.hop.ui.core.gui.GuiResource;
import org.apache.hop.ui.core.metadata.MetadataEditor;
import org.apache.hop.ui.core.metadata.MetadataManager;
import org.apache.hop.ui.core.widget.CheckBoxVar;
import org.apache.hop.ui.core.widget.ColumnInfo;
import org.apache.hop.ui.core.widget.PasswordTextVar;
import org.apache.hop.ui.core.widget.TableView;
import org.apache.hop.ui.core.widget.TextVar;
import org.apache.hop.ui.hopgui.HopGui;
import org.apache.hop.ui.hopgui.perspective.metadata.MetadataPerspective;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
/** Dialog that allows you to edit the settings of a Neo4j connection */
public class NeoConnectionEditor extends MetadataEditor<NeoConnection> {
private static final Class<?> PKG = NeoConnectionEditor.class;
private CTabFolder wTabFolder;
// Connection properties
//
private Text wName;
private Label wlAutomatic;
private CheckBoxVar wAutomatic;
private TextVar wProtocol;
private Label wlServer;
private TextVar wServer;
private Label wlDatabaseName;
private TextVar wDatabaseName;
private Label wlDatabasePort;
private TextVar wDatabasePort;
private TextVar wUsername;
private TextVar wPassword;
// Advanced
//
private Label wlVersion4;
private CheckBoxVar wVersion4;
private TextVar wBrowserPort;
private Label wlPolicy;
private TextVar wPolicy;
private Label wlRouting;
private CheckBoxVar wRouting;
private Label wlEncryption;
private CheckBoxVar wEncryption;
private Label wlTrustAllCertificates;
private CheckBoxVar wTrustAllCertificates;
private TextVar wConnectionLivenessCheckTimeout;
private TextVar wMaxConnectionLifetime;
private TextVar wMaxConnectionPoolSize;
private TextVar wConnectionAcquisitionTimeout;
private TextVar wConnectionTimeout;
private TextVar wMaxTransactionRetryTime;
private TableView wUrls;
public NeoConnectionEditor(
HopGui hopGui, MetadataManager<NeoConnection> manager, NeoConnection neoConnection) {
super(hopGui, manager, neoConnection);
}
@Override
public void createControl(Composite composite) {
PropsUi props = PropsUi.getInstance();
int middle = props.getMiddlePct();
int margin = PropsUi.getMargin() + 2;
IVariables variables = getHopGui().getVariables();
// The name
Label wlName = new Label(composite, SWT.RIGHT);
PropsUi.setLook(wlName);
wlName.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Name.Label"));
FormData fdlName = new FormData();
fdlName.top = new FormAttachment(0, margin);
fdlName.left = new FormAttachment(0, 0); // First one in the left top corner
fdlName.right = new FormAttachment(middle, -margin);
wlName.setLayoutData(fdlName);
wName = new Text(composite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wName);
FormData fdName = new FormData();
fdName.top = new FormAttachment(wlName, 0, SWT.CENTER);
fdName.left = new FormAttachment(middle, 0); // To the right of the label
fdName.right = new FormAttachment(95, 0);
wName.setLayoutData(fdName);
wTabFolder = new CTabFolder(composite, SWT.BORDER);
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.top = new FormAttachment(wName, 2 * margin);
fdTabFolder.bottom = new FormAttachment(100, -2 * margin);
wTabFolder.setLayoutData(fdTabFolder);
addBasicTab(props, variables, middle, margin);
addProtocolTab(props, variables, middle, margin);
addAdvancedTab(props, variables, middle, margin);
addUrlsTab(props, variables);
// Always select the basic tab
wTabFolder.setSelection(0);
setWidgetsContent();
enableFields();
clearChanged();
// Add modify listeners to all controls.
// This will inform the Metadata perspective in the Hop GUI that this object was modified and
// needs to be saved.
//
Control[] controls = {
wName,
wAutomatic,
wServer,
wDatabaseName,
wVersion4,
wDatabasePort,
wBrowserPort,
wPolicy,
wUsername,
wPassword,
wRouting,
wEncryption,
wTrustAllCertificates,
wConnectionLivenessCheckTimeout,
wMaxConnectionLifetime,
wMaxConnectionPoolSize,
wConnectionAcquisitionTimeout,
wConnectionTimeout,
wMaxTransactionRetryTime,
wProtocol
};
for (Control control : controls) {
control.addListener(SWT.Modify, e -> setChanged());
control.addListener(SWT.Selection, e -> setChanged());
}
}
private void addBasicTab(PropsUi props, IVariables variables, int middle, int margin) {
CTabItem wModelTab = new CTabItem(wTabFolder, SWT.NONE);
wModelTab.setFont(GuiResource.getInstance().getFontDefault());
wModelTab.setText("Basic ");
ScrolledComposite wBasicSComp = new ScrolledComposite(wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL);
wBasicSComp.setLayout(new FillLayout());
Composite wBasicComp = new Composite(wBasicSComp, SWT.NONE);
PropsUi.setLook(wBasicComp);
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 3;
formLayout.marginHeight = 3;
wBasicComp.setLayout(formLayout);
// Automatic?
wlAutomatic = new Label(wBasicComp, SWT.RIGHT);
wlAutomatic.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Automatic.Label"));
wlAutomatic.setToolTipText(
BaseMessages.getString(PKG, "NeoConnectionEditor.Automatic.Tooltip"));
PropsUi.setLook(wlAutomatic);
FormData fdlAutomatic = new FormData();
fdlAutomatic.top = new FormAttachment(0, margin);
fdlAutomatic.left = new FormAttachment(0, 0);
fdlAutomatic.right = new FormAttachment(middle, -margin);
wlAutomatic.setLayoutData(fdlAutomatic);
wAutomatic = new CheckBoxVar(variables, wBasicComp, SWT.CHECK);
wAutomatic.setToolTipText(BaseMessages.getString(PKG, "NeoConnectionEditor.Automatic.Tooltip"));
PropsUi.setLook(wAutomatic);
FormData fdAutomatic = new FormData();
fdAutomatic.top = new FormAttachment(wlAutomatic, 0, SWT.CENTER);
fdAutomatic.left = new FormAttachment(middle, 0);
fdAutomatic.right = new FormAttachment(95, 0);
wAutomatic.setLayoutData(fdAutomatic);
wAutomatic.addListener(SWT.Selection, e -> enableFields());
Control lastControl = wAutomatic;
// Protocol
Label wlProtocol = new Label(wBasicComp, SWT.RIGHT);
wlProtocol.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Protocol.Label"));
wlProtocol.setToolTipText(BaseMessages.getString(PKG, "NeoConnectionEditor.Protocol.Tooltip"));
PropsUi.setLook(wlProtocol);
FormData fdlProtocol = new FormData();
fdlProtocol.top = new FormAttachment(lastControl, margin);
fdlProtocol.left = new FormAttachment(0, 0);
fdlProtocol.right = new FormAttachment(middle, -margin);
wlProtocol.setLayoutData(fdlProtocol);
wProtocol = new TextVar(variables, wBasicComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wProtocol.setToolTipText(BaseMessages.getString(PKG, "NeoConnectionEditor.Protocol.Tooltip"));
PropsUi.setLook(wProtocol);
FormData fdProtocol = new FormData();
fdProtocol.top = new FormAttachment(wlProtocol, 0, SWT.CENTER);
fdProtocol.left = new FormAttachment(middle, 0);
fdProtocol.right = new FormAttachment(95, 0);
wProtocol.setLayoutData(fdProtocol);
lastControl = wProtocol;
// The server
wlServer = new Label(wBasicComp, SWT.RIGHT);
PropsUi.setLook(wlServer);
wlServer.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Server.Label"));
FormData fdlServer = new FormData();
fdlServer.top = new FormAttachment(lastControl, margin);
fdlServer.left = new FormAttachment(0, 0); // First one in the left top corner
fdlServer.right = new FormAttachment(middle, -margin);
wlServer.setLayoutData(fdlServer);
wServer = new TextVar(variables, wBasicComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wServer);
FormData fdServer = new FormData();
fdServer.top = new FormAttachment(wlServer, 0, SWT.CENTER);
fdServer.left = new FormAttachment(middle, 0); // To the right of the label
fdServer.right = new FormAttachment(95, 0);
wServer.setLayoutData(fdServer);
lastControl = wServer;
// The DatabaseName
wlDatabaseName = new Label(wBasicComp, SWT.RIGHT);
PropsUi.setLook(wlDatabaseName);
wlDatabaseName.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.DatabaseName.Label"));
FormData fdlDatabaseName = new FormData();
fdlDatabaseName.top = new FormAttachment(lastControl, margin);
fdlDatabaseName.left = new FormAttachment(0, 0); // First one in the left top corner
fdlDatabaseName.right = new FormAttachment(middle, -margin);
wlDatabaseName.setLayoutData(fdlDatabaseName);
wDatabaseName = new TextVar(variables, wBasicComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wDatabaseName);
FormData fdDatabaseName = new FormData();
fdDatabaseName.top = new FormAttachment(wlDatabaseName, 0, SWT.CENTER);
fdDatabaseName.left = new FormAttachment(middle, 0); // To the right of the label
fdDatabaseName.right = new FormAttachment(95, 0);
wDatabaseName.setLayoutData(fdDatabaseName);
lastControl = wDatabaseName;
// Database port?
wlDatabasePort = new Label(wBasicComp, SWT.RIGHT);
PropsUi.setLook(wlDatabasePort);
wlDatabasePort.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.DatabasePort.Label"));
FormData fdlDatabasePort = new FormData();
fdlDatabasePort.top = new FormAttachment(lastControl, margin);
fdlDatabasePort.left = new FormAttachment(0, 0); // First one in the left top corner
fdlDatabasePort.right = new FormAttachment(middle, -margin);
wlDatabasePort.setLayoutData(fdlDatabasePort);
wDatabasePort = new TextVar(variables, wBasicComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wDatabasePort);
FormData fdDatabasePort = new FormData();
fdDatabasePort.top = new FormAttachment(wlDatabasePort, 0, SWT.CENTER);
fdDatabasePort.left = new FormAttachment(middle, 0); // To the right of the label
fdDatabasePort.right = new FormAttachment(95, 0);
wDatabasePort.setLayoutData(fdDatabasePort);
lastControl = wDatabasePort;
// Username
Label wlUsername = new Label(wBasicComp, SWT.RIGHT);
wlUsername.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.UserName.Label"));
PropsUi.setLook(wlUsername);
FormData fdlUsername = new FormData();
fdlUsername.top = new FormAttachment(lastControl, margin);
fdlUsername.left = new FormAttachment(0, 0);
fdlUsername.right = new FormAttachment(middle, -margin);
wlUsername.setLayoutData(fdlUsername);
wUsername = new TextVar(variables, wBasicComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wUsername);
FormData fdUsername = new FormData();
fdUsername.top = new FormAttachment(wlUsername, 0, SWT.CENTER);
fdUsername.left = new FormAttachment(middle, 0);
fdUsername.right = new FormAttachment(95, 0);
wUsername.setLayoutData(fdUsername);
lastControl = wUsername;
// Password
Label wlPassword = new Label(wBasicComp, SWT.RIGHT);
wlPassword.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Password.Label"));
PropsUi.setLook(wlPassword);
FormData fdlPassword = new FormData();
fdlPassword.top = new FormAttachment(lastControl, margin);
fdlPassword.left = new FormAttachment(0, 0);
fdlPassword.right = new FormAttachment(middle, -margin);
wlPassword.setLayoutData(fdlPassword);
wPassword = new PasswordTextVar(variables, wBasicComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wPassword);
FormData fdPassword = new FormData();
fdPassword.top = new FormAttachment(wlPassword, 0, SWT.CENTER);
fdPassword.left = new FormAttachment(middle, 0);
fdPassword.right = new FormAttachment(95, 0);
wPassword.setLayoutData(fdPassword);
// End of the basic tab...
//
wBasicComp.pack();
Rectangle bounds = wBasicComp.getBounds();
wBasicSComp.setContent(wBasicComp);
wBasicSComp.setExpandHorizontal(true);
wBasicSComp.setExpandVertical(true);
wBasicSComp.setMinWidth(bounds.width);
wBasicSComp.setMinHeight(bounds.height);
wModelTab.setControl(wBasicSComp);
}
private void addProtocolTab(PropsUi props, IVariables variables, int middle, int margin) {
CTabItem wProtocolTab = new CTabItem(wTabFolder, SWT.NONE);
wProtocolTab.setFont(GuiResource.getInstance().getFontDefault());
wProtocolTab.setText("Protocol ");
ScrolledComposite wProtocolSComp =
new ScrolledComposite(wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL);
wProtocolSComp.setLayout(new FillLayout());
Composite wProtocolComp = new Composite(wProtocolSComp, SWT.NONE);
PropsUi.setLook(wProtocolComp);
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 3;
formLayout.marginHeight = 3;
wProtocolComp.setLayout(formLayout);
// Version4?
wlVersion4 = new Label(wProtocolComp, SWT.RIGHT);
wlVersion4.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Version4.Label"));
PropsUi.setLook(wlVersion4);
FormData fdlVersion4 = new FormData();
fdlVersion4.top = new FormAttachment(0, margin);
fdlVersion4.left = new FormAttachment(0, 0);
fdlVersion4.right = new FormAttachment(middle, -margin);
wlVersion4.setLayoutData(fdlVersion4);
wVersion4 = new CheckBoxVar(variables, wProtocolComp, SWT.CHECK);
PropsUi.setLook(wVersion4);
FormData fdVersion4 = new FormData();
fdVersion4.top = new FormAttachment(wlVersion4, 0, SWT.CENTER);
fdVersion4.left = new FormAttachment(middle, 0);
fdVersion4.right = new FormAttachment(95, 0);
wVersion4.setLayoutData(fdVersion4);
Control lastControl = wVersion4;
// Browser port?
Label wlBrowserPort = new Label(wProtocolComp, SWT.RIGHT);
PropsUi.setLook(wlBrowserPort);
wlBrowserPort.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.BrowserPort.Label"));
FormData fdlBrowserPort = new FormData();
fdlBrowserPort.top = new FormAttachment(lastControl, margin);
fdlBrowserPort.left = new FormAttachment(0, 0); // First one in the left top corner
fdlBrowserPort.right = new FormAttachment(middle, -margin);
wlBrowserPort.setLayoutData(fdlBrowserPort);
wBrowserPort = new TextVar(variables, wProtocolComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wBrowserPort);
FormData fdBrowserPort = new FormData();
fdBrowserPort.top = new FormAttachment(wlBrowserPort, 0, SWT.CENTER);
fdBrowserPort.left = new FormAttachment(middle, 0); // To the right of the label
fdBrowserPort.right = new FormAttachment(95, 0);
wBrowserPort.setLayoutData(fdBrowserPort);
lastControl = wBrowserPort;
// Routing
wlRouting = new Label(wProtocolComp, SWT.RIGHT);
wlRouting.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Routing.Label"));
PropsUi.setLook(wlRouting);
FormData fdlRouting = new FormData();
fdlRouting.top = new FormAttachment(lastControl, margin);
fdlRouting.left = new FormAttachment(0, 0);
fdlRouting.right = new FormAttachment(middle, -margin);
wlRouting.setLayoutData(fdlRouting);
wRouting = new CheckBoxVar(variables, wProtocolComp, SWT.CHECK);
PropsUi.setLook(wRouting);
FormData fdRouting = new FormData();
fdRouting.top = new FormAttachment(wlRouting, 0, SWT.CENTER);
fdRouting.left = new FormAttachment(middle, 0);
fdRouting.right = new FormAttachment(95, 0);
wRouting.setLayoutData(fdRouting);
wRouting.addListener(SWT.Selection, e -> enableFields());
lastControl = wRouting;
// Policy
wlPolicy = new Label(wProtocolComp, SWT.RIGHT);
wlPolicy.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Policy.Label"));
PropsUi.setLook(wlPolicy);
FormData fdlPolicy = new FormData();
fdlPolicy.top = new FormAttachment(lastControl, margin);
fdlPolicy.left = new FormAttachment(0, 0);
fdlPolicy.right = new FormAttachment(middle, -margin);
wlPolicy.setLayoutData(fdlPolicy);
wPolicy = new TextVar(variables, wProtocolComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wPolicy);
FormData fdPolicy = new FormData();
fdPolicy.top = new FormAttachment(wlPolicy, 0, SWT.CENTER);
fdPolicy.left = new FormAttachment(middle, 0);
fdPolicy.right = new FormAttachment(95, 0);
wPolicy.setLayoutData(fdPolicy);
lastControl = wPolicy;
// Encryption?
wlEncryption = new Label(wProtocolComp, SWT.RIGHT);
wlEncryption.setText(BaseMessages.getString(PKG, "NeoConnectionEditor.Encryption.Label"));
PropsUi.setLook(wlEncryption);
FormData fdlEncryption = new FormData();
fdlEncryption.top = new FormAttachment(lastControl, margin);
fdlEncryption.left = new FormAttachment(0, 0);
fdlEncryption.right = new FormAttachment(middle, -margin);
wlEncryption.setLayoutData(fdlEncryption);
wEncryption = new CheckBoxVar(variables, wProtocolComp, SWT.CHECK);
PropsUi.setLook(wEncryption);
FormData fdEncryption = new FormData();
fdEncryption.top = new FormAttachment(wlEncryption, 0, SWT.CENTER);
fdEncryption.left = new FormAttachment(middle, 0);
fdEncryption.right = new FormAttachment(95, 0);
wEncryption.setLayoutData(fdEncryption);
wEncryption.addListener(SWT.Selection, e -> enableFields());
lastControl = wEncryption;
// Trust Level?
wlTrustAllCertificates = new Label(wProtocolComp, SWT.RIGHT);
wlTrustAllCertificates.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.TrustAllCertificates.Label"));
PropsUi.setLook(wlTrustAllCertificates);
FormData fdlTrustAllCertificates = new FormData();
fdlTrustAllCertificates.top = new FormAttachment(lastControl, margin);
fdlTrustAllCertificates.left = new FormAttachment(0, 0);
fdlTrustAllCertificates.right = new FormAttachment(middle, -margin);
wlTrustAllCertificates.setLayoutData(fdlTrustAllCertificates);
wTrustAllCertificates = new CheckBoxVar(variables, wProtocolComp, SWT.CHECK);
PropsUi.setLook(wEncryption);
FormData fdTrustAllCertificates = new FormData();
fdTrustAllCertificates.top = new FormAttachment(wlTrustAllCertificates, 0, SWT.CENTER);
fdTrustAllCertificates.left = new FormAttachment(middle, 0);
fdTrustAllCertificates.right = new FormAttachment(95, 0);
wTrustAllCertificates.setLayoutData(fdTrustAllCertificates);
// End of the basic tab...
//
wProtocolComp.pack();
Rectangle bounds = wProtocolComp.getBounds();
wProtocolSComp.setContent(wProtocolComp);
wProtocolSComp.setExpandHorizontal(true);
wProtocolSComp.setExpandVertical(true);
wProtocolSComp.setMinWidth(bounds.width);
wProtocolSComp.setMinHeight(bounds.height);
wProtocolTab.setControl(wProtocolSComp);
}
private void addUrlsTab(PropsUi props, IVariables variables) {
CTabItem wUrlsTab = new CTabItem(wTabFolder, SWT.NONE);
wUrlsTab.setFont(GuiResource.getInstance().getFontDefault());
wUrlsTab.setText("Manual URLs");
ScrolledComposite wUrlsSComp = new ScrolledComposite(wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL);
wUrlsSComp.setLayout(new FillLayout());
Composite wUrlsComp = new Composite(wUrlsSComp, SWT.NONE);
PropsUi.setLook(wUrlsComp);
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 3;
formLayout.marginHeight = 3;
wUrlsComp.setLayout(formLayout);
// URLs
wUrls =
new TableView(
variables,
wUrlsComp,
SWT.NONE,
new ColumnInfo[] {
new ColumnInfo(
BaseMessages.getString(PKG, "NeoConnectionEditor.URLColumn.Label"),
ColumnInfo.COLUMN_TYPE_TEXT)
},
getMetadata().getManualUrls().size(),
e -> {
setChanged();
enableFields();
},
props);
FormData fdUrls = new FormData();
fdUrls.top = new FormAttachment(0, 0);
fdUrls.left = new FormAttachment(0, 0);
fdUrls.right = new FormAttachment(100, 0);
fdUrls.bottom = new FormAttachment(100, 0);
wUrls.setLayoutData(fdUrls);
// End of the basic tab...
//
wUrlsComp.pack();
Rectangle bounds = wUrlsComp.getBounds();
wUrlsSComp.setContent(wUrlsComp);
wUrlsSComp.setExpandHorizontal(true);
wUrlsSComp.setExpandVertical(true);
wUrlsSComp.setMinWidth(bounds.width);
wUrlsSComp.setMinHeight(bounds.height);
wUrlsTab.setControl(wUrlsSComp);
}
private void addAdvancedTab(PropsUi props, IVariables variables, int middle, int margin) {
CTabItem wAdvancedTab = new CTabItem(wTabFolder, SWT.NONE);
wAdvancedTab.setFont(GuiResource.getInstance().getFontDefault());
wAdvancedTab.setText("Advanced ");
ScrolledComposite wAdvancedSComp =
new ScrolledComposite(wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL);
wAdvancedSComp.setLayout(new FillLayout());
Composite wAdvancedComp = new Composite(wAdvancedSComp, SWT.NONE);
PropsUi.setLook(wAdvancedComp);
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 3;
formLayout.marginHeight = 3;
wAdvancedComp.setLayout(formLayout);
// ConnectionLivenessCheckTimeout
Label wlConnectionLivenessCheckTimeout = new Label(wAdvancedComp, SWT.RIGHT);
wlConnectionLivenessCheckTimeout.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.ConnectionLivenessCheckTimeout.Label"));
PropsUi.setLook(wlConnectionLivenessCheckTimeout);
FormData fdlConnectionLivenessCheckTimeout = new FormData();
fdlConnectionLivenessCheckTimeout.top = new FormAttachment(0, 0);
fdlConnectionLivenessCheckTimeout.left = new FormAttachment(0, 0);
fdlConnectionLivenessCheckTimeout.right = new FormAttachment(middle, -margin);
wlConnectionLivenessCheckTimeout.setLayoutData(fdlConnectionLivenessCheckTimeout);
wConnectionLivenessCheckTimeout =
new TextVar(variables, wAdvancedComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wConnectionLivenessCheckTimeout);
FormData fdConnectionLivenessCheckTimeout = new FormData();
fdConnectionLivenessCheckTimeout.top =
new FormAttachment(wlConnectionLivenessCheckTimeout, 0, SWT.CENTER);
fdConnectionLivenessCheckTimeout.left = new FormAttachment(middle, 0);
fdConnectionLivenessCheckTimeout.right = new FormAttachment(95, 0);
wConnectionLivenessCheckTimeout.setLayoutData(fdConnectionLivenessCheckTimeout);
Control lastGroupControl = wConnectionLivenessCheckTimeout;
// MaxConnectionLifetime
Label wlMaxConnectionLifetime = new Label(wAdvancedComp, SWT.RIGHT);
wlMaxConnectionLifetime.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.MaxConnectionLifetime.Label"));
PropsUi.setLook(wlMaxConnectionLifetime);
FormData fdlMaxConnectionLifetime = new FormData();
fdlMaxConnectionLifetime.top = new FormAttachment(lastGroupControl, margin);
fdlMaxConnectionLifetime.left = new FormAttachment(0, 0);
fdlMaxConnectionLifetime.right = new FormAttachment(middle, -margin);
wlMaxConnectionLifetime.setLayoutData(fdlMaxConnectionLifetime);
wMaxConnectionLifetime =
new TextVar(variables, wAdvancedComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wMaxConnectionLifetime);
FormData fdMaxConnectionLifetime = new FormData();
fdMaxConnectionLifetime.top = new FormAttachment(wlMaxConnectionLifetime, 0, SWT.CENTER);
fdMaxConnectionLifetime.left = new FormAttachment(middle, 0);
fdMaxConnectionLifetime.right = new FormAttachment(95, 0);
wMaxConnectionLifetime.setLayoutData(fdMaxConnectionLifetime);
lastGroupControl = wMaxConnectionLifetime;
// MaxConnectionPoolSize
Label wlMaxConnectionPoolSize = new Label(wAdvancedComp, SWT.RIGHT);
wlMaxConnectionPoolSize.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.MaxConnectionPoolSize.Label"));
PropsUi.setLook(wlMaxConnectionPoolSize);
FormData fdlMaxConnectionPoolSize = new FormData();
fdlMaxConnectionPoolSize.top = new FormAttachment(lastGroupControl, margin);
fdlMaxConnectionPoolSize.left = new FormAttachment(0, 0);
fdlMaxConnectionPoolSize.right = new FormAttachment(middle, -margin);
wlMaxConnectionPoolSize.setLayoutData(fdlMaxConnectionPoolSize);
wMaxConnectionPoolSize =
new TextVar(variables, wAdvancedComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wMaxConnectionPoolSize);
FormData fdMaxConnectionPoolSize = new FormData();
fdMaxConnectionPoolSize.top = new FormAttachment(wlMaxConnectionPoolSize, 0, SWT.CENTER);
fdMaxConnectionPoolSize.left = new FormAttachment(middle, 0);
fdMaxConnectionPoolSize.right = new FormAttachment(95, 0);
wMaxConnectionPoolSize.setLayoutData(fdMaxConnectionPoolSize);
lastGroupControl = wMaxConnectionPoolSize;
// ConnectionAcquisitionTimeout
Label wlConnectionAcquisitionTimeout = new Label(wAdvancedComp, SWT.RIGHT);
wlConnectionAcquisitionTimeout.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.ConnectionAcquisitionTimeout.Label"));
PropsUi.setLook(wlConnectionAcquisitionTimeout);
FormData fdlConnectionAcquisitionTimeout = new FormData();
fdlConnectionAcquisitionTimeout.top = new FormAttachment(lastGroupControl, margin);
fdlConnectionAcquisitionTimeout.left = new FormAttachment(0, 0);
fdlConnectionAcquisitionTimeout.right = new FormAttachment(middle, -margin);
wlConnectionAcquisitionTimeout.setLayoutData(fdlConnectionAcquisitionTimeout);
wConnectionAcquisitionTimeout =
new TextVar(variables, wAdvancedComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wConnectionAcquisitionTimeout);
FormData fdConnectionAcquisitionTimeout = new FormData();
fdConnectionAcquisitionTimeout.top =
new FormAttachment(wlConnectionAcquisitionTimeout, 0, SWT.CENTER);
fdConnectionAcquisitionTimeout.left = new FormAttachment(middle, 0);
fdConnectionAcquisitionTimeout.right = new FormAttachment(95, 0);
wConnectionAcquisitionTimeout.setLayoutData(fdConnectionAcquisitionTimeout);
lastGroupControl = wConnectionAcquisitionTimeout;
// ConnectionTimeout
Label wlConnectionTimeout = new Label(wAdvancedComp, SWT.RIGHT);
wlConnectionTimeout.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.ConnectionTimeout.Label"));
PropsUi.setLook(wlConnectionTimeout);
FormData fdlConnectionTimeout = new FormData();
fdlConnectionTimeout.top = new FormAttachment(lastGroupControl, margin);
fdlConnectionTimeout.left = new FormAttachment(0, 0);
fdlConnectionTimeout.right = new FormAttachment(middle, -margin);
wlConnectionTimeout.setLayoutData(fdlConnectionTimeout);
wConnectionTimeout = new TextVar(variables, wAdvancedComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wConnectionTimeout);
FormData fdConnectionTimeout = new FormData();
fdConnectionTimeout.top = new FormAttachment(wlConnectionTimeout, 0, SWT.CENTER);
fdConnectionTimeout.left = new FormAttachment(middle, 0);
fdConnectionTimeout.right = new FormAttachment(95, 0);
wConnectionTimeout.setLayoutData(fdConnectionTimeout);
lastGroupControl = wConnectionTimeout;
// MaxTransactionRetryTime
Label wlMaxTransactionRetryTime = new Label(wAdvancedComp, SWT.RIGHT);
wlMaxTransactionRetryTime.setText(
BaseMessages.getString(PKG, "NeoConnectionEditor.MaxTransactionRetryTime.Label"));
PropsUi.setLook(wlMaxTransactionRetryTime);
FormData fdlMaxTransactionRetryTime = new FormData();
fdlMaxTransactionRetryTime.top = new FormAttachment(lastGroupControl, margin);
fdlMaxTransactionRetryTime.left = new FormAttachment(0, 0);
fdlMaxTransactionRetryTime.right = new FormAttachment(middle, -margin);
wlMaxTransactionRetryTime.setLayoutData(fdlMaxTransactionRetryTime);
wMaxTransactionRetryTime =
new TextVar(variables, wAdvancedComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
PropsUi.setLook(wMaxTransactionRetryTime);
FormData fdMaxTransactionRetryTime = new FormData();
fdMaxTransactionRetryTime.top = new FormAttachment(wlMaxTransactionRetryTime, 0, SWT.CENTER);
fdMaxTransactionRetryTime.left = new FormAttachment(middle, 0);
fdMaxTransactionRetryTime.right = new FormAttachment(95, 0);
wMaxTransactionRetryTime.setLayoutData(fdMaxTransactionRetryTime);
// End of the basic tab...
//
wAdvancedComp.pack();
Rectangle bounds = wAdvancedComp.getBounds();
wAdvancedSComp.setContent(wAdvancedComp);
wAdvancedSComp.setExpandHorizontal(true);
wAdvancedSComp.setExpandVertical(true);
wAdvancedSComp.setMinWidth(bounds.width);
wAdvancedSComp.setMinHeight(bounds.height);
wAdvancedTab.setControl(wAdvancedSComp);
}
private void enableFields() {
// If you specify URLs manually a lot of things are no longer available...
//
boolean hasNoUrls = wUrls.nrNonEmpty() == 0;
for (Control control :
new Control[] {
wlServer,
wServer,
wlDatabaseName,
wDatabaseName,
wlDatabasePort,
wDatabasePort,
wlRouting,
wRouting,
wlPolicy,
wPolicy,
wlEncryption,
wEncryption,
}) {
control.setEnabled(hasNoUrls);
}
// For the normal scenarios without manual URLs we consider the automatic flag.
// If things are configured automatically a number of flags are no longer applicable:
// Version 4, routing, routing policy, encryption & trust all certificates.
//
NeoConnection neo = new NeoConnection();
getWidgetsContent(neo);
boolean automatic = neo.isAutomatic();
boolean routing = neo.isRouting();
boolean encryption = neo.isUsingEncryption();
wlVersion4.setEnabled(!automatic);
wVersion4.setEnabled(!automatic);
wRouting.setEnabled(!automatic);
wlRouting.setEnabled(!automatic);
wRouting.setEnabled(!automatic);
wlEncryption.setEnabled(!automatic);
wEncryption.setEnabled(!automatic);
wlPolicy.setEnabled(!automatic && routing);
wPolicy.setEnabled(!automatic && routing);
wlTrustAllCertificates.setEnabled(!automatic && encryption);
wTrustAllCertificates.setEnabled(!automatic && encryption);
wTrustAllCertificates.getTextVar().setEnabled(!automatic && encryption);
}
@Override
public void setWidgetsContent() {
wName.setText(Const.NVL(metadata.getName(), ""));
wAutomatic.setSelection(metadata.isAutomatic());
wAutomatic.setVariableName(Const.NVL(metadata.getAutomaticVariable(), ""));
wProtocol.setText(Const.NVL(metadata.getProtocol(), ""));
wServer.setText(Const.NVL(metadata.getServer(), ""));
wDatabaseName.setText(Const.NVL(metadata.getDatabaseName(), ""));
wVersion4.setSelection(metadata.isVersion4());
wVersion4.setVariableName(Const.NVL(metadata.getVersion4Variable(), ""));
wDatabasePort.setText(Const.NVL(metadata.getBoltPort(), ""));
wBrowserPort.setText(Const.NVL(metadata.getBrowserPort(), ""));
wRouting.setSelection(metadata.isRouting());
wRouting.setVariableName(Const.NVL(metadata.getRoutingVariable(), ""));
wPolicy.setText(Const.NVL(metadata.getRoutingPolicy(), ""));
wUsername.setText(Const.NVL(metadata.getUsername(), ""));
wPassword.setText(Const.NVL(metadata.getPassword(), ""));
wEncryption.setSelection(metadata.isUsingEncryption());
wEncryption.setVariableName(Const.NVL(metadata.getUsingEncryptionVariable(), ""));
wTrustAllCertificates.setSelection(metadata.isTrustAllCertificates());
wTrustAllCertificates.setVariableName(
Const.NVL(metadata.getTrustAllCertificatesVariable(), ""));
wConnectionLivenessCheckTimeout.setText(
Const.NVL(metadata.getConnectionLivenessCheckTimeout(), ""));
wMaxConnectionLifetime.setText(Const.NVL(metadata.getMaxConnectionLifetime(), ""));
wMaxConnectionPoolSize.setText(Const.NVL(metadata.getMaxConnectionPoolSize(), ""));
wConnectionAcquisitionTimeout.setText(
Const.NVL(metadata.getConnectionAcquisitionTimeout(), ""));
wConnectionTimeout.setText(Const.NVL(metadata.getConnectionTimeout(), ""));
wMaxTransactionRetryTime.setText(Const.NVL(metadata.getMaxTransactionRetryTime(), ""));
for (int i = 0; i < metadata.getManualUrls().size(); i++) {
TableItem item = wUrls.table.getItem(i);
item.setText(1, Const.NVL(metadata.getManualUrls().get(i), ""));
}
wUrls.setRowNums();
wUrls.optWidth(true);
enableFields();
wName.setFocus();
}
@Override
public void getWidgetsContent(NeoConnection neoConnection) {
neoConnection.setName(wName.getText());
neoConnection.setAutomatic(wAutomatic.getSelection());
neoConnection.setAutomaticVariable(wAutomatic.getVariableName());
neoConnection.setProtocol(wProtocol.getText());
neoConnection.setServer(wServer.getText());
neoConnection.setDatabaseName(wDatabaseName.getText());
neoConnection.setVersion4(wVersion4.getSelection());
neoConnection.setVersion4Variable(wVersion4.getVariableName());
neoConnection.setBoltPort(wDatabasePort.getText());
neoConnection.setBrowserPort(wBrowserPort.getText());
neoConnection.setRouting(wRouting.getSelection());
neoConnection.setRoutingVariable(wRouting.getVariableName());
neoConnection.setRoutingPolicy(wPolicy.getText());
neoConnection.setUsername(wUsername.getText());
neoConnection.setPassword(wPassword.getText());
neoConnection.setUsingEncryption(wEncryption.getSelection());
neoConnection.setUsingEncryptionVariable(wEncryption.getVariableName());
neoConnection.setTrustAllCertificates(wTrustAllCertificates.getSelection());
neoConnection.setTrustAllCertificatesVariable(wTrustAllCertificates.getVariableName());
neoConnection.setConnectionLivenessCheckTimeout(wConnectionLivenessCheckTimeout.getText());
neoConnection.setMaxConnectionLifetime(wMaxConnectionLifetime.getText());
neoConnection.setMaxConnectionPoolSize(wMaxConnectionPoolSize.getText());
neoConnection.setConnectionAcquisitionTimeout(wConnectionAcquisitionTimeout.getText());
neoConnection.setConnectionTimeout(wConnectionTimeout.getText());
neoConnection.setMaxTransactionRetryTime(wMaxTransactionRetryTime.getText());
neoConnection.getManualUrls().clear();
for (int i = 0; i < wUrls.nrNonEmpty(); i++) {
TableItem item = wUrls.getNonEmpty(i);
neoConnection.getManualUrls().add(item.getText(1));
}
}
public void test() {
IVariables variables = manager.getVariables();
NeoConnection neo = new NeoConnection(metadata);
try {
getWidgetsContent(neo);
neo.test(variables);
MessageBox box = new MessageBox(hopGui.getShell(), SWT.OK);
box.setText("OK");
String message = "Connection successful!" + Const.CR;
message += Const.CR;
message += "URL : " + neo.getUrl(variables);
box.setMessage(message);
box.open();
} catch (Exception e) {
new ErrorDialog(
hopGui.getShell(),
"Error",
"Error connecting to Neo with URL : " + neo.getUrl(variables),
e);
}
}
@Override
public Button[] createButtonsForButtonBar(Composite composite) {
Button wTest = new Button(composite, SWT.PUSH);
wTest.setText(BaseMessages.getString(PKG, "System.Button.Test"));
wTest.addListener(SWT.Selection, e -> test());
return new Button[] {wTest};
}
@Override
public boolean setFocus() {
if (wName == null || wName.isDisposed()) {
return false;
}
return wName.setFocus();
}
public void clearChanged() {
resetChanged();
MetadataPerspective.getInstance().updateEditor(this);
}
}
|
apache/ignite | 37,356 | modules/commons/src/main/java/org/apache/ignite/internal/util/GridLeanMap.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.util;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.jetbrains.annotations.Nullable;
/**
* Lean map implementation that keeps up to five entries in its fields.
* {@code Null}-keys are not supported.
*/
public class GridLeanMap<K, V> extends GridSerializableMap<K, V> implements Cloneable {
/** */
private static final long serialVersionUID = 0L;
/** Implementation used internally. */
private LeanMap<K, V> map;
/**
* Constructs lean map with initial size of {@code 3}.
*/
public GridLeanMap() {
this(3);
}
/**
* Constructs lean map with initial size.
* <p>
* If given size is greater than zero then map activates batch mode for <tt>put()</tt>
* operations. In this mode map allows to put up to <tt>size</tt> number of key-value
* pairs without internal size optimization, i.e. each next <tt>put()</tt> in batch
* doesn't switch backing implementation so that initial implementation is used as long
* as its capacity allows.
* <p>
* Note that any removal operation either through iterator or map
* itself turns batch mode off and map starts optimizing size after any modification.
*
* @param size Initial size.
*/
public GridLeanMap(int size) {
assert size >= 0;
if (size == 0)
map = null;
else if (size == 1)
map = new Map1<>();
else if (size == 2)
map = new Map2<>();
else if (size == 3)
map = new Map3<>();
else if (size == 4)
map = new Map4<>();
else if (size == 5)
map = new Map5<>();
else
map = new LeanHashMap<>(CommonUtils.capacity(size), 0.75f);
}
/**
* Constructs lean map.
*
* @param m Map to copy entries from.
*/
public GridLeanMap(Map<K, V> m) {
buildFrom(m);
}
/**
* @param m Map to build from.
*/
private void buildFrom(Map<K, V> m) {
Iterator<Entry<K, V>> iter = m.entrySet().iterator();
if (m.isEmpty())
map = null;
else if (m.size() == 1) {
Entry<K, V> e = iter.next();
map = new Map1<>(e.getKey(), e.getValue());
}
else if (m.size() == 2) {
Entry<K, V> e1 = iter.next();
Entry<K, V> e2 = iter.next();
map = new Map2<>(e1.getKey(), e1.getValue(), e2.getKey(), e2.getValue());
}
else if (m.size() == 3) {
Entry<K, V> e1 = iter.next();
Entry<K, V> e2 = iter.next();
Entry<K, V> e3 = iter.next();
map = new Map3<>(e1.getKey(), e1.getValue(), e2.getKey(), e2.getValue(), e3.getKey(), e3.getValue());
}
else if (m.size() == 4) {
Entry<K, V> e1 = iter.next();
Entry<K, V> e2 = iter.next();
Entry<K, V> e3 = iter.next();
Entry<K, V> e4 = iter.next();
map = new Map4<>(e1.getKey(), e1.getValue(), e2.getKey(), e2.getValue(), e3.getKey(), e3.getValue(),
e4.getKey(), e4.getValue());
}
else if (m.size() == 5) {
Entry<K, V> e1 = iter.next();
Entry<K, V> e2 = iter.next();
Entry<K, V> e3 = iter.next();
Entry<K, V> e4 = iter.next();
Entry<K, V> e5 = iter.next();
map = new Map5<>(e1.getKey(), e1.getValue(), e2.getKey(), e2.getValue(), e3.getKey(), e3.getValue(),
e4.getKey(), e4.getValue(), e5.getKey(), e5.getValue());
}
else
map = new LeanHashMap<>(m);
}
/** {@inheritDoc} */
@Override public int size() {
return map != null ? map.size() : 0;
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object key) {
A.notNull(key, "key");
return map != null && map.containsKey(key);
}
/** {@inheritDoc} */
@Override public boolean containsValue(Object val) {
return map != null && map.containsValue(val);
}
/** {@inheritDoc} */
@Nullable @Override public V get(Object key) {
A.notNull(key, "key");
return map != null ? map.get(key) : null;
}
/** {@inheritDoc} */
@Nullable @Override public V put(K key, V val) throws NullPointerException {
A.notNull(key, "key");
if (map == null) {
map = new Map1<>(key, val);
return null;
}
if (!map.isFull() || map.containsKey(key))
return map.put(key, val);
int size = map.size();
// Switch implementation.
if (size == 1) {
Map1<K, V> m = (Map1<K, V>)map;
map = new Map2<>(m.k1, m.v1, key, val);
}
else if (size == 2) {
Map2<K, V> m = (Map2<K, V>)map;
map = new Map3<>(m.k1, m.v1, m.k2, m.v2, key, val);
}
else if (size == 3) {
Map3<K, V> m = (Map3<K, V>)map;
map = new Map4<>(m.k1, m.v1, m.k2, m.v2, m.k3, m.v3, key, val);
}
else if (size == 4) {
Map4<K, V> m = (Map4<K, V>)map;
map = new Map5<>(m.k1, m.v1, m.k2, m.v2, m.k3, m.v3, m.k4, m.v4, key, val);
}
else if (size == 5) {
Map<K, V> m = map;
map = new LeanHashMap<>(6, 1.0f);
map.putAll(m);
map.put(key, val);
}
else
map.put(key, val);
return null;
}
/** {@inheritDoc} */
@Nullable @Override public V remove(Object key) {
A.notNull(key, "key");
V old;
if (map instanceof LeanHashMap) {
old = map.remove(key);
if (map.size() > 5)
return old;
else {
buildFrom(map);
return old;
}
}
else {
if (map == null)
return null;
int size = map.size();
old = map.remove(key);
if (map.size() < size)
buildFrom(map);
return old;
}
}
/** {@inheritDoc} */
@Override public void clear() {
map = null;
}
/** {@inheritDoc} */
@Override public Set<Entry<K, V>> entrySet() {
return new EntrySet();
}
/** {@inheritDoc} */
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"})
@Override protected Object clone() {
try {
GridLeanMap<K, V> clone = (GridLeanMap<K, V>)super.clone();
clone.buildFrom(this);
return clone;
}
catch (CloneNotSupportedException ignore) {
throw new InternalError();
}
}
/**
* Entry set.
*/
private class EntrySet extends AbstractSet<Entry<K, V>> {
/** {@inheritDoc} */
@Override public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
/** */
private int idx = -1;
/** */
private Iterator<Entry<K, V>> mapIter;
/** */
private Entry<K, V> curEnt;
/**
* @param forceNew If forced to create new instance.
* @return Iterator for internal map entry set.
*/
@SuppressWarnings("IfMayBeConditional")
private Iterator<Entry<K, V>> getMapIterator(boolean forceNew) {
if (mapIter == null || forceNew) {
if (map != null)
mapIter = map.entrySet().iterator();
else {
mapIter = new Iterator<Entry<K, V>>() {
@Override public boolean hasNext() {
return false;
}
@Override public Entry<K, V> next() {
throw new NoSuchElementException();
}
@Override public void remove() {
throw new IllegalStateException();
}
};
}
}
return mapIter;
}
@Override public boolean hasNext() {
return map != null && getMapIterator(false).hasNext();
}
@Override public Entry<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
idx++;
return curEnt = getMapIterator(false).next();
}
@Override public void remove() {
if (curEnt == null)
throw new IllegalStateException();
GridLeanMap.this.remove(curEnt.getKey());
curEnt = null;
mapIter = getMapIterator(true);
for (int i = 0; i < idx && mapIter.hasNext(); i++)
mapIter.next();
idx--;
}
};
}
/** {@inheritDoc} */
@Override public int size() {
return GridLeanMap.this.size();
}
}
/**
*
*/
private interface LeanMap<K, V> extends Map<K, V> {
/**
* @return {@code True} if map is full.
*/
public boolean isFull();
}
/**
* Map for single entry.
*/
private static class Map1<K, V> extends AbstractMap<K, V> implements LeanMap<K, V>, Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
protected K k1;
/** */
protected V v1;
/**
* Constructs map.
*/
Map1() {
// No-op.
}
/**
* Constructs map.
*
* @param k1 Key.
* @param v1 Value.
*/
Map1(K k1, V v1) {
this.k1 = k1;
this.v1 = v1;
}
/** {@inheritDoc} */
@Override public boolean isFull() {
return size() == 1;
}
/** {@inheritDoc} */
@Nullable @Override public V remove(Object key) {
V res = null;
if (Objects.equals(key, k1)) {
res = v1;
v1 = null;
k1 = null;
}
return res;
}
/** {@inheritDoc} */
@Override public int size() {
return k1 != null ? 1 : 0;
}
/** {@inheritDoc} */
@Override public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object key) {
return k1 != null && Objects.equals(key, k1);
}
/** {@inheritDoc} */
@Override public boolean containsValue(Object val) {
return k1 != null && Objects.equals(val, v1);
}
/** {@inheritDoc} */
@Nullable @Override public V get(Object key) {
return k1 != null && Objects.equals(key, k1) ? v1 : null;
}
/**
* Puts key-value pair into map only if given key is already contained in the map
* or there are free slots.
* Note that this implementation of {@link Map#put(Object, Object)} does not match
* general contract of {@link Map} interface and serves only for internal purposes.
*
* @param key Key.
* @param val Value.
* @return Previous value associated with given key.
*/
@Nullable @Override public V put(K key, V val) {
V oldVal = get(key);
if (k1 == null || Objects.equals(k1, key)) {
k1 = key;
v1 = val;
}
return oldVal;
}
/**
* @param key Key.
* @param val Value.
* @return New entry.
*/
protected Entry<K, V> e(K key, V val) {
return new SimpleImmutableEntry<>(key, val);
}
/** {@inheritDoc} */
@Override public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
@Override public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
private int idx;
@Override public boolean hasNext() {
return idx == 0 && k1 != null;
}
@Override public Entry<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
idx = 1;
return e(k1, v1);
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public int size() {
return Map1.this.size();
}
};
}
}
/**
* Map for two entries.
*/
private static class Map2<K, V> extends Map1<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** */
protected K k2;
/** */
protected V v2;
/**
* Constructs map.
*/
Map2() {
// No-op.
}
/**
* Constructs map.
*
* @param k1 Key1.
* @param v1 Value1.
* @param k2 Key2.
* @param v2 Value2.
*/
Map2(K k1, V v1, K k2, V v2) {
super(k1, v1);
this.k2 = k2;
this.v2 = v2;
}
/** {@inheritDoc} */
@Override public boolean isFull() {
return size() == 2;
}
/** {@inheritDoc} */
@Nullable @Override public V remove(Object key) {
if (Objects.equals(key, k2)) {
V res = v2;
v2 = null;
k2 = null;
return res;
}
return super.remove(key);
}
/** {@inheritDoc} */
@Override public int size() {
return super.size() + (k2 != null ? 1 : 0);
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object k) {
return super.containsKey(k) || (k2 != null && Objects.equals(k, k2));
}
/** {@inheritDoc} */
@Override public boolean containsValue(Object v) {
return super.containsValue(v) || (k2 != null && Objects.equals(v, v2));
}
/** {@inheritDoc} */
@Override public V get(Object k) {
V v = super.get(k);
return v != null ? v : (k2 != null && Objects.equals(k, k2)) ? v2 : null;
}
/**
* Puts key-value pair into map only if given key is already contained in the map
* or there are free slots.
* Note that this implementation of {@link Map#put(Object, Object)} does not match
* general contract of {@link Map} interface and serves only for internal purposes.
*
* @param key Key.
* @param val Value.
* @return Previous value associated with given key.
*/
@Nullable @Override public V put(K key, V val) throws NullPointerException {
V oldVal = get(key);
if (k1 == null || Objects.equals(k1, key)) {
k1 = key;
v1 = val;
}
else if (k2 == null || Objects.equals(k2, key)) {
k2 = key;
v2 = val;
}
return oldVal;
}
/** {@inheritDoc} */
@Override public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
@Override public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
private int idx;
private Entry<K, V> next;
{
if (k1 != null) {
idx = 1;
next = e(k1, v1);
}
else if (k2 != null) {
idx = 2;
next = e(k2, v2);
}
}
@Override public boolean hasNext() {
return next != null;
}
@Override public Entry<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
Entry<K, V> old = next;
next = null;
if (idx == 1 && k2 != null) {
idx = 2;
next = e(k2, v2);
}
return old;
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public int size() {
return Map2.this.size();
}
};
}
}
/**
* Map for three entries.
*/
private static class Map3<K, V> extends Map2<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** */
protected K k3;
/** */
protected V v3;
/**
* Constructs map.
*/
Map3() {
// No-op.
}
/**
* Constructs map.
*
* @param k1 Key1.
* @param v1 Value1.
* @param k2 Key2.
* @param v2 Value2.
* @param k3 Key3.
* @param v3 Value3.
*/
Map3(K k1, V v1, K k2, V v2, K k3, V v3) {
super(k1, v1, k2, v2);
this.k3 = k3;
this.v3 = v3;
}
/** {@inheritDoc} */
@Override public boolean isFull() {
return size() == 3;
}
/** {@inheritDoc} */
@Nullable @Override public V remove(Object key) {
if (Objects.equals(key, k3)) {
V res = v3;
v3 = null;
k3 = null;
return res;
}
return super.remove(key);
}
/** {@inheritDoc} */
@Override public int size() {
return super.size() + (k3 != null ? 1 : 0);
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object k) {
return super.containsKey(k) || (k3 != null && Objects.equals(k, k3));
}
/** {@inheritDoc} */
@Override public boolean containsValue(Object v) {
return super.containsValue(v) || (k3 != null && Objects.equals(v, v3));
}
/** {@inheritDoc} */
@Nullable @Override public V get(Object k) {
V v = super.get(k);
return v != null ? v : (k3 != null && Objects.equals(k, k3)) ? v3 : null;
}
/**
* Puts key-value pair into map only if given key is already contained in the map
* or there are free slots.
* Note that this implementation of {@link Map#put(Object, Object)} does not match
* general contract of {@link Map} interface and serves only for internal purposes.
*
* @param key Key.
* @param val Value.
* @return Previous value associated with given key.
*/
@Nullable @Override public V put(K key, V val) throws NullPointerException {
V oldVal = get(key);
if (k1 == null || Objects.equals(k1, key)) {
k1 = key;
v1 = val;
}
else if (k2 == null || Objects.equals(k2, key)) {
k2 = key;
v2 = val;
}
else if (k3 == null || Objects.equals(k3, key)) {
k3 = key;
v3 = val;
}
return oldVal;
}
/** {@inheritDoc} */
@Override public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
@Override public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
private int idx;
private Entry<K, V> next;
{
if (k1 != null) {
idx = 1;
next = e(k1, v1);
}
else if (k2 != null) {
idx = 2;
next = e(k2, v2);
}
else if (k3 != null) {
idx = 3;
next = e(k3, v3);
}
}
@Override public boolean hasNext() {
return next != null;
}
@SuppressWarnings("fallthrough")
@Override public Entry<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
Entry<K, V> old = next;
next = null;
switch (idx) {
case 1:
if (k2 != null) {
idx = 2;
next = e(k2, v2);
break;
}
case 2:
if (k3 != null) {
idx = 3;
next = e(k3, v3);
break;
}
}
return old;
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public int size() {
return Map3.this.size();
}
};
}
}
/**
* Map for four entries.
*/
private static class Map4<K, V> extends Map3<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** */
protected K k4;
/** */
protected V v4;
/**
* Constructs map.
*/
Map4() {
// No-op.
}
/**
* Constructs map.
*
* @param k1 Key1.
* @param v1 Value1.
* @param k2 Key2.
* @param v2 Value2.
* @param k3 Key3.
* @param v3 Value3.
* @param k4 Key4.
* @param v4 Value4.
*/
Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
super(k1, v1, k2, v2, k3, v3);
this.k4 = k4;
this.v4 = v4;
}
/** {@inheritDoc} */
@Override public boolean isFull() {
return size() == 4;
}
/** {@inheritDoc} */
@Nullable @Override public V remove(Object key) {
if (Objects.equals(key, k4)) {
V res = v4;
v4 = null;
k4 = null;
return res;
}
return super.remove(key);
}
/** {@inheritDoc} */
@Override public int size() {
return super.size() + (k4 != null ? 1 : 0);
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object k) {
return super.containsKey(k) || (k4 != null && Objects.equals(k, k4));
}
/** {@inheritDoc} */
@Override public boolean containsValue(Object v) {
return super.containsValue(v) || (k4 != null && Objects.equals(v, v4));
}
/** {@inheritDoc} */
@Nullable @Override public V get(Object k) {
V v = super.get(k);
return v != null ? v : (k4 != null && Objects.equals(k, k4)) ? v4 : null;
}
/**
* Puts key-value pair into map only if given key is already contained in the map
* or there are free slots.
* Note that this implementation of {@link Map#put(Object, Object)} does not match
* general contract of {@link Map} interface and serves only for internal purposes.
*
* @param key Key.
* @param val Value.
* @return Previous value associated with given key.
*/
@Nullable @Override public V put(K key, V val) throws NullPointerException {
V oldVal = get(key);
if (k1 == null || Objects.equals(k1, key)) {
k1 = key;
v1 = val;
}
else if (k2 == null || Objects.equals(k2, key)) {
k2 = key;
v2 = val;
}
else if (k3 == null || Objects.equals(k3, key)) {
k3 = key;
v3 = val;
}
else if (k4 == null || Objects.equals(k4, key)) {
k4 = key;
v4 = val;
}
return oldVal;
}
/** {@inheritDoc} */
@Override public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
@Override public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
private int idx;
private Entry<K, V> next;
{
if (k1 != null) {
idx = 1;
next = e(k1, v1);
}
else if (k2 != null) {
idx = 2;
next = e(k2, v2);
}
else if (k3 != null) {
idx = 3;
next = e(k3, v3);
}
else if (k4 != null) {
idx = 4;
next = e(k4, v4);
}
}
@Override public boolean hasNext() {
return next != null;
}
@SuppressWarnings("fallthrough")
@Override public Entry<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
Entry<K, V> old = next;
next = null;
switch (idx) {
case 1:
if (k2 != null) {
idx = 2;
next = e(k2, v2);
break;
}
case 2:
if (k3 != null) {
idx = 3;
next = e(k3, v3);
break;
}
case 3:
if (k4 != null) {
idx = 4;
next = e(k4, v4);
break;
}
}
return old;
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public int size() {
return Map4.this.size();
}
};
}
}
/**
* Map for five entries.
*/
private static class Map5<K, V> extends Map4<K, V> {
/** */
private static final long serialVersionUID = 0L;
/** */
private K k5;
/** */
private V v5;
/**
* Constructs map.
*/
Map5() {
// No-op.
}
/**
* Constructs map.
*
* @param k1 Key1.
* @param v1 Value1.
* @param k2 Key2.
* @param v2 Value2.
* @param k3 Key3.
* @param v3 Value3.
* @param k4 Key4.
* @param v4 Value4.
* @param k5 Key5.
* @param v5 Value5.
*/
Map5(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
super(k1, v1, k2, v2, k3, v3, k4, v4);
this.k5 = k5;
this.v5 = v5;
}
/** {@inheritDoc} */
@Override public boolean isFull() {
return size() == 5;
}
/** {@inheritDoc} */
@Nullable @Override public V remove(Object key) {
if (Objects.equals(key, k5)) {
V res = v5;
v5 = null;
k5 = null;
return res;
}
return super.remove(key);
}
/** {@inheritDoc} */
@Override public int size() {
return super.size() + (k5 != null ? 1 : 0);
}
/** {@inheritDoc} */
@Override public boolean containsKey(Object k) {
return super.containsKey(k) || (k5 != null && Objects.equals(k, k5));
}
/** {@inheritDoc} */
@Override public boolean containsValue(Object v) {
return super.containsValue(v) || (k5 != null && Objects.equals(v, v5));
}
/** {@inheritDoc} */
@Nullable @Override public V get(Object k) {
V v = super.get(k);
return v != null ? v : (k5 != null && Objects.equals(k, k5)) ? v5 : null;
}
/**
* Puts key-value pair into map only if given key is already contained in the map
* or there are free slots.
* Note that this implementation of {@link Map#put(Object, Object)} does not match
* general contract of {@link Map} interface and serves only for internal purposes.
*
* @param key Key.
* @param val Value.
* @return Previous value associated with given key.
*/
@Nullable @Override public V put(K key, V val) throws NullPointerException {
V oldVal = get(key);
if (k1 == null || Objects.equals(k1, key)) {
k1 = key;
v1 = val;
}
else if (k2 == null || Objects.equals(k2, key)) {
k2 = key;
v2 = val;
}
else if (k3 == null || Objects.equals(k3, key)) {
k3 = key;
v3 = val;
}
else if (k4 == null || Objects.equals(k4, key)) {
k4 = key;
v4 = val;
}
else if (k5 == null || Objects.equals(k5, key)) {
k5 = key;
v5 = val;
}
return oldVal;
}
/** {@inheritDoc} */
@Override public Set<Entry<K, V>> entrySet() {
return new AbstractSet<Entry<K, V>>() {
@Override public Iterator<Entry<K, V>> iterator() {
return new Iterator<Entry<K, V>>() {
private int idx;
private Entry<K, V> next;
{
if (k1 != null) {
idx = 1;
next = e(k1, v1);
}
else if (k2 != null) {
idx = 2;
next = e(k2, v2);
}
else if (k3 != null) {
idx = 3;
next = e(k3, v3);
}
else if (k4 != null) {
idx = 4;
next = e(k4, v4);
}
else if (k5 != null) {
idx = 5;
next = e(k5, v5);
}
}
@Override public boolean hasNext() {
return next != null;
}
@SuppressWarnings("fallthrough")
@Override public Entry<K, V> next() {
if (!hasNext())
throw new NoSuchElementException();
Entry<K, V> old = next;
next = null;
switch (idx) {
case 1:
if (k2 != null) {
idx = 2;
next = e(k2, v2);
break;
}
case 2:
if (k3 != null) {
idx = 3;
next = e(k3, v3);
break;
}
case 3:
if (k4 != null) {
idx = 4;
next = e(k4, v4);
break;
}
case 4:
if (k5 != null) {
idx = 5;
next = e(k5, v5);
break;
}
}
return old;
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public int size() {
return Map5.this.size();
}
};
}
}
/**
*
*/
private static class LeanHashMap<K, V> extends HashMap<K, V> implements LeanMap<K, V> {
/** */
private static final long serialVersionUID = 0L;
/**
* @param initCap Capacity.
* @param loadFactor Load factor.
*/
private LeanHashMap(int initCap, float loadFactor) {
super(initCap, loadFactor);
}
/**
* @param m Map.
*/
private LeanHashMap(Map<? extends K, ? extends V> m) {
super(m);
}
/** {@inheritDoc} */
@Override public boolean isFull() {
return false;
}
}
}
|
oracle/graalpython | 37,824 | graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/struct/StructBuiltins.java | /* Copyright (c) 2020, 2025, Oracle and/or its affiliates.
* Copyright (C) 1996-2020 Python Software Foundation
*
* Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
*/
package com.oracle.graal.python.builtins.objects.struct;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_BOOL;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_CHAR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_DOUBLE;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_FLOAT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_HALF_FLOAT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_INT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_LONG_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_PAD_BYTE;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_PASCAL_STRING;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_SHORT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_SIGNED_CHAR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_SIZE_T;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_STRING;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_UNSIGNED_CHAR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_UNSIGNED_INT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_UNSIGNED_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_UNSIGNED_LONG_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_UNSIGNED_SHORT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_UNSIGNED_SIZE_T;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.FMT_VOID_PTR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_BOOL;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_CHAR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_DOUBLE;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_FLOAT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_HALF_FLOAT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_INT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_LONG_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_PAD_BYTE;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_PASCAL_STRING;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_SHORT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_SIGNED_CHAR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_SIZE_T;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_STRING;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_UNSIGNED_CHAR;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_UNSIGNED_INT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_UNSIGNED_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_UNSIGNED_LONG_LONG;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_UNSIGNED_SHORT;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_UNSIGNED_SIZE_T;
import static com.oracle.graal.python.builtins.objects.struct.FormatCode.T_LBL_VOID_PTR;
import static com.oracle.graal.python.nodes.ErrorMessages.ARG_MUST_BE_STR_OR_BYTES;
import static com.oracle.graal.python.nodes.ErrorMessages.BAD_CHR_IN_STRUCT_FMT;
import static com.oracle.graal.python.nodes.ErrorMessages.EMBEDDED_NULL_CHARACTER;
import static com.oracle.graal.python.nodes.ErrorMessages.REPEAT_COUNT_WITHOUT_FMT;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_ITER_CANNOT_UNPACK_FROM_STRUCT_OF_SIZE_0;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_ITER_UNPACK_REQ_A_BUFFER_OF_A_MUL_OF_BYTES;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_NOT_ENOUGH_DATA_TO_UNPACK_N_BYTES;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_NO_SPACE_TO_PACK_N_BYTES;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_OFFSET_OUT_OF_RANGE;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_PACK_EXPECTED_N_ITEMS_GOT_K;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_PACK_INTO_REQ_BUFFER_TO_PACK;
import static com.oracle.graal.python.nodes.ErrorMessages.STRUCT_UNPACK_FROM_REQ_AT_LEAST_N_BYTES;
import static com.oracle.graal.python.nodes.ErrorMessages.S_TAKES_NO_KEYWORD_ARGS;
import static com.oracle.graal.python.nodes.ErrorMessages.UNPACK_REQ_A_BUFFER_OF_N_BYTES;
import static com.oracle.graal.python.runtime.exception.PythonErrorType.StructError;
import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError;
import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING;
import java.nio.ByteOrder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.oracle.graal.python.PythonLanguage;
import com.oracle.graal.python.annotations.ArgumentClinic;
import com.oracle.graal.python.annotations.Slot;
import com.oracle.graal.python.annotations.Slot.SlotKind;
import com.oracle.graal.python.annotations.Slot.SlotSignature;
import com.oracle.graal.python.annotations.Builtin;
import com.oracle.graal.python.builtins.CoreFunctions;
import com.oracle.graal.python.builtins.PythonBuiltinClassType;
import com.oracle.graal.python.builtins.PythonBuiltins;
import com.oracle.graal.python.annotations.PythonOS;
import com.oracle.graal.python.builtins.modules.StructModuleBuiltins;
import com.oracle.graal.python.builtins.objects.PNone;
import com.oracle.graal.python.builtins.objects.buffer.PythonBufferAccessLibrary;
import com.oracle.graal.python.builtins.objects.bytes.PBytes;
import com.oracle.graal.python.builtins.objects.function.PKeyword;
import com.oracle.graal.python.builtins.objects.iterator.PStructUnpackIterator;
import com.oracle.graal.python.builtins.objects.str.PString;
import com.oracle.graal.python.builtins.objects.type.TpSlots;
import com.oracle.graal.python.nodes.ErrorMessages;
import com.oracle.graal.python.nodes.PRaiseNode;
import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode;
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonTernaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonVarargsBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.clinic.ArgumentClinicProvider;
import com.oracle.graal.python.nodes.util.CastToTruffleStringNode;
import com.oracle.graal.python.runtime.IndirectCallData;
import com.oracle.graal.python.runtime.object.PFactory;
import com.oracle.graal.python.util.PythonUtils;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.dsl.Bind;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.ImportStatic;
import com.oracle.truffle.api.dsl.NeverDefault;
import com.oracle.truffle.api.dsl.NodeFactory;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.library.CachedLibrary;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.strings.TruffleString;
@CoreFunctions(extendClasses = PythonBuiltinClassType.PStruct)
public class StructBuiltins extends PythonBuiltins {
static void packInternal(VirtualFrame frame, PStruct self, StructNodes.PackValueNode packValueNode, Object[] args, byte[] buffer, int offset) {
assert self.getSize() <= buffer.length - offset;
FormatCode[] codes = self.getCodes();
int pos = 0;
for (FormatCode code : codes) {
int buffer_offset = offset + code.offset;
for (int j = 0; j < code.repeat; j++, pos++) {
packValueNode.execute(frame, code, self.formatAlignment, args[pos], buffer, buffer_offset);
buffer_offset += code.size;
}
}
}
public static Object[] unpackInternal(PStruct self, StructNodes.UnpackValueNode unpackValueNode, byte[] bytes, int offset) {
Object[] values = new Object[self.getLen()];
FormatCode[] codes = self.getCodes();
int pos = 0;
for (FormatCode code : codes) {
int buffer_offset = offset + code.offset;
for (int j = 0; j < code.repeat; j++, pos++) {
Object value = unpackValueNode.execute(code, self.formatAlignment, bytes, buffer_offset);
values[pos] = value;
buffer_offset += code.size;
}
}
return values;
}
public static final TpSlots SLOTS = StructBuiltinsSlotsGen.SLOTS;
@Override
protected List<? extends NodeFactory<? extends PythonBuiltinBaseNode>> getNodeFactories() {
return StructBuiltinsFactory.getFactories();
}
@ImportStatic(PythonUtils.class)
@Slot(value = SlotKind.tp_new, isComplex = true)
@SlotSignature(name = "Struct", minNumOfPositionalArgs = 2)
@GenerateNodeFactory
public abstract static class ConstructStructNode extends PythonBinaryBuiltinNode {
public static final int NUM_BYTES_LIMIT;
private static final int SHORT_ALIGN = Short.BYTES;
private static final int INT_ALIGN = Integer.BYTES;
private static final int LONG_ALIGN = Long.BYTES;
private static final int FLOAT_ALIGN = Float.BYTES;
private static final int DOUBLE_ALIGN = Double.BYTES;
private static final char ALIGNMENT_NATIVE_NATIVE = '@';
private static final char ALIGNMENT_NATIVE_STD = '=';
private static final char ALIGNMENT_LE_STD = '<';
private static final char ALIGNMENT_BE_STD = '>';
private static final char ALIGNMENT_NET_BE_STD = '!';
private static final char DEFAULT_ALIGNMENT = ALIGNMENT_NATIVE_NATIVE;
// format def tables
private static final FormatDef[] FMT_TABLE = new FormatDef[128];
private static final FormatDef[] FMT_TABLE_NATIVE = new FormatDef[128];
static {
Set<Integer> numBytes = new HashSet<>();
setFormatDefEntry(FMT_TABLE, FMT_PAD_BYTE, T_LBL_PAD_BYTE, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_SIGNED_CHAR, T_LBL_SIGNED_CHAR, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_UNSIGNED_CHAR, T_LBL_UNSIGNED_CHAR, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_CHAR, T_LBL_CHAR, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_STRING, T_LBL_STRING, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_PASCAL_STRING, T_LBL_PASCAL_STRING, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_SHORT, T_LBL_SHORT, 2, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_UNSIGNED_SHORT, T_LBL_UNSIGNED_SHORT, 2, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_INT, T_LBL_INT, 4, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_UNSIGNED_INT, T_LBL_UNSIGNED_INT, 4, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_LONG, T_LBL_LONG, 4, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_UNSIGNED_LONG, T_LBL_UNSIGNED_LONG, 4, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_LONG_LONG, T_LBL_LONG_LONG, 8, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_UNSIGNED_LONG_LONG, T_LBL_UNSIGNED_LONG_LONG, 8, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_BOOL, T_LBL_BOOL, 1, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_HALF_FLOAT, T_LBL_HALF_FLOAT, 2, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_FLOAT, T_LBL_FLOAT, 4, numBytes);
setFormatDefEntry(FMT_TABLE, FMT_DOUBLE, T_LBL_DOUBLE, 8, numBytes);
// native format table
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_PAD_BYTE, T_LBL_PAD_BYTE, Byte.BYTES, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_SIGNED_CHAR, T_LBL_SIGNED_CHAR, Byte.BYTES, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_UNSIGNED_CHAR, T_LBL_UNSIGNED_CHAR, Byte.BYTES, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_CHAR, T_LBL_CHAR, Byte.BYTES, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_STRING, T_LBL_STRING, Byte.BYTES, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_PASCAL_STRING, T_LBL_PASCAL_STRING, Byte.BYTES, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_SHORT, T_LBL_SHORT, Short.BYTES, SHORT_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_UNSIGNED_SHORT, T_LBL_UNSIGNED_SHORT, Short.BYTES, SHORT_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_INT, T_LBL_INT, Integer.BYTES, INT_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_UNSIGNED_INT, T_LBL_UNSIGNED_INT, Integer.BYTES, INT_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_LONG, T_LBL_LONG,
PythonLanguage.getPythonOS() == PythonOS.PLATFORM_WIN32 ? Integer.BYTES : Long.BYTES,
PythonLanguage.getPythonOS() == PythonOS.PLATFORM_WIN32 ? INT_ALIGN : LONG_ALIGN,
numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_UNSIGNED_LONG, T_LBL_UNSIGNED_LONG,
PythonLanguage.getPythonOS() == PythonOS.PLATFORM_WIN32 ? Integer.BYTES : Long.BYTES,
PythonLanguage.getPythonOS() == PythonOS.PLATFORM_WIN32 ? INT_ALIGN : LONG_ALIGN,
numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_SIZE_T, T_LBL_SIZE_T, Long.BYTES, LONG_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_UNSIGNED_SIZE_T, T_LBL_UNSIGNED_SIZE_T, Long.BYTES, LONG_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_LONG_LONG, T_LBL_LONG_LONG, Long.BYTES, LONG_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_UNSIGNED_LONG_LONG, T_LBL_UNSIGNED_LONG_LONG, Long.BYTES, LONG_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_BOOL, T_LBL_BOOL, Byte.BYTES, 0, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_HALF_FLOAT, T_LBL_HALF_FLOAT, Float.BYTES / 2, SHORT_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_FLOAT, T_LBL_FLOAT, Float.BYTES, FLOAT_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_DOUBLE, T_LBL_DOUBLE, Double.BYTES, DOUBLE_ALIGN, numBytes);
setFormatDefEntry(FMT_TABLE_NATIVE, FMT_VOID_PTR, T_LBL_VOID_PTR, Long.BYTES, LONG_ALIGN, numBytes);
NUM_BYTES_LIMIT = numBytes.size();
}
static void setFormatDefEntry(FormatDef[] table, char format, TruffleString label, int size, Set<Integer> numBytes) {
setFormatDefEntry(table, format, label, size, 0, numBytes);
}
static void setFormatDefEntry(FormatDef[] table, char format, TruffleString label, int size, int alignment, Set<Integer> numBytes) {
table[format] = new FormatDef(format, label, size, alignment);
numBytes.add(size);
}
public final PStruct execute(Object format) {
return execute(PythonBuiltinClassType.PStruct, format);
}
public abstract PStruct execute(Object cls, Object format);
@Specialization(guards = "isAscii(format, getCodeRangeNode)")
static PStruct struct(@SuppressWarnings("unused") Object cls, TruffleString format,
@Bind Node inliningTarget,
@Cached.Shared @Cached TruffleString.CopyToByteArrayNode copyToByteArrayNode,
@Cached.Shared @Cached TruffleString.SwitchEncodingNode switchEncodingNode,
@SuppressWarnings("unused") @Cached.Shared @Cached TruffleString.GetCodeRangeNode getCodeRangeNode) {
byte[] fmt = PythonUtils.getAsciiBytes(format, copyToByteArrayNode, switchEncodingNode);
return PFactory.createStruct(PythonLanguage.get(inliningTarget), createStructInternal(inliningTarget, fmt));
}
@Specialization
static PStruct struct(Object cls, PString format,
@Bind Node inliningTarget,
@Cached CastToTruffleStringNode castToTruffleStringNode,
@Cached.Shared @Cached TruffleString.CopyToByteArrayNode copyToByteArrayNode,
@Cached.Shared @Cached TruffleString.SwitchEncodingNode switchEncodingNode,
@SuppressWarnings("unused") @Cached.Shared @Cached TruffleString.GetCodeRangeNode getCodeRangeNode) {
return struct(cls, castToTruffleStringNode.execute(inliningTarget, format), inliningTarget, copyToByteArrayNode, switchEncodingNode, getCodeRangeNode);
}
@Specialization(limit = "1")
static PStruct struct(@SuppressWarnings("unused") Object cls, PBytes format,
@Bind Node inliningTarget,
@CachedLibrary("format") PythonBufferAccessLibrary bufferLib) {
byte[] fmt = bufferLib.getCopiedByteArray(format);
return PFactory.createStruct(PythonLanguage.get(inliningTarget), createStructInternal(inliningTarget, fmt));
}
@Specialization(guards = {"!isPBytes(format)", "!isPString(format)", "!isAsciiTruffleString(format, getCodeRangeNode)"})
static PStruct fallback(@SuppressWarnings("unused") Object cls, Object format,
@SuppressWarnings("unused") @Cached.Shared @Cached TruffleString.GetCodeRangeNode getCodeRangeNode,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, StructError, ARG_MUST_BE_STR_OR_BYTES, "Struct()", format);
}
protected static boolean isAsciiTruffleString(Object o, TruffleString.GetCodeRangeNode getCodeRangeNode) {
return o instanceof TruffleString && PythonUtils.isAscii((TruffleString) o, getCodeRangeNode);
}
@CompilerDirectives.TruffleBoundary
private static PStruct.StructInfo createStructInternal(Node raisingNode, byte[] format) {
int size = 0;
int len = 0;
int nCodes = 0;
int num;
if (StructModuleBuiltins.containsNullCharacter(format)) {
throw PRaiseNode.raiseStatic(raisingNode, PythonBuiltinClassType.StructError, EMBEDDED_NULL_CHARACTER);
}
char alignment = DEFAULT_ALIGNMENT;
int start = 0;
if (format.length > 0 && isAlignment((char) format[0])) {
alignment = (char) format[0];
start = 1;
}
final FormatAlignment formatAlignment = whichAlignment(alignment);
FormatDef[] formatTable = (formatAlignment.nativeSizing) ? FMT_TABLE_NATIVE : FMT_TABLE;
// first pass: validation
for (int i = start; i < format.length; i++) {
char c = (char) format[i];
if (c == ' ') {
continue;
} else if ('0' <= c && c <= '9') {
num = c - '0';
while (++i < format.length && '0' <= (c = (char) format[i]) && c <= '9') {
if (num >= Integer.MAX_VALUE / 10 && (num > Integer.MAX_VALUE / 10 || (c - '0') > Integer.MAX_VALUE % 10)) {
throw PRaiseNode.raiseStatic(raisingNode, StructError, ErrorMessages.STRUCT_SIZE_TOO_LONG);
}
num = num * 10 + (c - '0');
}
if (i == format.length) {
throw PRaiseNode.raiseStatic(raisingNode, StructError, REPEAT_COUNT_WITHOUT_FMT);
}
} else {
num = 1;
}
FormatDef formatDef = getEntry(raisingNode, c, formatTable);
switch (c) {
case 's': // fall through
case 'p':
len++;
nCodes++;
break;
case 'x':
break;
default:
len += num;
if (num != 0) {
nCodes++;
}
break;
}
int itemSize = formatDef.size;
size = align(size, c, formatDef);
if (size == -1) {
throw PRaiseNode.raiseStatic(raisingNode, StructError, ErrorMessages.STRUCT_SIZE_TOO_LONG);
}
if (num > (Integer.MAX_VALUE - size) / itemSize) {
throw PRaiseNode.raiseStatic(raisingNode, StructError, ErrorMessages.STRUCT_SIZE_TOO_LONG);
}
size += num * itemSize;
}
// second pass - fill in the codes (no validation needed)
FormatCode[] codes = new FormatCode[nCodes];
int structSize = size;
int structLen = len;
int j = 0;
size = 0;
for (int i = start; i < format.length; i++) {
char c = (char) format[i];
if (c == ' ') {
continue;
} else if ('0' <= c && c <= '9') {
num = c - '0';
while (++i < format.length && '0' <= (c = (char) format[i]) && c <= '9') {
num = num * 10 + (c - '0');
}
} else {
num = 1;
}
FormatDef formatDef = getEntry(raisingNode, c, formatTable);
size = align(size, c, formatDef);
if (c == 's' || c == 'p') {
codes[j++] = new FormatCode(formatDef, size, num, 1);
size += num;
} else if (c == 'x') {
size += num;
} else if (num != 0) {
codes[j++] = new FormatCode(formatDef, size, formatDef.size, num);
size += formatDef.size * num;
}
}
return new PStruct.StructInfo(format, structSize, structLen, formatAlignment, codes);
}
private static FormatDef getEntry(Node raisingNode, char format, FormatDef[] table) {
FormatDef formatDef = table[format];
if (formatDef != null) {
return formatDef;
}
throw PRaiseNode.raiseStatic(raisingNode, StructError, BAD_CHR_IN_STRUCT_FMT, format);
}
private static boolean isAlignment(char alignment) {
return alignment == ALIGNMENT_LE_STD ||
alignment == ALIGNMENT_BE_STD ||
alignment == ALIGNMENT_NET_BE_STD ||
alignment == ALIGNMENT_NATIVE_STD ||
alignment == ALIGNMENT_NATIVE_NATIVE;
}
private static FormatAlignment whichAlignment(char alignment) {
switch (alignment) {
case ALIGNMENT_LE_STD:
return new FormatAlignment(false, false);
case ALIGNMENT_BE_STD:
case ALIGNMENT_NET_BE_STD:
return new FormatAlignment(true, false);
case ALIGNMENT_NATIVE_STD:
return new FormatAlignment(ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN, false);
case ALIGNMENT_NATIVE_NATIVE:
default:
return new FormatAlignment(ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN, true);
}
}
private static int align(int size, char c, FormatDef formatDef) {
int extra;
int alignedSize = size;
if (formatDef.format == c) {
if (formatDef.alignment > 0 && alignedSize > 0) {
extra = (formatDef.alignment - 1) - (alignedSize - 1) % (formatDef.alignment);
if (extra > Integer.MAX_VALUE - alignedSize) {
return -1;
}
alignedSize += extra;
}
}
return alignedSize;
}
}
@Builtin(name = "pack", minNumOfPositionalArgs = 1, parameterNames = {"$self"}, takesVarArgs = true, takesVarKeywordArgs = true, forceSplitDirectCalls = true)
@GenerateNodeFactory
public abstract static class StructPackNode extends PythonVarargsBuiltinNode {
public final Object execute(VirtualFrame frame, PStruct self, Object[] args) {
return execute(frame, self, args, PKeyword.EMPTY_KEYWORDS);
}
@Specialization
static Object pack(VirtualFrame frame, PStruct self, Object[] args, PKeyword[] keywords,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached StructNodes.PackValueNode packValueNode,
@Cached PRaiseNode raiseNode) {
if (keywords.length != 0) {
throw raiseNode.raise(inliningTarget, TypeError, S_TAKES_NO_KEYWORD_ARGS, "pack()");
}
if (args.length != self.getLen()) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_PACK_EXPECTED_N_ITEMS_GOT_K, self.getLen(), args.length);
}
byte[] bytes = new byte[self.getSize()];
packInternal(frame, self, packValueNode, args, bytes, 0);
return PFactory.createBytes(language, bytes);
}
}
@Builtin(name = "pack_into", minNumOfPositionalArgs = 3, parameterNames = {"$self", "buffer", "offset"}, takesVarArgs = true, forceSplitDirectCalls = true)
@ArgumentClinic(name = "buffer", conversion = ArgumentClinic.ClinicConversion.WritableBuffer)
@ArgumentClinic(name = "offset", conversion = ArgumentClinic.ClinicConversion.Int)
@GenerateNodeFactory
public abstract static class StructPackIntoNode extends PythonClinicBuiltinNode {
public abstract Object execute(VirtualFrame frame, PStruct self, Object buffer, int offset, Object[] args);
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return StructBuiltinsClinicProviders.StructPackIntoNodeClinicProviderGen.INSTANCE;
}
@Specialization(limit = "3")
static Object packInto(VirtualFrame frame, PStruct self, Object buffer, int offset, Object[] args,
@Bind Node inliningTarget,
@Cached("createFor($node)") IndirectCallData indirectCallData,
@CachedLibrary("buffer") PythonBufferAccessLibrary bufferLib,
@Cached StructNodes.PackValueNode packValueNode,
@Cached PRaiseNode raiseNode) {
try {
final long size = self.getUnsignedSize();
if (args.length != self.getLen()) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_PACK_EXPECTED_N_ITEMS_GOT_K, size, args.length);
}
int bufferOffset = offset;
int bufferLen = bufferLib.getBufferLength(buffer);
boolean directWrite = bufferLib.hasInternalByteArray(buffer);
byte[] bytes;
if (directWrite) {
bytes = bufferLib.getInternalByteArray(buffer);
} else {
bytes = new byte[self.getSize()];
}
// support negative offsets
if (bufferOffset < 0) {
// Check that negative offset is low enough to fit data
if (bufferOffset + size > 0) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_NO_SPACE_TO_PACK_N_BYTES, size, bufferOffset);
}
// Check that negative offset is not crossing buffer boundary
if (bufferOffset + bufferLen < 0) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_OFFSET_OUT_OF_RANGE, bufferOffset, bufferLen);
}
bufferOffset += bufferLen;
}
// Check boundaries
if ((bufferLen - bufferOffset) < size) {
assert bufferOffset >= 0;
assert size >= 0;
throw raiseNode.raise(inliningTarget, StructError, STRUCT_PACK_INTO_REQ_BUFFER_TO_PACK, size + bufferOffset, size, bufferOffset, bufferLen);
}
// TODO: GR-54860 use buffer API in the packing process
packInternal(frame, self, packValueNode, args, bytes, directWrite ? bufferOffset : 0);
if (!directWrite) {
bufferLib.writeFromByteArray(buffer, bufferOffset, bytes, 0, bytes.length);
}
return PNone.NONE;
} finally {
bufferLib.release(buffer, frame, indirectCallData);
}
}
@NeverDefault
public static StructPackIntoNode create() {
return StructBuiltinsFactory.StructPackIntoNodeFactory.create(null);
}
}
@Builtin(name = "unpack", minNumOfPositionalArgs = 2, parameterNames = {"$self", "buffer"}, forceSplitDirectCalls = true)
@ArgumentClinic(name = "buffer", conversion = ArgumentClinic.ClinicConversion.ReadableBuffer)
@GenerateNodeFactory
public abstract static class StructUnpackNode extends PythonBinaryClinicBuiltinNode {
public abstract Object execute(VirtualFrame frame, PStruct self, Object buffer);
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return StructBuiltinsClinicProviders.StructUnpackNodeClinicProviderGen.INSTANCE;
}
@Specialization(limit = "3")
static Object unpack(VirtualFrame frame, PStruct self, Object buffer,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached("createFor($node)") IndirectCallData indirectCallData,
@CachedLibrary("buffer") PythonBufferAccessLibrary bufferLib,
@Cached StructNodes.UnpackValueNode unpackValueNode,
@Cached PRaiseNode raiseNode) {
try {
int bytesLen = bufferLib.getBufferLength(buffer);
byte[] bytes = bufferLib.getInternalOrCopiedByteArray(buffer);
if (bytesLen != self.getSize()) {
throw raiseNode.raise(inliningTarget, StructError, UNPACK_REQ_A_BUFFER_OF_N_BYTES, self.getSize());
}
return PFactory.createTuple(language, unpackInternal(self, unpackValueNode, bytes, 0));
} finally {
bufferLib.release(buffer, frame, indirectCallData);
}
}
}
@Builtin(name = "iter_unpack", minNumOfPositionalArgs = 2, parameterNames = {"$self", "buffer"}, forceSplitDirectCalls = true)
@ArgumentClinic(name = "buffer", conversion = ArgumentClinic.ClinicConversion.ReadableBuffer)
@GenerateNodeFactory
public abstract static class StructIterUnpackNode extends PythonBinaryClinicBuiltinNode {
public abstract Object execute(VirtualFrame frame, PStruct self, Object buffer);
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return StructBuiltinsClinicProviders.StructIterUnpackNodeClinicProviderGen.INSTANCE;
}
@Specialization(limit = "3")
static Object iterUnpack(VirtualFrame frame, PStruct self, Object buffer,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached("createFor($node)") IndirectCallData indirectCallData,
@CachedLibrary("buffer") PythonBufferAccessLibrary bufferLib,
@Cached PRaiseNode raiseNode) {
try {
if (self.getSize() == 0) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_ITER_CANNOT_UNPACK_FROM_STRUCT_OF_SIZE_0);
}
int bufferLen = bufferLib.getBufferLength(buffer);
if (bufferLen % self.getSize() != 0) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_ITER_UNPACK_REQ_A_BUFFER_OF_A_MUL_OF_BYTES, self.getSize());
}
} catch (Exception e) {
bufferLib.release(buffer, frame, indirectCallData);
throw e;
}
// The buffer ownership is transferred to the iterator
// TODO: GR-54860 release it when iterator is collected
final PStructUnpackIterator structUnpackIterator = PFactory.createStructUnpackIterator(language, self, buffer);
structUnpackIterator.index = 0;
return structUnpackIterator;
}
}
@Builtin(name = "unpack_from", minNumOfPositionalArgs = 2, parameterNames = {"$self", "buffer", "offset"}, forceSplitDirectCalls = true)
@ArgumentClinic(name = "buffer", conversion = ArgumentClinic.ClinicConversion.ReadableBuffer)
@ArgumentClinic(name = "offset", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "0")
@GenerateNodeFactory
public abstract static class StructUnpackFromNode extends PythonTernaryClinicBuiltinNode {
public abstract Object execute(VirtualFrame frame, PStruct self, Object buffer, int offset);
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return StructBuiltinsClinicProviders.StructUnpackFromNodeClinicProviderGen.INSTANCE;
}
@Specialization(limit = "3")
static Object unpackFrom(VirtualFrame frame, PStruct self, Object buffer, int offset,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached("createFor($node)") IndirectCallData indirectCallData,
@CachedLibrary("buffer") PythonBufferAccessLibrary bufferLib,
@Cached StructNodes.UnpackValueNode unpackValueNode,
@Cached PRaiseNode raiseNode) {
try {
int bufferOffset = offset;
int bytesLen = bufferLib.getBufferLength(buffer);
byte[] bytes = bufferLib.getInternalOrCopiedByteArray(buffer);
final long size = self.getUnsignedSize();
if (bufferOffset < 0) {
if (bufferOffset + size > 0) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_NOT_ENOUGH_DATA_TO_UNPACK_N_BYTES, size, bufferOffset);
}
if (bufferOffset + bytesLen < 0) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_OFFSET_OUT_OF_RANGE, bufferOffset, bytesLen);
}
bufferOffset += bytesLen;
}
if ((bytesLen - bufferOffset) < size) {
throw raiseNode.raise(inliningTarget, StructError, STRUCT_UNPACK_FROM_REQ_AT_LEAST_N_BYTES, size + bufferOffset, size, bufferOffset, bytesLen);
}
return PFactory.createTuple(language, unpackInternal(self, unpackValueNode, bytes, bufferOffset));
} finally {
bufferLib.release(buffer, frame, indirectCallData);
}
}
}
@Builtin(name = "calcsize", minNumOfPositionalArgs = 1)
@GenerateNodeFactory
public abstract static class StructCalcSizeNode extends PythonUnaryBuiltinNode {
@Specialization
Object calcSize(PStruct self) {
return self.getSize();
}
}
@Builtin(name = "size", minNumOfPositionalArgs = 1, isGetter = true)
@GenerateNodeFactory
public abstract static class GetStructSizeNode extends PythonBuiltinNode {
@Specialization
protected Object get(PStruct self) {
return self.getSize();
}
}
@Builtin(name = "format", minNumOfPositionalArgs = 1, isGetter = true)
@GenerateNodeFactory
public abstract static class GetStructFormat extends PythonBuiltinNode {
@Specialization
protected Object get(PStruct self,
@Cached TruffleString.FromByteArrayNode fromBytes,
@Cached TruffleString.SwitchEncodingNode switchEncoding) {
return switchEncoding.execute(fromBytes.execute(self.getFormat(), TruffleString.Encoding.US_ASCII), TS_ENCODING);
}
}
}
|
googleapis/google-cloud-java | 37,432 | java-discoveryengine/proto-google-cloud-discoveryengine-v1alpha/src/main/java/com/google/cloud/discoveryengine/v1alpha/UpdateServingConfigRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/discoveryengine/v1alpha/serving_config_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1alpha;
/**
*
*
* <pre>
* Request for UpdateServingConfig method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest}
*/
public final class UpdateServingConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest)
UpdateServingConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateServingConfigRequest.newBuilder() to construct.
private UpdateServingConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateServingConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateServingConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1alpha.ServingConfigServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_UpdateServingConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1alpha.ServingConfigServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_UpdateServingConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest.class,
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest.Builder.class);
}
private int bitField0_;
public static final int SERVING_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.discoveryengine.v1alpha.ServingConfig servingConfig_;
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the servingConfig field is set.
*/
@java.lang.Override
public boolean hasServingConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The servingConfig.
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ServingConfig getServingConfig() {
return servingConfig_ == null
? com.google.cloud.discoveryengine.v1alpha.ServingConfig.getDefaultInstance()
: servingConfig_;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ServingConfigOrBuilder
getServingConfigOrBuilder() {
return servingConfig_ == null
? com.google.cloud.discoveryengine.v1alpha.ServingConfig.getDefaultInstance()
: servingConfig_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getServingConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getServingConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest other =
(com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest) obj;
if (hasServingConfig() != other.hasServingConfig()) return false;
if (hasServingConfig()) {
if (!getServingConfig().equals(other.getServingConfig())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasServingConfig()) {
hash = (37 * hash) + SERVING_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getServingConfig().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for UpdateServingConfig method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest)
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1alpha.ServingConfigServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_UpdateServingConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1alpha.ServingConfigServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_UpdateServingConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest.class,
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest.Builder.class);
}
// Construct using
// com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getServingConfigFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
servingConfig_ = null;
if (servingConfigBuilder_ != null) {
servingConfigBuilder_.dispose();
servingConfigBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.discoveryengine.v1alpha.ServingConfigServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_UpdateServingConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest build() {
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest buildPartial() {
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest result =
new com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.servingConfig_ =
servingConfigBuilder_ == null ? servingConfig_ : servingConfigBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest) {
return mergeFrom(
(com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest other) {
if (other
== com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
.getDefaultInstance()) return this;
if (other.hasServingConfig()) {
mergeServingConfig(other.getServingConfig());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getServingConfigFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.discoveryengine.v1alpha.ServingConfig servingConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.discoveryengine.v1alpha.ServingConfig,
com.google.cloud.discoveryengine.v1alpha.ServingConfig.Builder,
com.google.cloud.discoveryengine.v1alpha.ServingConfigOrBuilder>
servingConfigBuilder_;
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the servingConfig field is set.
*/
public boolean hasServingConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The servingConfig.
*/
public com.google.cloud.discoveryengine.v1alpha.ServingConfig getServingConfig() {
if (servingConfigBuilder_ == null) {
return servingConfig_ == null
? com.google.cloud.discoveryengine.v1alpha.ServingConfig.getDefaultInstance()
: servingConfig_;
} else {
return servingConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setServingConfig(com.google.cloud.discoveryengine.v1alpha.ServingConfig value) {
if (servingConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
servingConfig_ = value;
} else {
servingConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setServingConfig(
com.google.cloud.discoveryengine.v1alpha.ServingConfig.Builder builderForValue) {
if (servingConfigBuilder_ == null) {
servingConfig_ = builderForValue.build();
} else {
servingConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeServingConfig(
com.google.cloud.discoveryengine.v1alpha.ServingConfig value) {
if (servingConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& servingConfig_ != null
&& servingConfig_
!= com.google.cloud.discoveryengine.v1alpha.ServingConfig.getDefaultInstance()) {
getServingConfigBuilder().mergeFrom(value);
} else {
servingConfig_ = value;
}
} else {
servingConfigBuilder_.mergeFrom(value);
}
if (servingConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearServingConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
servingConfig_ = null;
if (servingConfigBuilder_ != null) {
servingConfigBuilder_.dispose();
servingConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.discoveryengine.v1alpha.ServingConfig.Builder
getServingConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getServingConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.discoveryengine.v1alpha.ServingConfigOrBuilder
getServingConfigOrBuilder() {
if (servingConfigBuilder_ != null) {
return servingConfigBuilder_.getMessageOrBuilder();
} else {
return servingConfig_ == null
? com.google.cloud.discoveryengine.v1alpha.ServingConfig.getDefaultInstance()
: servingConfig_;
}
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.discoveryengine.v1alpha.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.discoveryengine.v1alpha.ServingConfig,
com.google.cloud.discoveryengine.v1alpha.ServingConfig.Builder,
com.google.cloud.discoveryengine.v1alpha.ServingConfigOrBuilder>
getServingConfigFieldBuilder() {
if (servingConfigBuilder_ == null) {
servingConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.discoveryengine.v1alpha.ServingConfig,
com.google.cloud.discoveryengine.v1alpha.ServingConfig.Builder,
com.google.cloud.discoveryengine.v1alpha.ServingConfigOrBuilder>(
getServingConfig(), getParentForChildren(), isClean());
servingConfig_ = null;
}
return servingConfigBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig] to
* update. The following are NOT supported:
*
* * [ServingConfig.name][google.cloud.discoveryengine.v1alpha.ServingConfig.name]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest)
private static final com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest();
}
public static com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateServingConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateServingConfigRequest>() {
@java.lang.Override
public UpdateServingConfigRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<UpdateServingConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateServingConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.UpdateServingConfigRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,230 | java-api-gateway/proto-google-cloud-api-gateway-v1/src/main/java/com/google/cloud/apigateway/v1/ListGatewaysRequest.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/apigateway/v1/apigateway.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.apigateway.v1;
/**
*
*
* <pre>
* Request message for ApiGatewayService.ListGateways
* </pre>
*
* Protobuf type {@code google.cloud.apigateway.v1.ListGatewaysRequest}
*/
public final class ListGatewaysRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.apigateway.v1.ListGatewaysRequest)
ListGatewaysRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListGatewaysRequest.newBuilder() to construct.
private ListGatewaysRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListGatewaysRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListGatewaysRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_ListGatewaysRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_ListGatewaysRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigateway.v1.ListGatewaysRequest.class,
com.google.cloud.apigateway.v1.ListGatewaysRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </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>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.apigateway.v1.ListGatewaysRequest)) {
return super.equals(obj);
}
com.google.cloud.apigateway.v1.ListGatewaysRequest other =
(com.google.cloud.apigateway.v1.ListGatewaysRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest 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.apigateway.v1.ListGatewaysRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest 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.apigateway.v1.ListGatewaysRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest 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.apigateway.v1.ListGatewaysRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest 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.apigateway.v1.ListGatewaysRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest 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.apigateway.v1.ListGatewaysRequest 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 ApiGatewayService.ListGateways
* </pre>
*
* Protobuf type {@code google.cloud.apigateway.v1.ListGatewaysRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.apigateway.v1.ListGatewaysRequest)
com.google.cloud.apigateway.v1.ListGatewaysRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_ListGatewaysRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_ListGatewaysRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigateway.v1.ListGatewaysRequest.class,
com.google.cloud.apigateway.v1.ListGatewaysRequest.Builder.class);
}
// Construct using com.google.cloud.apigateway.v1.ListGatewaysRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.apigateway.v1.Apigateway
.internal_static_google_cloud_apigateway_v1_ListGatewaysRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.ListGatewaysRequest getDefaultInstanceForType() {
return com.google.cloud.apigateway.v1.ListGatewaysRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.apigateway.v1.ListGatewaysRequest build() {
com.google.cloud.apigateway.v1.ListGatewaysRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.ListGatewaysRequest buildPartial() {
com.google.cloud.apigateway.v1.ListGatewaysRequest result =
new com.google.cloud.apigateway.v1.ListGatewaysRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.apigateway.v1.ListGatewaysRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.apigateway.v1.ListGatewaysRequest) {
return mergeFrom((com.google.cloud.apigateway.v1.ListGatewaysRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.apigateway.v1.ListGatewaysRequest other) {
if (other == com.google.cloud.apigateway.v1.ListGatewaysRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent resource of the Gateway, of the form:
* `projects/*/locations/*`
* </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>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Order by parameters.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.apigateway.v1.ListGatewaysRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.apigateway.v1.ListGatewaysRequest)
private static final com.google.cloud.apigateway.v1.ListGatewaysRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.apigateway.v1.ListGatewaysRequest();
}
public static com.google.cloud.apigateway.v1.ListGatewaysRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListGatewaysRequest> PARSER =
new com.google.protobuf.AbstractParser<ListGatewaysRequest>() {
@java.lang.Override
public ListGatewaysRequest 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<ListGatewaysRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListGatewaysRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.apigateway.v1.ListGatewaysRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/graal | 37,817 | substratevm/src/com.oracle.graal.pointsto/src/com/oracle/graal/pointsto/results/TypeFlowSimplifier.java | /*
* Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.pointsto.results;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.graalvm.collections.EconomicSet;
import org.graalvm.nativeimage.AnnotationAccess;
import com.oracle.graal.pointsto.PointsToAnalysis;
import com.oracle.graal.pointsto.flow.InvokeTypeFlow;
import com.oracle.graal.pointsto.flow.MethodFlowsGraph;
import com.oracle.graal.pointsto.flow.MethodTypeFlow;
import com.oracle.graal.pointsto.flow.PrimitiveFilterTypeFlow;
import com.oracle.graal.pointsto.flow.TypeFlow;
import com.oracle.graal.pointsto.meta.AnalysisMethod;
import com.oracle.graal.pointsto.meta.AnalysisType;
import com.oracle.graal.pointsto.meta.PointsToAnalysisField;
import com.oracle.graal.pointsto.meta.PointsToAnalysisMethod;
import com.oracle.graal.pointsto.typestate.PrimitiveConstantTypeState;
import com.oracle.graal.pointsto.typestate.TypeState;
import com.oracle.graal.pointsto.util.AnalysisError;
import com.oracle.svm.core.annotate.Delete;
import com.oracle.svm.util.ImageBuildStatistics;
import jdk.graal.compiler.core.common.type.IntegerStamp;
import jdk.graal.compiler.core.common.type.ObjectStamp;
import jdk.graal.compiler.core.common.type.Stamp;
import jdk.graal.compiler.core.common.type.StampFactory;
import jdk.graal.compiler.core.common.type.TypeReference;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph.NodeBitMap;
import jdk.graal.compiler.graph.NodeInputList;
import jdk.graal.compiler.graph.NodeMap;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodes.AbstractBeginNode;
import jdk.graal.compiler.nodes.CallTargetNode;
import jdk.graal.compiler.nodes.ConstantNode;
import jdk.graal.compiler.nodes.FixedGuardNode;
import jdk.graal.compiler.nodes.FixedNode;
import jdk.graal.compiler.nodes.FixedWithNextNode;
import jdk.graal.compiler.nodes.FrameState;
import jdk.graal.compiler.nodes.IfNode;
import jdk.graal.compiler.nodes.Invoke;
import jdk.graal.compiler.nodes.InvokeWithExceptionNode;
import jdk.graal.compiler.nodes.LogicConstantNode;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.ParameterNode;
import jdk.graal.compiler.nodes.PiNode;
import jdk.graal.compiler.nodes.StartNode;
import jdk.graal.compiler.nodes.StateSplit;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.extended.BytecodeExceptionNode;
import jdk.graal.compiler.nodes.extended.ValueAnchorNode;
import jdk.graal.compiler.nodes.java.ClassIsAssignableFromNode;
import jdk.graal.compiler.nodes.java.InstanceOfNode;
import jdk.graal.compiler.nodes.java.LoadFieldNode;
import jdk.graal.compiler.nodes.java.LoadIndexedNode;
import jdk.graal.compiler.nodes.java.MethodCallTargetNode;
import jdk.graal.compiler.nodes.spi.SimplifierTool;
import jdk.graal.compiler.nodes.util.GraphUtil;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.JavaMethodProfile;
import jdk.vm.ci.meta.JavaTypeProfile;
import jdk.vm.ci.meta.PrimitiveConstant;
/**
* Simplify graphs based on reachability information tracked by the static analysis. Additionally,
* simplify graphs based on more concrete type information proven by the points-to analysis. The
* optimizations enabled by the points-to analysis are a superset of the optimizations enabled by
* the reachability analysis.
*/
class TypeFlowSimplifier extends ReachabilitySimplifier {
private final PointsToAnalysis analysis;
private final MethodTypeFlow methodFlow;
private final TypeFlow<?>[] parameterFlows;
private final NodeMap<TypeFlow<?>> nodeFlows;
private final boolean allowConstantFolding;
private final boolean allowOptimizeReturnParameter;
private final EconomicSet<ValueNode> unreachableValues = EconomicSet.create();
private final NodeBitMap createdPiNodes;
TypeFlowSimplifier(StrengthenGraphs strengthenGraphs, AnalysisMethod method, StructuredGraph graph) {
super(strengthenGraphs, method, graph);
analysis = (PointsToAnalysis) strengthenGraphs.bb;
methodFlow = ((PointsToAnalysisMethod) method).getTypeFlow();
AnalysisError.guarantee(methodFlow.flowsGraphCreated(), "Trying to strengthen a method without a type flows graph: %s.", method);
MethodFlowsGraph originalFlows = methodFlow.getMethodFlowsGraph();
parameterFlows = originalFlows.getParameters();
nodeFlows = new NodeMap<>(graph);
var cursor = originalFlows.getNodeFlows().getEntries();
while (cursor.advance()) {
Node node = cursor.getKey().getNode();
assert nodeFlows.get(node) == null : "overwriting existing entry for " + node;
nodeFlows.put(node, cursor.getValue());
}
createdPiNodes = new NodeBitMap(graph);
allowConstantFolding = strengthenGraphs.strengthenGraphWithConstants && analysis.getHostVM().allowConstantFolding(method);
/*
* In deoptimization target methods optimizing the return parameter can make new values live
* across deoptimization entrypoints.
*
* In runtime-compiled methods invokes may be intrinsified during runtime partial evaluation
* and change the behavior of the invoke. This would be a problem if the behavior of the
* method completely changed; however, currently this intrinsification is used to improve
* the stamp of the returned value, but not to alter the semantics. Hence, it is preferred
* to continue to use the return value of the invoke (as opposed to the parameter value).
*/
allowOptimizeReturnParameter = method.isOriginalMethod() && analysis.optimizeReturnedParameter();
}
private TypeFlow<?> getNodeFlow(Node node) {
return nodeFlows == null || nodeFlows.isNew(node) ? null : nodeFlows.get(node);
}
@Override
public void simplify(Node n, SimplifierTool tool) {
if (n instanceof ValueNode node) {
super.tryImproveStamp(node, tool);
}
if (strengthenGraphs.simplifyDelegate(n, tool)) {
// Handled in the delegate simplification.
return;
}
switch (n) {
case ParameterNode node -> handleParameter(node, tool);
case LoadFieldNode node -> handleLoadField(node, tool);
case LoadIndexedNode node -> handleLoadIndexed(node, tool);
case IfNode node -> handleIf(node, tool);
case FixedGuardNode node -> handleFixedGuard(node, tool);
case Invoke invoke -> handleInvoke(invoke, tool);
// Next simplifications don't use type states and are shared with reachability analysis.
case InstanceOfNode node -> super.handleInstanceOf(node, tool);
case ClassIsAssignableFromNode node -> super.handleClassIsAssignableFrom(node, tool);
case BytecodeExceptionNode node -> super.handleBytecodeException(node, tool);
case FrameState node -> super.handleFrameState(node);
case PiNode node -> super.handlePi(node, tool);
case null, default -> {
}
}
}
private void handleParameter(ParameterNode node, SimplifierTool tool) {
StartNode anchorPoint = graph.start();
Object newStampOrConstant = strengthenStampFromTypeFlow(node, parameterFlows[node.index()], anchorPoint, tool);
updateStampUsingPiNode(node, newStampOrConstant, anchorPoint, tool);
}
private void handleLoadField(LoadFieldNode node, SimplifierTool tool) {
/*
* First step: it is beneficial to strengthen the stamp of the LoadFieldNode because then
* there is no artificial anchor after which the more precise type is available. However,
* the memory load will be a floating node later, so we can only update the stamp directly
* to the stamp that is correct for the whole method and all inlined methods.
*/
PointsToAnalysisField field = (PointsToAnalysisField) node.field();
Object fieldNewStampOrConstant = strengthenStampFromTypeFlow(node, field.getSinkFlow(), node, tool);
if (fieldNewStampOrConstant instanceof JavaConstant) {
ConstantNode replacement = ConstantNode.forConstant((JavaConstant) fieldNewStampOrConstant, analysis.getMetaAccess(), graph);
graph.replaceFixedWithFloating(node, replacement);
tool.addToWorkList(replacement);
} else {
super.updateStampInPlace(node, (Stamp) fieldNewStampOrConstant, tool);
/*
* Second step: strengthen using context-sensitive analysis results, which requires an
* anchored PiNode.
*/
Object nodeNewStampOrConstant = strengthenStampFromTypeFlow(node, getNodeFlow(node), node, tool);
updateStampUsingPiNode(node, nodeNewStampOrConstant, node, tool);
}
}
private void handleLoadIndexed(LoadIndexedNode node, SimplifierTool tool) {
Object newStampOrConstant = strengthenStampFromTypeFlow(node, getNodeFlow(node), node, tool);
updateStampUsingPiNode(node, newStampOrConstant, node, tool);
}
private void handleIf(IfNode node, SimplifierTool tool) {
boolean trueUnreachable = isUnreachable(node.trueSuccessor());
boolean falseUnreachable = isUnreachable(node.falseSuccessor());
if (trueUnreachable && falseUnreachable) {
super.makeUnreachable(node, tool, () -> super.location(node) + ": both successors of IfNode are unreachable");
} else if (trueUnreachable || falseUnreachable) {
AbstractBeginNode killedBegin = node.successor(trueUnreachable);
AbstractBeginNode survivingBegin = node.successor(!trueUnreachable);
if (survivingBegin.hasUsages()) {
/*
* Even when we know that the IfNode is not necessary because the condition is
* statically proven, all PiNode that are anchored at the surviving branch must
* remain anchored at exactly this point. It would be wrong to anchor the PiNode at
* the BeginNode of the preceding block, because at that point the condition is not
* proven yet.
*/
ValueAnchorNode anchor = graph.add(new ValueAnchorNode());
graph.addAfterFixed(survivingBegin, anchor);
survivingBegin.replaceAtUsages(anchor, InputType.Guard, InputType.Anchor);
}
graph.removeSplit(node, survivingBegin);
GraphUtil.killCFG(killedBegin);
}
}
private void handleFixedGuard(FixedGuardNode node, SimplifierTool tool) {
if (isUnreachable(node)) {
node.setCondition(LogicConstantNode.tautology(graph), true);
tool.addToWorkList(node);
}
}
private boolean isUnreachable(Node branch) {
TypeFlow<?> branchFlow = getNodeFlow(branch);
if (branchFlow != null && !methodFlow.isSaturated(analysis, branchFlow)) {
if (!branchFlow.isFlowEnabled()) {
return true;
}
TypeState typeState = methodFlow.foldTypeFlow(analysis, branchFlow);
if (branchFlow.isPrimitiveFlow()) {
/*
* This assert is a safeguard to verify the assumption that only one type of flow
* has to be considered as a branch predicate at the moment.
*/
assert branchFlow instanceof PrimitiveFilterTypeFlow : "Unexpected type of primitive flow encountered as branch predicate: " + branchFlow;
}
return typeState.isEmpty();
}
return false;
}
private void handleInvoke(Invoke invoke, SimplifierTool tool) {
if (!(invoke.callTarget() instanceof MethodCallTargetNode callTarget)) {
return;
}
if (super.maybeMarkUnreachable(invoke, tool)) {
/* Invoke is unreachable, there is no point in improving any types further. */
return;
}
FixedNode node = invoke.asFixedNode();
InvokeTypeFlow invokeFlow = (InvokeTypeFlow) getNodeFlow(node);
if (invokeFlow == null) {
/* No points-to analysis results. */
return;
}
if (!invokeFlow.isFlowEnabled()) {
super.unreachableInvoke(invoke, tool, () -> super.location(invoke) + ": flow is not enabled by its predicate " + invokeFlow.getPredicate());
/* Invoke is unreachable, there is no point in improving any types further. */
return;
}
AnalysisMethod targetMethod = (AnalysisMethod) callTarget.targetMethod();
Collection<AnalysisMethod> callees = invokeFlow.getOriginalCallees();
if (callees.isEmpty()) {
if (strengthenGraphs.isClosedTypeWorld) {
/* Invoke is unreachable, there is no point in improving any types further. */
super.unreachableInvoke(invoke, tool, () -> super.location(invoke) + ": empty list of callees for call to " + targetMethod.getQualifiedName());
}
/* In open world we cannot make any assumptions about an invoke with 0 callees. */
return;
}
assert invokeFlow.isFlowEnabled() : "Disabled invoke should have no callees: " + invokeFlow + ", in method " + StrengthenGraphs.getQualifiedName(graph);
FixedWithNextNode beforeInvoke = (FixedWithNextNode) invoke.predecessor();
NodeInputList<ValueNode> arguments = callTarget.arguments();
for (int i = 0; i < arguments.size(); i++) {
ValueNode argument = arguments.get(i);
Object newStampOrConstant = strengthenStampFromTypeFlow(argument, invokeFlow.getActualParameters()[i], beforeInvoke, tool);
if (node.isDeleted()) {
/* Parameter stamp was empty, so invoke is unreachable. */
return;
}
if (i == 0 && invoke.getInvokeKind() != CallTargetNode.InvokeKind.Static) {
/*
* Check for null receiver. If so, the invoke is unreachable.
*
* Note it is not necessary to check for an empty stamp, as in that case
* strengthenStampFromTypeFlow will make the invoke unreachable.
*/
boolean nullReceiver = false;
if (argument instanceof ConstantNode constantNode) {
nullReceiver = constantNode.getValue().isDefaultForKind();
}
if (!nullReceiver && newStampOrConstant instanceof ObjectStamp stamp) {
nullReceiver = stamp.alwaysNull();
}
if (!nullReceiver && newStampOrConstant instanceof Constant constantValue) {
nullReceiver = constantValue.isDefaultForKind();
}
if (nullReceiver) {
invokeWithNullReceiver(invoke);
return;
}
}
if (newStampOrConstant != null) {
ValueNode pi = insertPi(argument, newStampOrConstant, beforeInvoke);
if (pi != null && pi != argument) {
callTarget.replaceAllInputs(argument, pi);
}
}
}
if (callTarget.invokeKind().isDirect()) {
/*
* Note: A direct invoke doesn't necessarily imply that the analysis should have
* discovered a single callee. When dealing with interfaces it is in fact possible that
* the Graal stamps are more accurate than the analysis results. So an interface call
* may have already been optimized to a special call by stamp strengthening of the
* receiver object, hence the invoke kind is direct, whereas the points-to analysis
* inaccurately concluded there can be more than one callee.
*
* Below we just check that if there is a direct invoke *and* the analysis discovered a
* single callee, then the callee should match the target method.
*/
if (callees.size() == 1) {
AnalysisMethod singleCallee = callees.iterator().next();
assert targetMethod.equals(singleCallee) : "Direct invoke target mismatch: " + targetMethod + " != " + singleCallee + ". Called from " + graph.method().format("%H.%n");
}
} else if (AnnotationAccess.isAnnotationPresent(targetMethod, Delete.class)) {
/* We de-virtualize invokes to deleted methods since the callee must be unique. */
AnalysisError.guarantee(callees.size() == 1, "@Delete methods should have a single callee.");
AnalysisMethod singleCallee = callees.iterator().next();
devirtualizeInvoke(singleCallee, invoke);
} else if (targetMethod.canBeStaticallyBound() || strengthenGraphs.isClosedTypeWorld) {
/*
* We only de-virtualize invokes if we run a closed type world analysis or the target
* method can be trivially statically bound.
*/
if (callees.size() == 1) {
AnalysisMethod singleCallee = callees.iterator().next();
devirtualizeInvoke(singleCallee, invoke);
} else {
TypeState receiverTypeState = null;
/* If the receiver flow is saturated, its exact type state does not matter. */
if (invokeFlow.getTargetMethod().hasReceiver() && !methodFlow.isSaturated(analysis, invokeFlow.getReceiver())) {
receiverTypeState = methodFlow.foldTypeFlow(analysis, invokeFlow.getReceiver());
}
assignInvokeProfiles(invoke, invokeFlow, callees, receiverTypeState, false);
}
} else {
/* Last resort, try to inject profiles optimistically. */
TypeState receiverTypeState = null;
if (invokeFlow.getTargetMethod().hasReceiver()) {
if (methodFlow.isSaturated(analysis, invokeFlow)) {
/*
* For saturated invokes use all seen instantiated subtypes of target method
* declaring class. In an open world this is incomplete as new types may be seen
* later, but it is an optimistic approximation.
*/
receiverTypeState = targetMethod.getDeclaringClass().getTypeFlow(analysis, false).getState();
} else {
receiverTypeState = methodFlow.foldTypeFlow(analysis, invokeFlow.getReceiver());
}
}
if (receiverTypeState != null && receiverTypeState.typesCount() <= MAX_TYPES_OPTIMISTIC_PROFILES) {
assignInvokeProfiles(invoke, invokeFlow, callees, receiverTypeState, true);
}
}
if (allowOptimizeReturnParameter && (strengthenGraphs.isClosedTypeWorld || callTarget.invokeKind().isDirect() || targetMethod.canBeStaticallyBound())) {
/* Can only optimize returned parameter when all possible callees are visible. */
optimizeReturnedParameter(callees, arguments, node, tool);
}
FixedWithNextNode anchorPointAfterInvoke = (FixedWithNextNode) (invoke instanceof InvokeWithExceptionNode ? invoke.next() : invoke);
TypeFlow<?> nodeFlow = invokeFlow.getResult();
if (nodeFlow != null && node.getStackKind() == JavaKind.Void && !methodFlow.isSaturated(analysis, nodeFlow)) {
/*
* We track the reachability of return statements in void methods via returning either
* Empty or AnyPrimitive TypeState, therefore we perform an emptiness check.
*/
var typeState = methodFlow.foldTypeFlow(analysis, nodeFlow);
if (typeState.isEmpty() && unreachableValues.add(node)) {
super.makeUnreachable(anchorPointAfterInvoke.next(), tool, () -> super.location(node) + ": return from void method was proven unreachable");
}
}
Object newStampOrConstant = strengthenStampFromTypeFlow(node, nodeFlow, anchorPointAfterInvoke, tool);
updateStampUsingPiNode(node, newStampOrConstant, anchorPointAfterInvoke, tool);
}
/**
* The invoke always has a null receiver, so it can be removed.
*/
private void invokeWithNullReceiver(Invoke invoke) {
FixedNode replacement = strengthenGraphs.createInvokeWithNullReceiverReplacement(graph);
((FixedWithNextNode) invoke.predecessor()).setNext(replacement);
GraphUtil.killCFG(invoke.asFixedNode());
}
/**
* The invoke has only one callee, i.e., the call can be devirtualized to this callee. This
* allows later inlining of the callee.
*/
private void devirtualizeInvoke(AnalysisMethod singleCallee, Invoke invoke) {
if (ImageBuildStatistics.Options.CollectImageBuildStatistics.getValue(graph.getOptions())) {
ImageBuildStatistics.counters().incDevirtualizedInvokeCounter();
}
Stamp anchoredReceiverStamp = StampFactory.object(TypeReference.createWithoutAssumptions(singleCallee.getDeclaringClass()));
ValueNode piReceiver = insertPi(invoke.getReceiver(), anchoredReceiverStamp, (FixedWithNextNode) invoke.asNode().predecessor());
if (piReceiver != null) {
invoke.callTarget().replaceFirstInput(invoke.getReceiver(), piReceiver);
}
assert invoke.getInvokeKind().isIndirect() : invoke;
invoke.callTarget().setInvokeKind(CallTargetNode.InvokeKind.Special);
invoke.callTarget().setTargetMethod(singleCallee);
}
/**
* Maximum number of types seen in a {@link TypeState} for a virtual {@link Invoke} to consider
* optimistic profile injection. See {@link #handleInvoke(Invoke, SimplifierTool)} for more
* details. Note that this is a footprint consideration - we do not want to carry around
* gargantuan {@link JavaTypeProfile} in {@link MethodCallTargetNode} that cannot be used
* anyway.
*/
private static final int MAX_TYPES_OPTIMISTIC_PROFILES = 100;
private void assignInvokeProfiles(Invoke invoke, InvokeTypeFlow invokeFlow, Collection<AnalysisMethod> callees, TypeState receiverTypeState, boolean assumeNotRecorded) {
/*
* In an open type world we cannot trust the type state of the receiver for virtual calls as
* new subtypes could be added later.
*
* Note: assumeNotRecorded specifies if profiles are injected for a closed or open world.
* For a closed world with precise analysis results we never have a notRecordedProbabiltiy
* in any profile. For the open world we always assume that there is a not recorded
* probability in the profile. Such a not recorded probability will be injected if
* assumeNotRecorded==true.
*/
JavaTypeProfile typeProfile = strengthenGraphs.makeTypeProfile(receiverTypeState, assumeNotRecorded);
/*
* In a closed type world analysis the method profile of an invoke is complete and contains
* all the callees reachable at that invocation location. Even if that invoke is saturated
* it is still correct as it contains all the reachable implementations of the target
* method. However, in an open type world the method profile of an invoke, saturated or not,
* is incomplete, as there can be implementations that we haven't yet seen.
*/
JavaMethodProfile methodProfile = strengthenGraphs.makeMethodProfile(callees, assumeNotRecorded);
assert typeProfile == null || typeProfile.getTypes().length > 1 || assumeNotRecorded : "Should devirtualize with typeProfile=" + typeProfile + " and methodProfile=" + methodProfile +
" and callees" + callees + " invoke " + invokeFlow + " " + invokeFlow.getReceiver() + " in method " + StrengthenGraphs.getQualifiedName(graph);
assert methodProfile == null || methodProfile.getMethods().length > 1 || assumeNotRecorded : "Should devirtualize with typeProfile=" + typeProfile + " and methodProfile=" + methodProfile +
" and callees" + callees + " invoke " + invokeFlow + " " + invokeFlow.getReceiver() + " in method " + StrengthenGraphs.getQualifiedName(graph);
strengthenGraphs.setInvokeProfiles(invoke, typeProfile, methodProfile);
}
/**
* If all possible callees return the same parameter, then we can replace the invoke with that
* parameter at all usages. This is the same that would happen when the callees are inlined. So
* we get a bit of the benefits of method inlining without actually performing the inlining.
*/
private static void optimizeReturnedParameter(Collection<AnalysisMethod> callees, NodeInputList<ValueNode> arguments, FixedNode invoke, SimplifierTool tool) {
int returnedParameterIndex = -1;
for (AnalysisMethod callee : callees) {
if (callee.hasNeverInlineDirective()) {
/*
* If the method is explicitly marked as "never inline", it might be an intentional
* sink to prevent an optimization. Mostly, this is a pattern we use in unit tests.
* So this reduces the surprise that tests are "too well optimized" without doing
* any harm for real-world methods.
*/
return;
}
int returnedCalleeParameterIndex = PointsToAnalysis.assertPointsToAnalysisMethod(callee).getTypeFlow().getReturnedParameterIndex();
if (returnedCalleeParameterIndex == -1) {
/* This callee does not return a parameter. */
return;
}
if (returnedParameterIndex == -1) {
returnedParameterIndex = returnedCalleeParameterIndex;
} else if (returnedParameterIndex != returnedCalleeParameterIndex) {
/* This callee returns a different parameter than a previous callee. */
return;
}
}
assert returnedParameterIndex != -1 : callees;
ValueNode returnedActualParameter = arguments.get(returnedParameterIndex);
tool.addToWorkList(invoke.usages());
invoke.replaceAtUsages(returnedActualParameter);
}
private void updateStampUsingPiNode(ValueNode node, Object newStampOrConstant, FixedWithNextNode anchorPoint, SimplifierTool tool) {
if (newStampOrConstant != null && node.hasUsages() && !createdPiNodes.isMarked(node)) {
ValueNode pi = insertPi(node, newStampOrConstant, anchorPoint);
if (pi != null) {
/*
* The Canonicalizer that drives all of our node processing is iterative. We only
* want to insert the PiNode the first time we handle a node.
*/
createdPiNodes.mark(node);
if (pi.isConstant()) {
node.replaceAtUsages(pi);
} else {
FrameState anchorState = node instanceof StateSplit ? ((StateSplit) node).stateAfter() : graph.start().stateAfter();
node.replaceAtUsages(pi, usage -> usage != pi && usage != anchorState);
}
tool.addToWorkList(pi.usages());
}
}
}
/**
* See comment on {@link StrengthenGraphs} on why anchoring is necessary.
*/
private ValueNode insertPi(ValueNode input, Object newStampOrConstant, FixedWithNextNode anchorPoint) {
if (newStampOrConstant instanceof JavaConstant constant) {
if (input.isConstant()) {
assert analysis.getConstantReflectionProvider().constantEquals(input.asConstant(), constant) : input.asConstant() + ", " + constant;
return null;
}
return ConstantNode.forConstant(constant, analysis.getMetaAccess(), graph);
}
Stamp piStamp = (Stamp) newStampOrConstant;
Stamp oldStamp = input.stamp(NodeView.DEFAULT);
Stamp computedStamp = oldStamp.improveWith(piStamp);
if (oldStamp.equals(computedStamp)) {
/* The PiNode does not give any additional information. */
return null;
}
ValueAnchorNode anchor = graph.add(new ValueAnchorNode());
graph.addAfterFixed(anchorPoint, anchor);
return graph.unique(new PiNode(input, piStamp, anchor));
}
private Object strengthenStampFromTypeFlow(ValueNode node, TypeFlow<?> nodeFlow, FixedWithNextNode anchorPoint, SimplifierTool tool) {
if (nodeFlow == null || !analysis.isSupportedJavaKind(node.getStackKind())) {
return null;
}
if (methodFlow.isSaturated(analysis, nodeFlow)) {
/* The type flow is saturated, its type state does not matter. */
return null;
}
if (unreachableValues.contains(node)) {
/* This node has already been made unreachable - no further action is needed. */
return null;
}
/*
* If there are no usages of the node, then adding a PiNode would only bloat the graph.
* However, we don't immediately return null since the stamp can still indicate this node is
* unreachable.
*/
boolean hasUsages = node.usages().filter(n -> !(n instanceof FrameState)).isNotEmpty();
if (!nodeFlow.isFlowEnabled()) {
super.makeUnreachable(anchorPoint.next(), tool, () -> super.location(node) + ": flow is not enabled by its predicate " + nodeFlow.getPredicate());
unreachableValues.add(node);
return null;
}
TypeState nodeTypeState = methodFlow.foldTypeFlow(analysis, nodeFlow);
if (hasUsages && allowConstantFolding && !nodeTypeState.canBeNull()) {
JavaConstant constantValue = nodeTypeState.asConstant();
if (constantValue != null) {
return constantValue;
}
}
node.inferStamp();
Stamp s = node.stamp(NodeView.DEFAULT);
if (s.isIntegerStamp() || nodeTypeState.isPrimitive()) {
return getIntegerStamp(node, ((IntegerStamp) s), anchorPoint, nodeTypeState, tool);
}
ObjectStamp oldStamp = (ObjectStamp) s;
AnalysisType oldType = (AnalysisType) oldStamp.type();
boolean nonNull = oldStamp.nonNull() || !nodeTypeState.canBeNull();
/*
* Find all types of the TypeState that are compatible with the current stamp. Since stamps
* are propagated around immediately by the Canonicalizer it is possible and allowed that
* the stamp is already more precise than the static analysis results.
*/
List<AnalysisType> typeStateTypes = new ArrayList<>(nodeTypeState.typesCount());
for (AnalysisType typeStateType : nodeTypeState.types(analysis)) {
if (oldType == null || (oldStamp.isExactType() ? oldType.equals(typeStateType) : oldType.isJavaLangObject() || oldType.isAssignableFrom(typeStateType))) {
typeStateTypes.add(typeStateType);
}
}
if (typeStateTypes.isEmpty()) {
if (nonNull) {
super.makeUnreachable(anchorPoint.next(), tool, () -> super.location(node) + ": empty object type state when strengthening oldStamp " + oldStamp);
unreachableValues.add(node);
return null;
} else {
return hasUsages ? StampFactory.alwaysNull() : null;
}
} else if (!hasUsages) {
// no need to return strengthened stamp if it is unused
return null;
} else if (typeStateTypes.size() == 1) {
AnalysisType exactType = typeStateTypes.get(0);
assert strengthenGraphs.getSingleImplementorType(exactType) == null || exactType.equals(strengthenGraphs.getSingleImplementorType(exactType)) : "exactType=" + exactType +
", singleImplementor=" + strengthenGraphs.getSingleImplementorType(exactType);
assert exactType.equals(strengthenGraphs.getStrengthenStampType(exactType)) : exactType;
if (!oldStamp.isExactType() || !exactType.equals(oldType)) {
if (typePredicate.test(exactType)) {
TypeReference typeRef = TypeReference.createExactTrusted(exactType);
return StampFactory.object(typeRef, nonNull);
}
}
} else if (!oldStamp.isExactType()) {
assert typeStateTypes.size() > 1 : typeStateTypes;
AnalysisType baseType = typeStateTypes.get(0);
for (int i = 1; i < typeStateTypes.size(); i++) {
if (baseType.isJavaLangObject()) {
break;
}
baseType = baseType.findLeastCommonAncestor(typeStateTypes.get(i));
}
if (oldType != null && !oldType.isAssignableFrom(baseType)) {
/*
* When the original stamp is an interface type, we do not want to weaken that type
* with the common base class of all implementation types (which could even be
* java.lang.Object).
*/
baseType = oldType;
}
/*
* With more than one type in the type state, there cannot be a single implementor.
* Because that single implementor would need to be the only type in the type state.
*/
assert strengthenGraphs.getSingleImplementorType(baseType) == null || baseType.equals(strengthenGraphs.getSingleImplementorType(baseType)) : "baseType=" + baseType +
", singleImplementor=" + strengthenGraphs.getSingleImplementorType(baseType);
AnalysisType newType = strengthenGraphs.getStrengthenStampType(baseType);
assert typeStateTypes.stream().map(newType::isAssignableFrom).reduce(Boolean::logicalAnd).get() : typeStateTypes;
if (!newType.equals(oldType) && (oldType != null || !newType.isJavaLangObject())) {
if (typePredicate.test(newType)) {
TypeReference typeRef = TypeReference.createTrustedWithoutAssumptions(newType);
return StampFactory.object(typeRef, nonNull);
}
}
}
if (nonNull != oldStamp.nonNull()) {
assert nonNull : oldStamp;
return oldStamp.asNonNull();
}
/* Nothing to strengthen. */
return null;
}
private IntegerStamp getIntegerStamp(ValueNode node, IntegerStamp originalStamp, FixedWithNextNode anchorPoint, TypeState nodeTypeState, SimplifierTool tool) {
assert analysis.trackPrimitiveValues() : nodeTypeState + "," + node + " in " + node.graph();
assert nodeTypeState != null && (nodeTypeState.isEmpty() || nodeTypeState.isPrimitive()) : nodeTypeState + "," + node + " in " + node.graph();
if (nodeTypeState.isEmpty()) {
super.makeUnreachable(anchorPoint.next(), tool, () -> super.location(node) + ": empty primitive type state when strengthening oldStamp " + originalStamp);
unreachableValues.add(node);
return null;
}
if (nodeTypeState instanceof PrimitiveConstantTypeState constantTypeState) {
long constantValue = constantTypeState.getValue();
if (node instanceof ConstantNode constant) {
/*
* Sanity check, verify that what was proven by the analysis is consistent with the
* constant node in the graph.
*/
Constant value = constant.getValue();
assert value instanceof PrimitiveConstant : "Node " + value + " should be a primitive constant when extracting an integer stamp, method " + node.graph().method();
assert ((PrimitiveConstant) value).asLong() == constantValue : "The actual value of node: " + value + " is different than the value " + constantValue +
" computed by points-to analysis, method in " + node.graph().method();
} else {
return IntegerStamp.createConstant(originalStamp.getBits(), constantValue);
}
}
return null;
}
}
|
googleapis/google-cloud-java | 37,522 | java-translate/proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/GlossaryInputConfig.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/translate/v3/translation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.translate.v3;
/**
*
*
* <pre>
* Input configuration for glossaries.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.GlossaryInputConfig}
*/
public final class GlossaryInputConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.translation.v3.GlossaryInputConfig)
GlossaryInputConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use GlossaryInputConfig.newBuilder() to construct.
private GlossaryInputConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GlossaryInputConfig() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GlossaryInputConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.TranslationServiceProto
.internal_static_google_cloud_translation_v3_GlossaryInputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.TranslationServiceProto
.internal_static_google_cloud_translation_v3_GlossaryInputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.GlossaryInputConfig.class,
com.google.cloud.translate.v3.GlossaryInputConfig.Builder.class);
}
private int sourceCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object source_;
public enum SourceCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
GCS_SOURCE(1),
SOURCE_NOT_SET(0);
private final int value;
private SourceCase(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 SourceCase valueOf(int value) {
return forNumber(value);
}
public static SourceCase forNumber(int value) {
switch (value) {
case 1:
return GCS_SOURCE;
case 0:
return SOURCE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public static final int GCS_SOURCE_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.translate.v3.GcsSource getGcsSource() {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3.GcsSource) source_;
}
return com.google.cloud.translate.v3.GcsSource.getDefaultInstance();
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3.GcsSource) source_;
}
return com.google.cloud.translate.v3.GcsSource.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 (sourceCase_ == 1) {
output.writeMessage(1, (com.google.cloud.translate.v3.GcsSource) source_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (sourceCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.translate.v3.GcsSource) source_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.translate.v3.GlossaryInputConfig)) {
return super.equals(obj);
}
com.google.cloud.translate.v3.GlossaryInputConfig other =
(com.google.cloud.translate.v3.GlossaryInputConfig) obj;
if (!getSourceCase().equals(other.getSourceCase())) return false;
switch (sourceCase_) {
case 1:
if (!getGcsSource().equals(other.getGcsSource())) 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 (sourceCase_) {
case 1:
hash = (37 * hash) + GCS_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getGcsSource().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.GlossaryInputConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.translate.v3.GlossaryInputConfig 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>
* Input configuration for glossaries.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.GlossaryInputConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.translation.v3.GlossaryInputConfig)
com.google.cloud.translate.v3.GlossaryInputConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.TranslationServiceProto
.internal_static_google_cloud_translation_v3_GlossaryInputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.TranslationServiceProto
.internal_static_google_cloud_translation_v3_GlossaryInputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.GlossaryInputConfig.class,
com.google.cloud.translate.v3.GlossaryInputConfig.Builder.class);
}
// Construct using com.google.cloud.translate.v3.GlossaryInputConfig.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (gcsSourceBuilder_ != null) {
gcsSourceBuilder_.clear();
}
sourceCase_ = 0;
source_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.translate.v3.TranslationServiceProto
.internal_static_google_cloud_translation_v3_GlossaryInputConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.translate.v3.GlossaryInputConfig getDefaultInstanceForType() {
return com.google.cloud.translate.v3.GlossaryInputConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.translate.v3.GlossaryInputConfig build() {
com.google.cloud.translate.v3.GlossaryInputConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.translate.v3.GlossaryInputConfig buildPartial() {
com.google.cloud.translate.v3.GlossaryInputConfig result =
new com.google.cloud.translate.v3.GlossaryInputConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.translate.v3.GlossaryInputConfig result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.cloud.translate.v3.GlossaryInputConfig result) {
result.sourceCase_ = sourceCase_;
result.source_ = this.source_;
if (sourceCase_ == 1 && gcsSourceBuilder_ != null) {
result.source_ = gcsSourceBuilder_.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.translate.v3.GlossaryInputConfig) {
return mergeFrom((com.google.cloud.translate.v3.GlossaryInputConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.translate.v3.GlossaryInputConfig other) {
if (other == com.google.cloud.translate.v3.GlossaryInputConfig.getDefaultInstance())
return this;
switch (other.getSourceCase()) {
case GCS_SOURCE:
{
mergeGcsSource(other.getGcsSource());
break;
}
case SOURCE_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(getGcsSourceFieldBuilder().getBuilder(), extensionRegistry);
sourceCase_ = 1;
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 sourceCase_ = 0;
private java.lang.Object source_;
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public Builder clearSource() {
sourceCase_ = 0;
source_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.translate.v3.GcsSource,
com.google.cloud.translate.v3.GcsSource.Builder,
com.google.cloud.translate.v3.GcsSourceOrBuilder>
gcsSourceBuilder_;
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.translate.v3.GcsSource getGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3.GcsSource) source_;
}
return com.google.cloud.translate.v3.GcsSource.getDefaultInstance();
} else {
if (sourceCase_ == 1) {
return gcsSourceBuilder_.getMessage();
}
return com.google.cloud.translate.v3.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(com.google.cloud.translate.v3.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
source_ = value;
onChanged();
} else {
gcsSourceBuilder_.setMessage(value);
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(com.google.cloud.translate.v3.GcsSource.Builder builderForValue) {
if (gcsSourceBuilder_ == null) {
source_ = builderForValue.build();
onChanged();
} else {
gcsSourceBuilder_.setMessage(builderForValue.build());
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
public Builder mergeGcsSource(com.google.cloud.translate.v3.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1
&& source_ != com.google.cloud.translate.v3.GcsSource.getDefaultInstance()) {
source_ =
com.google.cloud.translate.v3.GcsSource.newBuilder(
(com.google.cloud.translate.v3.GcsSource) source_)
.mergeFrom(value)
.buildPartial();
} else {
source_ = value;
}
onChanged();
} else {
if (sourceCase_ == 1) {
gcsSourceBuilder_.mergeFrom(value);
} else {
gcsSourceBuilder_.setMessage(value);
}
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
public Builder clearGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
onChanged();
}
} else {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
}
gcsSourceBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
public com.google.cloud.translate.v3.GcsSource.Builder getGcsSourceBuilder() {
return getGcsSourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if ((sourceCase_ == 1) && (gcsSourceBuilder_ != null)) {
return gcsSourceBuilder_.getMessageOrBuilder();
} else {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3.GcsSource) source_;
}
return com.google.cloud.translate.v3.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* No headers in this file. The first row contains data and not column
* names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3.GcsSource gcs_source = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.translate.v3.GcsSource,
com.google.cloud.translate.v3.GcsSource.Builder,
com.google.cloud.translate.v3.GcsSourceOrBuilder>
getGcsSourceFieldBuilder() {
if (gcsSourceBuilder_ == null) {
if (!(sourceCase_ == 1)) {
source_ = com.google.cloud.translate.v3.GcsSource.getDefaultInstance();
}
gcsSourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.translate.v3.GcsSource,
com.google.cloud.translate.v3.GcsSource.Builder,
com.google.cloud.translate.v3.GcsSourceOrBuilder>(
(com.google.cloud.translate.v3.GcsSource) source_,
getParentForChildren(),
isClean());
source_ = null;
}
sourceCase_ = 1;
onChanged();
return gcsSourceBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.translation.v3.GlossaryInputConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.translation.v3.GlossaryInputConfig)
private static final com.google.cloud.translate.v3.GlossaryInputConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.translate.v3.GlossaryInputConfig();
}
public static com.google.cloud.translate.v3.GlossaryInputConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GlossaryInputConfig> PARSER =
new com.google.protobuf.AbstractParser<GlossaryInputConfig>() {
@java.lang.Override
public GlossaryInputConfig 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<GlossaryInputConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GlossaryInputConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.translate.v3.GlossaryInputConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,395 | java-billingbudgets/proto-google-cloud-billingbudgets-v1beta1/src/main/java/com/google/cloud/billing/budgets/v1beta1/ListBudgetsResponse.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/billing/budgets/v1beta1/budget_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.billing.budgets.v1beta1;
/**
*
*
* <pre>
* Response for ListBudgets
* </pre>
*
* Protobuf type {@code google.cloud.billing.budgets.v1beta1.ListBudgetsResponse}
*/
public final class ListBudgetsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.billing.budgets.v1beta1.ListBudgetsResponse)
ListBudgetsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListBudgetsResponse.newBuilder() to construct.
private ListBudgetsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListBudgetsResponse() {
budgets_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListBudgetsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.billing.budgets.v1beta1.BudgetServiceOuterClass
.internal_static_google_cloud_billing_budgets_v1beta1_ListBudgetsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.billing.budgets.v1beta1.BudgetServiceOuterClass
.internal_static_google_cloud_billing_budgets_v1beta1_ListBudgetsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.class,
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.Builder.class);
}
public static final int BUDGETS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.billing.budgets.v1beta1.Budget> budgets_;
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.billing.budgets.v1beta1.Budget> getBudgetsList() {
return budgets_;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder>
getBudgetsOrBuilderList() {
return budgets_;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
@java.lang.Override
public int getBudgetsCount() {
return budgets_.size();
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
@java.lang.Override
public com.google.cloud.billing.budgets.v1beta1.Budget getBudgets(int index) {
return budgets_.get(index);
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
@java.lang.Override
public com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder getBudgetsOrBuilder(int index) {
return budgets_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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 < budgets_.size(); i++) {
output.writeMessage(1, budgets_.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 < budgets_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, budgets_.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.billing.budgets.v1beta1.ListBudgetsResponse)) {
return super.equals(obj);
}
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse other =
(com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse) obj;
if (!getBudgetsList().equals(other.getBudgetsList())) 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 (getBudgetsCount() > 0) {
hash = (37 * hash) + BUDGETS_FIELD_NUMBER;
hash = (53 * hash) + getBudgetsList().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.billing.budgets.v1beta1.ListBudgetsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse 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.billing.budgets.v1beta1.ListBudgetsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse 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.billing.budgets.v1beta1.ListBudgetsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse 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.billing.budgets.v1beta1.ListBudgetsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse 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.billing.budgets.v1beta1.ListBudgetsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse 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.billing.budgets.v1beta1.ListBudgetsResponse 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 ListBudgets
* </pre>
*
* Protobuf type {@code google.cloud.billing.budgets.v1beta1.ListBudgetsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.billing.budgets.v1beta1.ListBudgetsResponse)
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.billing.budgets.v1beta1.BudgetServiceOuterClass
.internal_static_google_cloud_billing_budgets_v1beta1_ListBudgetsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.billing.budgets.v1beta1.BudgetServiceOuterClass
.internal_static_google_cloud_billing_budgets_v1beta1_ListBudgetsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.class,
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.Builder.class);
}
// Construct using com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (budgetsBuilder_ == null) {
budgets_ = java.util.Collections.emptyList();
} else {
budgets_ = null;
budgetsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.billing.budgets.v1beta1.BudgetServiceOuterClass
.internal_static_google_cloud_billing_budgets_v1beta1_ListBudgetsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse
getDefaultInstanceForType() {
return com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse build() {
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse buildPartial() {
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse result =
new com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse result) {
if (budgetsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
budgets_ = java.util.Collections.unmodifiableList(budgets_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.budgets_ = budgets_;
} else {
result.budgets_ = budgetsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse 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.billing.budgets.v1beta1.ListBudgetsResponse) {
return mergeFrom((com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse other) {
if (other
== com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse.getDefaultInstance())
return this;
if (budgetsBuilder_ == null) {
if (!other.budgets_.isEmpty()) {
if (budgets_.isEmpty()) {
budgets_ = other.budgets_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureBudgetsIsMutable();
budgets_.addAll(other.budgets_);
}
onChanged();
}
} else {
if (!other.budgets_.isEmpty()) {
if (budgetsBuilder_.isEmpty()) {
budgetsBuilder_.dispose();
budgetsBuilder_ = null;
budgets_ = other.budgets_;
bitField0_ = (bitField0_ & ~0x00000001);
budgetsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getBudgetsFieldBuilder()
: null;
} else {
budgetsBuilder_.addAllMessages(other.budgets_);
}
}
}
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.billing.budgets.v1beta1.Budget m =
input.readMessage(
com.google.cloud.billing.budgets.v1beta1.Budget.parser(),
extensionRegistry);
if (budgetsBuilder_ == null) {
ensureBudgetsIsMutable();
budgets_.add(m);
} else {
budgetsBuilder_.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.billing.budgets.v1beta1.Budget> budgets_ =
java.util.Collections.emptyList();
private void ensureBudgetsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
budgets_ =
new java.util.ArrayList<com.google.cloud.billing.budgets.v1beta1.Budget>(budgets_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.billing.budgets.v1beta1.Budget,
com.google.cloud.billing.budgets.v1beta1.Budget.Builder,
com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder>
budgetsBuilder_;
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public java.util.List<com.google.cloud.billing.budgets.v1beta1.Budget> getBudgetsList() {
if (budgetsBuilder_ == null) {
return java.util.Collections.unmodifiableList(budgets_);
} else {
return budgetsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public int getBudgetsCount() {
if (budgetsBuilder_ == null) {
return budgets_.size();
} else {
return budgetsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public com.google.cloud.billing.budgets.v1beta1.Budget getBudgets(int index) {
if (budgetsBuilder_ == null) {
return budgets_.get(index);
} else {
return budgetsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder setBudgets(int index, com.google.cloud.billing.budgets.v1beta1.Budget value) {
if (budgetsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureBudgetsIsMutable();
budgets_.set(index, value);
onChanged();
} else {
budgetsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder setBudgets(
int index, com.google.cloud.billing.budgets.v1beta1.Budget.Builder builderForValue) {
if (budgetsBuilder_ == null) {
ensureBudgetsIsMutable();
budgets_.set(index, builderForValue.build());
onChanged();
} else {
budgetsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder addBudgets(com.google.cloud.billing.budgets.v1beta1.Budget value) {
if (budgetsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureBudgetsIsMutable();
budgets_.add(value);
onChanged();
} else {
budgetsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder addBudgets(int index, com.google.cloud.billing.budgets.v1beta1.Budget value) {
if (budgetsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureBudgetsIsMutable();
budgets_.add(index, value);
onChanged();
} else {
budgetsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder addBudgets(
com.google.cloud.billing.budgets.v1beta1.Budget.Builder builderForValue) {
if (budgetsBuilder_ == null) {
ensureBudgetsIsMutable();
budgets_.add(builderForValue.build());
onChanged();
} else {
budgetsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder addBudgets(
int index, com.google.cloud.billing.budgets.v1beta1.Budget.Builder builderForValue) {
if (budgetsBuilder_ == null) {
ensureBudgetsIsMutable();
budgets_.add(index, builderForValue.build());
onChanged();
} else {
budgetsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder addAllBudgets(
java.lang.Iterable<? extends com.google.cloud.billing.budgets.v1beta1.Budget> values) {
if (budgetsBuilder_ == null) {
ensureBudgetsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, budgets_);
onChanged();
} else {
budgetsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder clearBudgets() {
if (budgetsBuilder_ == null) {
budgets_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
budgetsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public Builder removeBudgets(int index) {
if (budgetsBuilder_ == null) {
ensureBudgetsIsMutable();
budgets_.remove(index);
onChanged();
} else {
budgetsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public com.google.cloud.billing.budgets.v1beta1.Budget.Builder getBudgetsBuilder(int index) {
return getBudgetsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder getBudgetsOrBuilder(int index) {
if (budgetsBuilder_ == null) {
return budgets_.get(index);
} else {
return budgetsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public java.util.List<? extends com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder>
getBudgetsOrBuilderList() {
if (budgetsBuilder_ != null) {
return budgetsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(budgets_);
}
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public com.google.cloud.billing.budgets.v1beta1.Budget.Builder addBudgetsBuilder() {
return getBudgetsFieldBuilder()
.addBuilder(com.google.cloud.billing.budgets.v1beta1.Budget.getDefaultInstance());
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public com.google.cloud.billing.budgets.v1beta1.Budget.Builder addBudgetsBuilder(int index) {
return getBudgetsFieldBuilder()
.addBuilder(index, com.google.cloud.billing.budgets.v1beta1.Budget.getDefaultInstance());
}
/**
*
*
* <pre>
* List of the budgets owned by the requested billing account.
* </pre>
*
* <code>repeated .google.cloud.billing.budgets.v1beta1.Budget budgets = 1;</code>
*/
public java.util.List<com.google.cloud.billing.budgets.v1beta1.Budget.Builder>
getBudgetsBuilderList() {
return getBudgetsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.billing.budgets.v1beta1.Budget,
com.google.cloud.billing.budgets.v1beta1.Budget.Builder,
com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder>
getBudgetsFieldBuilder() {
if (budgetsBuilder_ == null) {
budgetsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.billing.budgets.v1beta1.Budget,
com.google.cloud.billing.budgets.v1beta1.Budget.Builder,
com.google.cloud.billing.budgets.v1beta1.BudgetOrBuilder>(
budgets_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
budgets_ = null;
}
return budgetsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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>
* If not empty, indicates that there may be more budgets that match the
* request; this value should be passed in a new `ListBudgetsRequest`.
* </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.billing.budgets.v1beta1.ListBudgetsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.billing.budgets.v1beta1.ListBudgetsResponse)
private static final com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse();
}
public static com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListBudgetsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListBudgetsResponse>() {
@java.lang.Override
public ListBudgetsResponse 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<ListBudgetsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListBudgetsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.billing.budgets.v1beta1.ListBudgetsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,339 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ViewIndexedAssetsRequest.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>
* Request message for ViewIndexedAssets.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ViewIndexedAssetsRequest}
*/
public final class ViewIndexedAssetsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ViewIndexedAssetsRequest)
ViewIndexedAssetsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ViewIndexedAssetsRequest.newBuilder() to construct.
private ViewIndexedAssetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ViewIndexedAssetsRequest() {
index_ = "";
pageToken_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ViewIndexedAssetsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ViewIndexedAssetsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ViewIndexedAssetsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.class,
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.Builder.class);
}
public static final int INDEX_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object index_ = "";
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The index.
*/
@java.lang.Override
public java.lang.String getIndex() {
java.lang.Object ref = index_;
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();
index_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for index.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIndexBytes() {
java.lang.Object ref = index_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
index_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of assets to return. The service may return fewer than
* this value.
* If unspecified, at most 50 assets will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(index_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, index_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(index_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, index_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.ViewIndexedAssetsRequest)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest other =
(com.google.cloud.visionai.v1.ViewIndexedAssetsRequest) obj;
if (!getIndex().equals(other.getIndex())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + INDEX_FIELD_NUMBER;
hash = (53 * hash) + getIndex().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest 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.ViewIndexedAssetsRequest 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 ViewIndexedAssets.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ViewIndexedAssetsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ViewIndexedAssetsRequest)
com.google.cloud.visionai.v1.ViewIndexedAssetsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ViewIndexedAssetsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ViewIndexedAssetsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.class,
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
index_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
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_ViewIndexedAssetsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ViewIndexedAssetsRequest getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.ViewIndexedAssetsRequest build() {
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ViewIndexedAssetsRequest buildPartial() {
com.google.cloud.visionai.v1.ViewIndexedAssetsRequest result =
new com.google.cloud.visionai.v1.ViewIndexedAssetsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.ViewIndexedAssetsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.index_ = index_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.ViewIndexedAssetsRequest) {
return mergeFrom((com.google.cloud.visionai.v1.ViewIndexedAssetsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.ViewIndexedAssetsRequest other) {
if (other == com.google.cloud.visionai.v1.ViewIndexedAssetsRequest.getDefaultInstance())
return this;
if (!other.getIndex().isEmpty()) {
index_ = other.index_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
index_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object index_ = "";
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The index.
*/
public java.lang.String getIndex() {
java.lang.Object ref = index_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
index_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for index.
*/
public com.google.protobuf.ByteString getIndexBytes() {
java.lang.Object ref = index_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
index_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The index to set.
* @return This builder for chaining.
*/
public Builder setIndex(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
index_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearIndex() {
index_ = getDefaultInstance().getIndex();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The index that owns this collection of assets.
* Format:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/indexes/{index}`
* </pre>
*
* <code>
* string index = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for index to set.
* @return This builder for chaining.
*/
public Builder setIndexBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
index_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of assets to return. The service may return fewer than
* this value.
* If unspecified, at most 50 assets will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of assets to return. The service may return fewer than
* this value.
* If unspecified, at most 50 assets will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of assets to return. The service may return fewer than
* this value.
* If unspecified, at most 50 assets will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous `ViewIndexedAssets` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ViewIndexedAssets` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* The filter applied to the returned list.
* Only the following filterings are supported:
* "asset_id = xxxx", which returns asset with specified id.
* "asset_id = xxxx, yyyy, zzzz", which returns assets with specified ids.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ViewIndexedAssetsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ViewIndexedAssetsRequest)
private static final com.google.cloud.visionai.v1.ViewIndexedAssetsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ViewIndexedAssetsRequest();
}
public static com.google.cloud.visionai.v1.ViewIndexedAssetsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ViewIndexedAssetsRequest> PARSER =
new com.google.protobuf.AbstractParser<ViewIndexedAssetsRequest>() {
@java.lang.Override
public ViewIndexedAssetsRequest 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<ViewIndexedAssetsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ViewIndexedAssetsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ViewIndexedAssetsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 37,611 | jaxp/src/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xerces.internal.impl.xs.opti;
import java.io.IOException;
import java.util.Locale;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.XML11DTDScannerImpl;
import com.sun.org.apache.xerces.internal.impl.XML11NSDocumentScannerImpl;
import com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl;
import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
import com.sun.org.apache.xerces.internal.impl.XMLEntityManager;
import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
import com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl;
import com.sun.org.apache.xerces.internal.impl.XMLVersionDetector;
import com.sun.org.apache.xerces.internal.impl.dv.DTDDVFactory;
import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
import com.sun.org.apache.xerces.internal.impl.xs.XSMessageFormatter;
import com.sun.org.apache.xerces.internal.parsers.BasicParserConfiguration;
import com.sun.org.apache.xerces.internal.util.FeatureState;
import com.sun.org.apache.xerces.internal.util.PropertyState;
import com.sun.org.apache.xerces.internal.util.Status;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.xni.XMLLocator;
import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.grammars.XMLGrammarPool;
import com.sun.org.apache.xerces.internal.xni.parser.XMLComponent;
import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
import com.sun.org.apache.xerces.internal.xni.parser.XMLDTDScanner;
import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentScanner;
import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
import com.sun.org.apache.xerces.internal.xni.parser.XMLPullParserConfiguration;
/**
* @xerces.internal
*
* @author Rahul Srivastava, Sun Microsystems Inc.
*
* @version $Id: SchemaParsingConfig.java,v 1.8 2010-11-01 04:40:01 joehw Exp $
*/
public class SchemaParsingConfig extends BasicParserConfiguration
implements XMLPullParserConfiguration {
//
// Constants
//
protected final static String XML11_DATATYPE_VALIDATOR_FACTORY =
"com.sun.org.apache.xerces.internal.impl.dv.dtd.XML11DTDDVFactoryImpl";
// feature identifiers
/** Feature identifier: warn on duplicate attribute definition. */
protected static final String WARN_ON_DUPLICATE_ATTDEF =
Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ATTDEF_FEATURE;
/** Feature identifier: warn on duplicate entity definition. */
// protected static final String WARN_ON_DUPLICATE_ENTITYDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE;
/** Feature identifier: warn on undeclared element definition. */
protected static final String WARN_ON_UNDECLARED_ELEMDEF =
Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_UNDECLARED_ELEMDEF_FEATURE;
/** Feature identifier: allow Java encodings. */
protected static final String ALLOW_JAVA_ENCODINGS =
Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE;
/** Feature identifier: continue after fatal error. */
protected static final String CONTINUE_AFTER_FATAL_ERROR =
Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE;
/** Feature identifier: load external DTD. */
protected static final String LOAD_EXTERNAL_DTD =
Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE;
/** Feature identifier: notify built-in refereces. */
protected static final String NOTIFY_BUILTIN_REFS =
Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_BUILTIN_REFS_FEATURE;
/** Feature identifier: notify character refereces. */
protected static final String NOTIFY_CHAR_REFS =
Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_CHAR_REFS_FEATURE;
/** Feature identifier: expose schema normalized value */
protected static final String NORMALIZE_DATA =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE;
/** Feature identifier: send element default value via characters() */
protected static final String SCHEMA_ELEMENT_DEFAULT =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT;
/** Feature identifier: generate synthetic annotations. */
protected static final String GENERATE_SYNTHETIC_ANNOTATIONS =
Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE;
// property identifiers
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: entity manager. */
protected static final String ENTITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
/** Property identifier document scanner: */
protected static final String DOCUMENT_SCANNER =
Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_SCANNER_PROPERTY;
/** Property identifier: DTD scanner. */
protected static final String DTD_SCANNER =
Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_SCANNER_PROPERTY;
/** Property identifier: grammar pool. */
protected static final String XMLGRAMMAR_POOL =
Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
/** Property identifier: DTD validator. */
protected static final String DTD_VALIDATOR =
Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_VALIDATOR_PROPERTY;
/** Property identifier: namespace binder. */
protected static final String NAMESPACE_BINDER =
Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_BINDER_PROPERTY;
/** Property identifier: datatype validator factory. */
protected static final String DATATYPE_VALIDATOR_FACTORY =
Constants.XERCES_PROPERTY_PREFIX + Constants.DATATYPE_VALIDATOR_FACTORY_PROPERTY;
protected static final String VALIDATION_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
/** Property identifier: XML Schema validator. */
protected static final String SCHEMA_VALIDATOR =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY;
/** Property identifier: locale. */
protected static final String LOCALE =
Constants.XERCES_PROPERTY_PREFIX + Constants.LOCALE_PROPERTY;
// debugging
/** Set to true and recompile to print exception stack trace. */
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
//
// Data
//
//
// XML 1.0 components
//
/** The XML 1.0 Datatype validator factory. */
protected final DTDDVFactory fDatatypeValidatorFactory;
/** The XML 1.0 Document scanner. */
protected final XMLNSDocumentScannerImpl fNamespaceScanner;
/** The XML 1.0 DTD scanner. */
protected final XMLDTDScannerImpl fDTDScanner;
//
// XML 1.1 components
//
/** The XML 1.1 Datatype validator factory. */
protected DTDDVFactory fXML11DatatypeFactory = null;
/** The XML 1.1 Document scanner. */
protected XML11NSDocumentScannerImpl fXML11NSDocScanner = null;
/** The XML 1.1 DTD scanner. **/
protected XML11DTDScannerImpl fXML11DTDScanner = null;
// common components (non-configurable)
/** Current Datatype validator factory. */
protected DTDDVFactory fCurrentDVFactory;
/** Current scanner */
protected XMLDocumentScanner fCurrentScanner;
/** Current DTD scanner. */
protected XMLDTDScanner fCurrentDTDScanner;
/** Grammar pool. */
protected XMLGrammarPool fGrammarPool;
/** XML version detector. */
protected final XMLVersionDetector fVersionDetector;
// common components (configurable)
/** Error reporter. */
protected final XMLErrorReporter fErrorReporter;
/** Entity manager. */
protected final XMLEntityManager fEntityManager;
/** Input Source */
protected XMLInputSource fInputSource;
protected final ValidationManager fValidationManager;
// state
/** Locator */
protected XMLLocator fLocator;
/**
* True if a parse is in progress. This state is needed because
* some features/properties cannot be set while parsing (e.g.
* validation and namespaces).
*/
protected boolean fParseInProgress = false;
/**
* fConfigUpdated is set to true if there has been any change to the configuration settings,
* i.e a feature or a property was changed.
*/
protected boolean fConfigUpdated = false;
/** Flag indiciating whether XML11 components have been initialized. */
private boolean f11Initialized = false;
//
// Constructors
//
/** Default constructor. */
public SchemaParsingConfig() {
this(null, null, null);
} // <init>()
/**
* Constructs a parser configuration using the specified symbol table.
*
* @param symbolTable The symbol table to use.
*/
public SchemaParsingConfig(SymbolTable symbolTable) {
this(symbolTable, null, null);
} // <init>(SymbolTable)
/**
* Constructs a parser configuration using the specified symbol table and
* grammar pool.
* <p>
* <strong>REVISIT:</strong>
* Grammar pool will be updated when the new validation engine is
* implemented.
*
* @param symbolTable The symbol table to use.
* @param grammarPool The grammar pool to use.
*/
public SchemaParsingConfig(SymbolTable symbolTable,
XMLGrammarPool grammarPool) {
this(symbolTable, grammarPool, null);
} // <init>(SymbolTable,XMLGrammarPool)
/**
* Constructs a parser configuration using the specified symbol table,
* grammar pool, and parent settings.
* <p>
* <strong>REVISIT:</strong>
* Grammar pool will be updated when the new validation engine is
* implemented.
*
* @param symbolTable The symbol table to use.
* @param grammarPool The grammar pool to use.
* @param parentSettings The parent settings.
*/
public SchemaParsingConfig(SymbolTable symbolTable,
XMLGrammarPool grammarPool,
XMLComponentManager parentSettings) {
super(symbolTable, parentSettings);
// add default recognized features
final String[] recognizedFeatures = {
PARSER_SETTINGS, WARN_ON_DUPLICATE_ATTDEF, WARN_ON_UNDECLARED_ELEMDEF,
ALLOW_JAVA_ENCODINGS, CONTINUE_AFTER_FATAL_ERROR,
LOAD_EXTERNAL_DTD, NOTIFY_BUILTIN_REFS,
NOTIFY_CHAR_REFS, GENERATE_SYNTHETIC_ANNOTATIONS
};
addRecognizedFeatures(recognizedFeatures);
fFeatures.put(PARSER_SETTINGS, Boolean.TRUE);
// set state for default features
fFeatures.put(WARN_ON_DUPLICATE_ATTDEF, Boolean.FALSE);
//setFeature(WARN_ON_DUPLICATE_ENTITYDEF, false);
fFeatures.put(WARN_ON_UNDECLARED_ELEMDEF, Boolean.FALSE);
fFeatures.put(ALLOW_JAVA_ENCODINGS, Boolean.FALSE);
fFeatures.put(CONTINUE_AFTER_FATAL_ERROR, Boolean.FALSE);
fFeatures.put(LOAD_EXTERNAL_DTD, Boolean.TRUE);
fFeatures.put(NOTIFY_BUILTIN_REFS, Boolean.FALSE);
fFeatures.put(NOTIFY_CHAR_REFS, Boolean.FALSE);
fFeatures.put(GENERATE_SYNTHETIC_ANNOTATIONS, Boolean.FALSE);
// add default recognized properties
final String[] recognizedProperties = {
ERROR_REPORTER,
ENTITY_MANAGER,
DOCUMENT_SCANNER,
DTD_SCANNER,
DTD_VALIDATOR,
NAMESPACE_BINDER,
XMLGRAMMAR_POOL,
DATATYPE_VALIDATOR_FACTORY,
VALIDATION_MANAGER,
GENERATE_SYNTHETIC_ANNOTATIONS,
LOCALE
};
addRecognizedProperties(recognizedProperties);
fGrammarPool = grammarPool;
if (fGrammarPool != null) {
setProperty(XMLGRAMMAR_POOL, fGrammarPool);
}
fEntityManager = new XMLEntityManager();
fProperties.put(ENTITY_MANAGER, fEntityManager);
addComponent(fEntityManager);
fErrorReporter = new XMLErrorReporter();
fErrorReporter.setDocumentLocator(fEntityManager.getEntityScanner());
fProperties.put(ERROR_REPORTER, fErrorReporter);
addComponent(fErrorReporter);
fNamespaceScanner = new XMLNSDocumentScannerImpl();
fProperties.put(DOCUMENT_SCANNER, fNamespaceScanner);
addRecognizedParamsAndSetDefaults(fNamespaceScanner);
fDTDScanner = new XMLDTDScannerImpl();
fProperties.put(DTD_SCANNER, fDTDScanner);
addRecognizedParamsAndSetDefaults(fDTDScanner);
fDatatypeValidatorFactory = DTDDVFactory.getInstance();
fProperties.put(DATATYPE_VALIDATOR_FACTORY,
fDatatypeValidatorFactory);
fValidationManager = new ValidationManager();
fProperties.put(VALIDATION_MANAGER, fValidationManager);
fVersionDetector = new XMLVersionDetector();
// add message formatters
if (fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) {
XMLMessageFormatter xmft = new XMLMessageFormatter();
fErrorReporter.putMessageFormatter(XMLMessageFormatter.XML_DOMAIN, xmft);
fErrorReporter.putMessageFormatter(XMLMessageFormatter.XMLNS_DOMAIN, xmft);
}
if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) {
XSMessageFormatter xmft = new XSMessageFormatter();
fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, xmft);
}
// set locale
try {
setLocale(Locale.getDefault());
}
catch (XNIException e) {
// do nothing
// REVISIT: What is the right thing to do? -Ac
}
} // <init>(SymbolTable,XMLGrammarPool)
//
// Public methods
//
/**
* Returns the state of a feature.
*
* @param featureId The feature identifier.
* @return true if the feature is supported
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
public FeatureState getFeatureState(String featureId)
throws XMLConfigurationException {
// make this feature special
if (featureId.equals(PARSER_SETTINGS)) {
return FeatureState.is(fConfigUpdated);
}
return super.getFeatureState(featureId);
} // getFeature(String):boolean
/**
* Set the state of a feature.
*
* Set the state of any feature in a SAX2 parser. The parser
* might not recognize the feature, and if it does recognize
* it, it might not be able to fulfill the request.
*
* @param featureId The unique identifier (URI) of the feature.
* @param state The requested state of the feature (true or false).
*
* @exception com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException If the
* requested feature is not known.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
fConfigUpdated = true;
// forward to every XML 1.0 component
fNamespaceScanner.setFeature(featureId, state);
fDTDScanner.setFeature(featureId, state);
// forward to every XML 1.1 component
if (f11Initialized) {
try {
fXML11DTDScanner.setFeature(featureId, state);
}
// ignore the exception.
catch (Exception e) {}
try {
fXML11NSDocScanner.setFeature(featureId, state);
}
// ignore the exception
catch (Exception e) {}
}
// save state if noone "objects"
super.setFeature(featureId, state);
} // setFeature(String,boolean)
/**
* Returns the value of a property.
*
* @param propertyId The property identifier.
* @return the value of the property
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
public PropertyState getPropertyState(String propertyId)
throws XMLConfigurationException {
if (LOCALE.equals(propertyId)) {
return PropertyState.is(getLocale());
}
return super.getPropertyState(propertyId);
}
/**
* setProperty
*
* @param propertyId
* @param value
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
fConfigUpdated = true;
if (LOCALE.equals(propertyId)) {
setLocale((Locale) value);
}
// forward to every XML 1.0 component
fNamespaceScanner.setProperty(propertyId, value);
fDTDScanner.setProperty(propertyId, value);
// forward to every XML 1.1 component
if (f11Initialized) {
try {
fXML11DTDScanner.setProperty(propertyId, value);
}
// ignore the exception.
catch (Exception e) {}
try {
fXML11NSDocScanner.setProperty(propertyId, value);
}
// ignore the exception
catch (Exception e) {}
}
// store value if noone "objects"
super.setProperty(propertyId, value);
} // setProperty(String,Object)
/**
* Set the locale to use for messages.
*
* @param locale The locale object to use for localization of messages.
*
* @exception XNIException Thrown if the parser does not support the
* specified locale.
*/
public void setLocale(Locale locale) throws XNIException {
super.setLocale(locale);
fErrorReporter.setLocale(locale);
} // setLocale(Locale)
//
// XMLPullParserConfiguration methods
//
// parsing
/**
* Sets the input source for the document to parse.
*
* @param inputSource The document's input source.
*
* @exception XMLConfigurationException Thrown if there is a
* configuration error when initializing the
* parser.
* @exception IOException Thrown on I/O error.
*
* @see #parse(boolean)
*/
public void setInputSource(XMLInputSource inputSource)
throws XMLConfigurationException, IOException {
// REVISIT: this method used to reset all the components and
// construct the pipeline. Now reset() is called
// in parse (boolean) just before we parse the document
// Should this method still throw exceptions..?
fInputSource = inputSource;
} // setInputSource(XMLInputSource)
/**
* Parses the document in a pull parsing fashion.
*
* @param complete True if the pull parser should parse the
* remaining document completely.
*
* @return True if there is more document to parse.
*
* @exception XNIException Any XNI exception, possibly wrapping
* another exception.
* @exception IOException An IO exception from the parser, possibly
* from a byte stream or character stream
* supplied by the parser.
*
* @see #setInputSource
*/
public boolean parse(boolean complete) throws XNIException, IOException {
//
// reset and configure pipeline and set InputSource.
if (fInputSource != null) {
try {
fValidationManager.reset();
fVersionDetector.reset(this);
reset();
short version = fVersionDetector.determineDocVersion(fInputSource);
// XML 1.0
if (version == Constants.XML_VERSION_1_0) {
configurePipeline();
resetXML10();
}
// XML 1.1
else if (version == Constants.XML_VERSION_1_1) {
initXML11Components();
configureXML11Pipeline();
resetXML11();
}
// Unrecoverable error reported during version detection
else {
return false;
}
// mark configuration as fixed
fConfigUpdated = false;
// resets and sets the pipeline.
fVersionDetector.startDocumentParsing((XMLEntityHandler) fCurrentScanner, version);
fInputSource = null;
}
catch (XNIException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (IOException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (RuntimeException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (Exception ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw new XNIException(ex);
}
}
try {
return fCurrentScanner.scanDocument(complete);
}
catch (XNIException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (IOException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (RuntimeException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (Exception ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw new XNIException(ex);
}
} // parse(boolean):boolean
/**
* If the application decides to terminate parsing before the xml document
* is fully parsed, the application should call this method to free any
* resource allocated during parsing. For example, close all opened streams.
*/
public void cleanup() {
fEntityManager.closeReaders();
}
//
// XMLParserConfiguration methods
//
/**
* Parses the specified input source.
*
* @param source The input source.
*
* @exception XNIException Throws exception on XNI error.
* @exception java.io.IOException Throws exception on i/o error.
*/
public void parse(XMLInputSource source) throws XNIException, IOException {
if (fParseInProgress) {
// REVISIT - need to add new error message
throw new XNIException("FWK005 parse may not be called while parsing.");
}
fParseInProgress = true;
try {
setInputSource(source);
parse(true);
}
catch (XNIException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (IOException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (RuntimeException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
}
catch (Exception ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw new XNIException(ex);
}
finally {
fParseInProgress = false;
// close all streams opened by xerces
this.cleanup();
}
} // parse(InputSource)
//
// Protected methods
//
/**
* Reset all components before parsing.
*
* @throws XNIException Thrown if an error occurs during initialization.
*/
public void reset() throws XNIException {
// initialize the common components
super.reset();
} // reset()
/** Configures the XML 1.0 pipeline. */
protected void configurePipeline() {
if (fCurrentDVFactory != fDatatypeValidatorFactory) {
fCurrentDVFactory = fDatatypeValidatorFactory;
// use XML 1.0 datatype library
setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory);
}
// setup document pipeline
if (fCurrentScanner != fNamespaceScanner) {
fCurrentScanner = fNamespaceScanner;
setProperty(DOCUMENT_SCANNER, fCurrentScanner);
}
fNamespaceScanner.setDocumentHandler(fDocumentHandler);
if (fDocumentHandler != null) {
fDocumentHandler.setDocumentSource(fNamespaceScanner);
}
fLastComponent = fNamespaceScanner;
// setup dtd pipeline
if (fCurrentDTDScanner != fDTDScanner) {
fCurrentDTDScanner = fDTDScanner;
setProperty(DTD_SCANNER, fCurrentDTDScanner);
}
fDTDScanner.setDTDHandler(fDTDHandler);
if (fDTDHandler != null) {
fDTDHandler.setDTDSource(fDTDScanner);
}
fDTDScanner.setDTDContentModelHandler(fDTDContentModelHandler);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.setDTDContentModelSource(fDTDScanner);
}
} // configurePipeline()
/** Configures the XML 1.1 pipeline. */
protected void configureXML11Pipeline() {
if (fCurrentDVFactory != fXML11DatatypeFactory) {
fCurrentDVFactory = fXML11DatatypeFactory;
// use XML 1.1 datatype library
setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory);
}
// setup document pipeline
if (fCurrentScanner != fXML11NSDocScanner) {
fCurrentScanner = fXML11NSDocScanner;
setProperty(DOCUMENT_SCANNER, fCurrentScanner);
}
fXML11NSDocScanner.setDocumentHandler(fDocumentHandler);
if (fDocumentHandler != null) {
fDocumentHandler.setDocumentSource(fXML11NSDocScanner);
}
fLastComponent = fXML11NSDocScanner;
// setup dtd pipeline
if (fCurrentDTDScanner != fXML11DTDScanner) {
fCurrentDTDScanner = fXML11DTDScanner;
setProperty(DTD_SCANNER, fCurrentDTDScanner);
}
fXML11DTDScanner.setDTDHandler(fDTDHandler);
if (fDTDHandler != null) {
fDTDHandler.setDTDSource(fXML11DTDScanner);
}
fXML11DTDScanner.setDTDContentModelHandler(fDTDContentModelHandler);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.setDTDContentModelSource(fXML11DTDScanner);
}
} // configureXML11Pipeline()
// features and properties
/**
* Check a feature. If feature is know and supported, this method simply
* returns. Otherwise, the appropriate exception is thrown.
*
* @param featureId The unique identifier (URI) of the feature.
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
protected FeatureState checkFeature(String featureId)
throws XMLConfigurationException {
//
// Xerces Features
//
if (featureId.startsWith(Constants.XERCES_FEATURE_PREFIX)) {
final int suffixLength = featureId.length() - Constants.XERCES_FEATURE_PREFIX.length();
//
// http://apache.org/xml/features/validation/dynamic
// Allows the parser to validate a document only when it
// contains a grammar. Validation is turned on/off based
// on each document instance, automatically.
//
if (suffixLength == Constants.DYNAMIC_VALIDATION_FEATURE.length() &&
featureId.endsWith(Constants.DYNAMIC_VALIDATION_FEATURE)) {
return FeatureState.RECOGNIZED;
}
//
// http://apache.org/xml/features/validation/default-attribute-values
//
if (suffixLength == Constants.DEFAULT_ATTRIBUTE_VALUES_FEATURE.length() &&
featureId.endsWith(Constants.DEFAULT_ATTRIBUTE_VALUES_FEATURE)) {
// REVISIT
return FeatureState.NOT_SUPPORTED;
}
//
// http://apache.org/xml/features/validation/default-attribute-values
//
if (suffixLength == Constants.VALIDATE_CONTENT_MODELS_FEATURE.length() &&
featureId.endsWith(Constants.VALIDATE_CONTENT_MODELS_FEATURE)) {
// REVISIT
return FeatureState.NOT_SUPPORTED;
}
//
// http://apache.org/xml/features/validation/nonvalidating/load-dtd-grammar
//
if (suffixLength == Constants.LOAD_DTD_GRAMMAR_FEATURE.length() &&
featureId.endsWith(Constants.LOAD_DTD_GRAMMAR_FEATURE)) {
return FeatureState.RECOGNIZED;
}
//
// http://apache.org/xml/features/validation/nonvalidating/load-external-dtd
//
if (suffixLength == Constants.LOAD_EXTERNAL_DTD_FEATURE.length() &&
featureId.endsWith(Constants.LOAD_EXTERNAL_DTD_FEATURE)) {
return FeatureState.RECOGNIZED;
}
//
// http://apache.org/xml/features/validation/default-attribute-values
//
if (suffixLength == Constants.VALIDATE_DATATYPES_FEATURE.length() &&
featureId.endsWith(Constants.VALIDATE_DATATYPES_FEATURE)) {
return FeatureState.NOT_SUPPORTED;
}
}
//
// Not recognized
//
return super.checkFeature(featureId);
} // checkFeature(String)
/**
* Check a property. If the property is know and supported, this method
* simply returns. Otherwise, the appropriate exception is thrown.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
protected PropertyState checkProperty(String propertyId)
throws XMLConfigurationException {
//
// Xerces Properties
//
if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) {
final int suffixLength = propertyId.length() - Constants.XERCES_PROPERTY_PREFIX.length();
if (suffixLength == Constants.DTD_SCANNER_PROPERTY.length() &&
propertyId.endsWith(Constants.DTD_SCANNER_PROPERTY)) {
return PropertyState.RECOGNIZED;
}
}
if (propertyId.startsWith(Constants.JAXP_PROPERTY_PREFIX)) {
final int suffixLength = propertyId.length() - Constants.JAXP_PROPERTY_PREFIX.length();
if (suffixLength == Constants.SCHEMA_SOURCE.length() &&
propertyId.endsWith(Constants.SCHEMA_SOURCE)) {
return PropertyState.RECOGNIZED;
}
}
//
// Not recognized
//
return super.checkProperty(propertyId);
} // checkProperty(String)
/**
* Adds all of the component's recognized features and properties
* to the list of default recognized features and properties, and
* sets default values on the configuration for features and
* properties which were previously absent from the configuration.
*
* @param component The component whose recognized features
* and properties will be added to the configuration
*/
private void addRecognizedParamsAndSetDefaults(XMLComponent component) {
// register component's recognized features
String[] recognizedFeatures = component.getRecognizedFeatures();
addRecognizedFeatures(recognizedFeatures);
// register component's recognized properties
String[] recognizedProperties = component.getRecognizedProperties();
addRecognizedProperties(recognizedProperties);
// set default values
if (recognizedFeatures != null) {
for (int i = 0; i < recognizedFeatures.length; ++i) {
String featureId = recognizedFeatures[i];
Boolean state = component.getFeatureDefault(featureId);
if (state != null) {
// Do not overwrite values already set on the configuration.
if (!fFeatures.containsKey(featureId)) {
fFeatures.put(featureId, state);
// For newly added components who recognize this feature
// but did not offer a default value, we need to make
// sure these components will get an opportunity to read
// the value before parsing begins.
fConfigUpdated = true;
}
}
}
}
if (recognizedProperties != null) {
for (int i = 0; i < recognizedProperties.length; ++i) {
String propertyId = recognizedProperties[i];
Object value = component.getPropertyDefault(propertyId);
if (value != null) {
// Do not overwrite values already set on the configuration.
if (!fProperties.containsKey(propertyId)) {
fProperties.put(propertyId, value);
// For newly added components who recognize this property
// but did not offer a default value, we need to make
// sure these components will get an opportunity to read
// the value before parsing begins.
fConfigUpdated = true;
}
}
}
}
}
/**
* Reset all XML 1.0 components before parsing
*/
protected final void resetXML10() throws XNIException {
// Reset XML 1.0 components
fNamespaceScanner.reset(this);
fDTDScanner.reset(this);
} // resetXML10()
/**
* Reset all XML 1.1 components before parsing
*/
protected final void resetXML11() throws XNIException {
// Reset XML 1.1 components
fXML11NSDocScanner.reset(this);
fXML11DTDScanner.reset(this);
} // resetXML11()
//
// other methods
//
/** */
public void resetNodePool() {
// REVISIT: to implement: introduce a node pool to reuse DTM nodes.
// reset this pool here.
}
private void initXML11Components() {
if (!f11Initialized) {
// create datatype factory
fXML11DatatypeFactory = DTDDVFactory.getInstance(XML11_DATATYPE_VALIDATOR_FACTORY);
// setup XML 1.1 DTD pipeline
fXML11DTDScanner = new XML11DTDScannerImpl();
addRecognizedParamsAndSetDefaults(fXML11DTDScanner);
// setup XML 1.1. document pipeline - namespace aware
fXML11NSDocScanner = new XML11NSDocumentScannerImpl();
addRecognizedParamsAndSetDefaults(fXML11NSDocScanner);
f11Initialized = true;
}
}
}
|
oracle/coherence | 37,434 | prj/coherence-core-components/src/main/java/com/tangosol/coherence/component/net/message/requestMessage/DistributedCacheRequest.java |
/*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
// ---- class: com.tangosol.coherence.component.net.message.requestMessage.DistributedCacheRequest
package com.tangosol.coherence.component.net.message.requestMessage;
import com.tangosol.coherence.component.net.message.responseMessage.DistributedPartialResponse;
import com.tangosol.coherence.component.net.requestContext.AsyncContext;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.PartitionedService;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache;
import com.tangosol.net.internal.PartitionVersions;
import com.tangosol.net.partition.PartitionSet;
import com.tangosol.util.ExternalizableHelper;
import com.tangosol.util.ThreadGate;
import java.util.List;
/**
* DistributeCacheRequest is a base component for RequestMessage(s) used by the
* partitioned cache service that are key set or filter based. Quite often a
* collection of similar requests are sent in parallel and a client thread has
* to wait for all of them to return.
*/
@SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"})
public class DistributedCacheRequest
extends com.tangosol.coherence.component.net.message.RequestMessage
implements com.tangosol.net.PriorityTask,
com.tangosol.net.cache.KeyAssociation,
Runnable
{
// ---- Fields declarations ----
/**
* Property CacheId
*
* The Id of the cache this request is for.
*/
private long __m_CacheId;
/**
* Property ExecutionTimeoutMillis
*
* From PriorityTask interface.
*/
private long __m_ExecutionTimeoutMillis;
/**
* Property OrderId
*
* Unit-of-order id for asynchronous agents. This value is zero for
* synchronous requests.
*
* @see com.tangosol.util.processor.AsynchronousProcessor,
* com.tangosol.util.aggregator.AsynchronousAggregator
*/
private long __m_OrderId;
/**
* Property OwnershipVersions
*
* The ownership versions of the partitions associated with this Request
* (from the client's point of view).
*
* Used for AsyncOperations only.
*/
private com.tangosol.net.internal.PartitionVersions __m_OwnershipVersions;
/**
* Property PartResults
*
* Transient list of partial results returned by [storage-enabled] service
* members that processed this request. Most commonly the elements of this
* list are DistributedPartialResponse messages.
*/
private transient java.util.List __m_PartResults;
/**
* Property ProcessedPartitions
*
* The set of partitions processed by this request.
*
* This transient property is optional, and is filled in only after the
* request is processed.
*/
private com.tangosol.net.partition.PartitionSet __m_ProcessedPartitions;
/**
* Property ReadException
*
* (Transient) An Exception that occurred during the read() and had to be
* deferred to be processed during onReceived() ans possibly reported back
* to the client (requestor). Usually it is an IOException, but for
* technical reasons could also be a ClassCastException.
*
* See COH-2150 for details.
*/
private transient Exception __m_ReadException;
/**
* Property RequestTimeoutMillis
*
* From PriorityTask interface.
*/
private long __m_RequestTimeoutMillis;
/**
* Property SchedulingPriority
*
* From PriorityTask interface.
*/
private int __m_SchedulingPriority;
private static com.tangosol.util.ListMap __mapChildren;
/**
* Property RepliesMask
*
* Keep track of replies against request mask while keeping the latter safe.
*
* This property is not serialized, it is only used locally.
*/
private transient PartitionSet __m_RepliesMask;
// Static initializer
static
{
__initStatic();
}
// Default static initializer
private static void __initStatic()
{
// register child classes
__mapChildren = new com.tangosol.util.ListMap();
__mapChildren.put("Poll", DistributedCacheRequest.Poll.get_CLASS());
}
// Default constructor
public DistributedCacheRequest()
{
this(null, null, true);
}
// Initializing constructor
public DistributedCacheRequest(String sName, com.tangosol.coherence.Component compParent, boolean fInit)
{
super(sName, compParent, false);
if (fInit)
{
__init();
}
}
// Main initializer
public void __init()
{
// private initialization
__initPrivate();
// containment initialization: children
// signal the end of the initialization
set_Constructed(true);
}
// Private initializer
protected void __initPrivate()
{
super.__initPrivate();
}
// Getter for virtual constant ReadOnly
public boolean isReadOnly()
{
return true;
}
// Getter for virtual constant Suspendable
public boolean isSuspendable()
{
return true;
}
//++ getter for static property _Instance
/**
* Getter for property _Instance.<p>
* Auto generated
*/
public static com.tangosol.coherence.Component get_Instance()
{
return new com.tangosol.coherence.component.net.message.requestMessage.DistributedCacheRequest();
}
//++ getter for static property _CLASS
/**
* Getter for property _CLASS.<p>
* Property with auto-generated accessor that returns the Class object for a
* given component.
*/
public static Class get_CLASS()
{
Class clz;
try
{
clz = Class.forName("com.tangosol.coherence/component/net/message/requestMessage/DistributedCacheRequest".replace('/', '.'));
}
catch (ClassNotFoundException e)
{
throw new NoClassDefFoundError(e.getMessage());
}
return clz;
}
//++ getter for autogen property _Module
/**
* This is an auto-generated method that returns the global [design time]
* parent component.
*
* Note: the class generator will ignore any custom implementation for this
* behavior.
*/
private com.tangosol.coherence.Component get_Module()
{
return this;
}
//++ getter for autogen property _ChildClasses
/**
* This is an auto-generated method that returns the map of design time
* [static] children.
*
* Note: the class generator will ignore any custom implementation for this
* behavior.
*/
protected java.util.Map get_ChildClasses()
{
return __mapChildren;
}
// Declared at the super level
/**
* Instantiate a copy of this message. This is quite different from the
* standard "clone" since only the "transmittable" portion of the message
* (and none of the internal) state should be cloned.
*/
public com.tangosol.coherence.component.net.Message cloneMessage()
{
DistributedCacheRequest msg = (DistributedCacheRequest) super.cloneMessage();
msg.setCacheId(getCacheId());
msg.setExecutionTimeoutMillis(getExecutionTimeoutMillis());
msg.setRequestTimeoutMillis(getRequestTimeoutMillis());
msg.setSchedulingPriority(getSchedulingPriority());
msg.setOrderId(getOrderId());
if (isAsyncOperation())
{
msg.setOwnershipVersions(getOwnershipVersions());
}
return msg;
}
/**
* Copy the PriorityTask attributes from the specified task.
*/
public void copyPriorityAttributes(com.tangosol.net.PriorityTask task)
{
if (task != null)
{
setExecutionTimeoutMillis(task.getExecutionTimeoutMillis());
setRequestTimeoutMillis(task.getRequestTimeoutMillis());
setSchedulingPriority(task.getSchedulingPriority());
}
}
// From interface: com.tangosol.net.cache.KeyAssociation
public Object getAssociatedKey()
{
long lOrderId = getOrderId();
return lOrderId == 0L ? null : Long.valueOf(lOrderId);
}
// Accessor for the property "CacheId"
/**
* Getter for property CacheId.<p>
* The Id of the cache this request is for.
*/
public long getCacheId()
{
return __m_CacheId;
}
// Declared at the super level
/**
* Getter for property Description.<p>
* Used for debugging purposes (from toString). Create a human-readable
* description of the specific Message data.
*/
public String getDescription()
{
// import Component.Util.Daemon.QueueProcessor.Service.Grid.PartitionedService.PartitionedCache;
String sCacheName = ((PartitionedCache) getService()).getCacheName(getCacheId());
if (sCacheName == null)
{
sCacheName = "<unknown>";
}
return "CacheName=" + sCacheName;
}
// Declared at the super level
/**
* Getter for property EstimatedByteSize.<p>
* The estimated serialized size of this message. A negative value
* indicates that the size is unknown and that it is safe to estimate the
* size via a double serialization.
*/
public int getEstimatedByteSize()
{
return super.getEstimatedByteSize() +
8 + // long - CacheId
8 + // long - ExecutionTimeoutMillis
8 + // long - RequestTimeoutMillis
4 + // int - SchedulingPriority
8; // long - OrderId
}
// From interface: com.tangosol.net.PriorityTask
// Accessor for the property "ExecutionTimeoutMillis"
/**
* Getter for property ExecutionTimeoutMillis.<p>
* From PriorityTask interface.
*/
public long getExecutionTimeoutMillis()
{
return __m_ExecutionTimeoutMillis;
}
// Accessor for the property "OrderId"
/**
* Getter for property OrderId.<p>
* Unit-of-order id for asynchronous agents. This value is zero for
* synchronous requests.
*
* @see com.tangosol.util.processor.AsynchronousProcessor,
* com.tangosol.util.aggregator.AsynchronousAggregator
*/
public long getOrderId()
{
return __m_OrderId;
}
// Accessor for the property "OwnershipVersions"
/**
* Getter for property OwnershipVersions.<p>
* The ownership versions of the partitions associated with this Request
* (from the client's point of view).
*
* Used for AsyncOperations only.
*/
public com.tangosol.net.internal.PartitionVersions getOwnershipVersions()
{
return __m_OwnershipVersions;
}
// Accessor for the property "PartResults"
/**
* Getter for property PartResults.<p>
* Transient list of partial results returned by [storage-enabled] service
* members that processed this request. Most commonly the elements of this
* list are DistributedPartialResponse messages.
*/
public java.util.List getPartResults()
{
return __m_PartResults;
}
// Accessor for the property "ProcessedPartitions"
/**
* Getter for property ProcessedPartitions.<p>
* The set of partitions processed by this request.
*
* This transient property is optional, and is filled in only after the
* request is processed.
*/
public com.tangosol.net.partition.PartitionSet getProcessedPartitions()
{
return __m_ProcessedPartitions;
}
// Accessor for the property "ReadException"
/**
* Getter for property ReadException.<p>
* (Transient) An Exception that occurred during the read() and had to be
* deferred to be processed during onReceived() ans possibly reported back
* to the client (requestor). Usually it is an IOException, but for
* technical reasons could also be a ClassCastException.
*
* See COH-2150 for details.
*/
public Exception getReadException()
{
return __m_ReadException;
}
// Accessor for the property "RequestPartitions"
/**
* Getter for property RequestPartitions.<p>
* (Calculated) Set of partitions that need to be processed for this
* request. This value is never null for asynchronous requests.
*/
public com.tangosol.net.partition.PartitionSet getRequestPartitions()
{
// this method needs to be overridden to be used
throw new UnsupportedOperationException();
}
// From interface: com.tangosol.net.PriorityTask
// Accessor for the property "RequestTimeoutMillis"
/**
* Getter for property RequestTimeoutMillis.<p>
* From PriorityTask interface.
*/
public long getRequestTimeoutMillis()
{
return __m_RequestTimeoutMillis;
}
// From interface: com.tangosol.net.PriorityTask
// Accessor for the property "SchedulingPriority"
/**
* Getter for property SchedulingPriority.<p>
* From PriorityTask interface.
*/
public int getSchedulingPriority()
{
return __m_SchedulingPriority;
}
/**
* Getter for RepliesMask
*
* Keep track of replies against request mask while keeping the latter safe.
*
* @return the replies mask PartitionSet
*/
public PartitionSet getRepliesMask()
{
return __m_RepliesMask;
}
// Declared at the super level
protected com.tangosol.coherence.component.net.Poll instantiatePoll()
{
return (DistributedCacheRequest.Poll) _newChild("Poll");
}
// Accessor for the property "AsyncOperation"
/**
* Getter for property AsyncOperation.<p>
* Calculated property indicating whether or not this message represents an
* asynchronous operation.
*/
public boolean isAsyncOperation()
{
return getOrderId() != 0;
}
// Declared at the super level
/**
* This is the event that is executed when a Message is received.
* <p>
* It is the main processing event of the Message called by the
* <code>Service.onMessage()</code> event. With regards to the use of
* Message components within clustered Services, Services are designed by
* dragging Message components into them as static children. These Messages
* are the components that a Service can send to other running instances of
* the same Service within a cluster. When the onReceived event is invoked
* by a Service, it means that the Message has been received; the code in
* the onReceived event is therefore the Message specific logic for
* processing a received Message. For example, when onReceived is invoked on
* a Message named FindData, the onReceived event should do the work to
* "find the data", because it is being invoked by the Service that received
* the "find the data" Message.
*/
public void onReceived()
{
super.onReceived();
getService().getDaemonPool().add(this);
}
// Declared at the super level
/**
* Asynchronously send this message. The actual transmission of the message
* may be deferred due to the send queue batching.
* This method should not be called directly; see Grid#post(Message).
*/
public void post()
{
// import Component.Util.Daemon.QueueProcessor.Service.Grid.PartitionedService.PartitionedCache as com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache;
if (isAsyncOperation())
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache service = (com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache) getService();
// stamp async requests with the client's view of the ownership versions
setOwnershipVersions(service.collectOwnershipVersions(getRequestPartitions()));
}
super.post();
}
// Declared at the super level
/**
* Preprocess this message.
*
* @return true iff this message has been fully processed (onReceived was
* called)
*/
public boolean preprocess()
{
// import Component.Util.Daemon.QueueProcessor.Service.Grid.PartitionedService;
// import com.tangosol.util.ThreadGate;
if (isDeserializationRequired())
{
return false;
}
// Note: we check if the service is concurrent rather then
// checking that the thread pool is running. The result is that
// when the thread-pool is running this work is dispatched there, but
// when it is not enabled, but the service is concurrent
// we can execute the work directly on the IO thread. Basically
// configuring a negative thread count enables IO thread request processing.
PartitionedService service = (PartitionedService) getService();
if (service.isConcurrent())
{
ThreadGate gate = service.getPreprocessingGate();
if (gate.enter(0))
{
try
{
service.onMessage(this);
return true;
}
finally
{
gate.exit();
}
}
}
return false;
}
// Declared at the super level
public void read(com.tangosol.io.ReadBuffer.BufferInput input)
throws java.io.IOException
{
// import com.tangosol.net.internal.PartitionVersions;
// import com.tangosol.util.ExternalizableHelper;
super.read(input);
setCacheId(ExternalizableHelper.readLong(input));
setExecutionTimeoutMillis(ExternalizableHelper.readLong(input));
setRequestTimeoutMillis(ExternalizableHelper.readLong(input));
setSchedulingPriority(ExternalizableHelper.readInt(input));
setOrderId(ExternalizableHelper.readLong(input));
if (isAsyncOperation())
{
PartitionVersions versions = new PartitionVersions();
versions.readExternal(input);
setOwnershipVersions(versions);
}
}
// From interface: java.lang.Runnable
public void run()
{
throw new UnsupportedOperationException();
}
// From interface: com.tangosol.net.PriorityTask
public void runCanceled(boolean fAbandoned)
{
}
// Accessor for the property "CacheId"
/**
* Setter for property CacheId.<p>
* The Id of the cache this request is for.
*/
public void setCacheId(long lCacheId)
{
__m_CacheId = lCacheId;
}
// Accessor for the property "ExecutionTimeoutMillis"
/**
* Setter for property ExecutionTimeoutMillis.<p>
* From PriorityTask interface.
*/
public void setExecutionTimeoutMillis(long cMillis)
{
__m_ExecutionTimeoutMillis = cMillis;
}
// Accessor for the property "OrderId"
/**
* Setter for property OrderId.<p>
* Unit-of-order id for asynchronous agents. This value is zero for
* synchronous requests.
*
* @see com.tangosol.util.processor.AsynchronousProcessor,
* com.tangosol.util.aggregator.AsynchronousAggregator
*/
public void setOrderId(long lId)
{
__m_OrderId = lId;
}
// Accessor for the property "OwnershipVersions"
/**
* Setter for property OwnershipVersions.<p>
* The ownership versions of the partitions associated with this Request
* (from the client's point of view).
*
* Used for AsyncOperations only.
*/
public void setOwnershipVersions(com.tangosol.net.internal.PartitionVersions versionsOwnership)
{
__m_OwnershipVersions = versionsOwnership;
}
// Accessor for the property "PartResults"
/**
* Setter for property PartResults.<p>
* Transient list of partial results returned by [storage-enabled] service
* members that processed this request. Most commonly the elements of this
* list are DistributedPartialResponse messages.
*/
public void setPartResults(java.util.List listResults)
{
__m_PartResults = listResults;
}
// Accessor for the property "ProcessedPartitions"
/**
* Setter for property ProcessedPartitions.<p>
* The set of partitions processed by this request.
*
* This transient property is optional, and is filled in only after the
* request is processed.
*/
public void setProcessedPartitions(com.tangosol.net.partition.PartitionSet parts)
{
__m_ProcessedPartitions = parts;
}
// Accessor for the property "ReadException"
/**
* Setter for property ReadException.<p>
* (Transient) An Exception that occurred during the read() and had to be
* deferred to be processed during onReceived() ans possibly reported back
* to the client (requestor). Usually it is an IOException, but for
* technical reasons could also be a ClassCastException.
*
* See COH-2150 for details.
*/
public void setReadException(Exception exception)
{
__m_ReadException = exception;
}
// Accessor for the property "RequestTimeoutMillis"
/**
* Setter for property RequestTimeoutMillis.<p>
* From PriorityTask interface.
*/
public void setRequestTimeoutMillis(long cMillis)
{
__m_RequestTimeoutMillis = cMillis;
}
// Accessor for the property "SchedulingPriority"
/**
* Setter for property SchedulingPriority.<p>
* From PriorityTask interface.
*/
public void setSchedulingPriority(int nPriority)
{
__m_SchedulingPriority = nPriority;
}
/**
* Setter for RepliesMask
*
* Keep track of replies against request mask while keeping the latter safe.
*
* @param set PartitionSet initially set to request mask
*/
public void setRepliesMask(PartitionSet set)
{
__m_RepliesMask = set;
}
// Declared at the super level
public void write(com.tangosol.io.WriteBuffer.BufferOutput output)
throws java.io.IOException
{
// import com.tangosol.util.ExternalizableHelper;
super.write(output);
ExternalizableHelper.writeLong(output, getCacheId());
ExternalizableHelper.writeLong(output, getExecutionTimeoutMillis());
ExternalizableHelper.writeLong(output, getRequestTimeoutMillis());
ExternalizableHelper.writeInt(output, getSchedulingPriority());
ExternalizableHelper.writeLong(output, getOrderId());
if (isAsyncOperation())
{
getOwnershipVersions().writeExternal(output);
}
}
// ---- class: com.tangosol.coherence.component.net.message.requestMessage.DistributedCacheRequest$Poll
/**
* The Poll contains information regarding a request sent to one or more
* Cluster Members that require responses. A Service may poll other Members
* that are running the same Service, and the Poll is used to wait for and
* assemble the responses from each of those Members. A client thread may
* also use the Poll to block on a response or set of responses, thus
* waiting for the completion of the Poll. In its simplest form, which is a
* Poll that is sent to one Member of the Cluster, the Poll actually
* represents the request/response model.
*/
@SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"})
public static class Poll
extends com.tangosol.coherence.component.net.Poll
{
// ---- Fields declarations ----
/**
* Property RequestRejected
*
* False if the response carries any partial result; true if the
* request has been fully rejected.
*
* Note: this property is used only by the onResponse() method and any
* changes to its default value by sub-components should be done
* *before* super.onResponse() call is made.
*/
private boolean __m_RequestRejected;
// Default constructor
public Poll()
{
this(null, null, true);
}
// Initializing constructor
public Poll(String sName, com.tangosol.coherence.Component compParent, boolean fInit)
{
super(sName, compParent, false);
if (fInit)
{
__init();
}
}
// Main initializer
public void __init()
{
// private initialization
__initPrivate();
// signal the end of the initialization
set_Constructed(true);
}
// Private initializer
protected void __initPrivate()
{
super.__initPrivate();
}
//++ getter for static property _Instance
/**
* Getter for property _Instance.<p>
* Auto generated
*/
public static com.tangosol.coherence.Component get_Instance()
{
return new com.tangosol.coherence.component.net.message.requestMessage.DistributedCacheRequest.Poll();
}
//++ getter for static property _CLASS
/**
* Getter for property _CLASS.<p>
* Property with auto-generated accessor that returns the Class object
* for a given component.
*/
public static Class get_CLASS()
{
Class clz;
try
{
clz = Class.forName("com.tangosol.coherence/component/net/message/requestMessage/DistributedCacheRequest$Poll".replace('/', '.'));
}
catch (ClassNotFoundException e)
{
throw new NoClassDefFoundError(e.getMessage());
}
return clz;
}
//++ getter for autogen property _Module
/**
* This is an auto-generated method that returns the global [design
* time] parent component.
*
* Note: the class generator will ignore any custom implementation for
* this behavior.
*/
private com.tangosol.coherence.Component get_Module()
{
return this.get_Parent();
}
// Accessor for the property "RequestRejected"
/**
* Getter for property RequestRejected.<p>
* False if the response carries any partial result; true if the request
* has been fully rejected.
*
* Note: this property is used only by the onResponse() method and any
* changes to its default value by sub-components should be done
* *before* super.onResponse() call is made.
*/
protected boolean isRequestRejected()
{
return __m_RequestRejected;
}
// Declared at the super level
/**
* This is the event that is executed when all the Members that were
* polled have responded or have left the Service.
*/
protected void onCompletion()
{
// import Component.Net.Message.RequestMessage.DistributedCacheRequest as DistributedCacheRequest;
// import Component.Net.Message.ResponseMessage.DistributedPartialResponse as com.tangosol.coherence.component.net.message.responseMessage.DistributedPartialResponse;
// import Component.Net.RequestContext.AsyncContext;
// import Component.Util.Daemon.QueueProcessor.Service.Grid.PartitionedService.PartitionedCache as com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache;
// import Component.Util.Daemon.QueueProcessor.Service.Grid.PartitionedService.PartitionedCache$RequestCoordinator as com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache.RequestCoordinator;
// import com.tangosol.net.partition.PartitionSet;
super.onCompletion();
DistributedCacheRequest msgRequest = (DistributedCacheRequest) get_Module();
if (msgRequest.isAsyncOperation())
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache service = (com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache) getService();
com.tangosol.coherence.component.util.daemon.queueProcessor.service.grid.partitionedService.PartitionedCache.RequestCoordinator coordinator = service.getRequestCoordinator();
AsyncContext context = (AsyncContext) msgRequest.getRequestContext();
PartitionSet partRequest = msgRequest.getRequestPartitions();
PartitionSet partRemain = context.getPartitionSet();
com.tangosol.coherence.component.net.message.responseMessage.DistributedPartialResponse msgResponse = (com.tangosol.coherence.component.net.message.responseMessage.DistributedPartialResponse) getResult();
if (msgResponse == null)
{
if (getRespondedMemberSet().isEmpty() && getLeftMemberSet().isEmpty())
{
// exception during message post()
partRemain.remove(partRequest);
}
else
{
// Note1: we must run this logic (to create a new message and call submit()
// even if the service has stopped, as it is our only mechanism to
// unblock a potentially waiting client
// Note2: resubmit may not throw; any exceptions are reported via the context
if (!coordinator.resubmitRequest((DistributedCacheRequest) msgRequest.cloneMessage(), partRequest, null))
{
// none of the partitions need to be resubmitted any longer
partRemain.remove(partRequest);
}
// this is either the service or a transport thread; no need to flush
}
}
else
{
// re-submit rejected keys/partitions
PartitionSet partReject = msgResponse.getRejectPartitions();
if (!coordinator.resubmitRequest((DistributedCacheRequest) msgRequest.cloneMessage(), partReject, partReject))
{
if (partReject != null)
{
partRemain.remove(partReject);
}
}
// process the results
processAsyncResponse(msgResponse);
PartitionSet partResult = partRequest;
if (partReject != null)
{
// finalize the response only after resubmitting rejected partitions (COH-10351)
coordinator.finalizeResponse(partReject); // only rejected partitions
}
}
if (partRemain.isEmpty())
{
context.processCompletion();
}
// finalize the response only after resubmitting rejected partitions (COH-10351)
coordinator.finalizeResponse(partRequest); // does not include rejected partitions
}
}
// Declared at the super level
/**
* This is the event that occurs when the RequestMessage associated with
* this poll failed in post()
*/
public void onException(Throwable eReason)
{
// import Component.Net.RequestContext.AsyncContext;
DistributedCacheRequest msgRequest = (DistributedCacheRequest) get_Module();
if (msgRequest.isAsyncOperation())
{
AsyncContext context = (AsyncContext) msgRequest.getRequestContext();
context.processException(eReason);
}
}
// Declared at the super level
/**
* This event occurs for each response Message from each polled Member.
*/
public void onResponse(com.tangosol.coherence.component.net.Message msg)
{
// import java.util.List;
DistributedCacheRequest msgRequest = (DistributedCacheRequest) get_Module();
List listParts = msgRequest.getPartResults();
if (listParts == null)
{
// optimization for pseudo-partial requests (e.g. KeyAssociatedFilter)
setResult(msg);
}
else if (!isRequestRejected())
{
synchronized (listParts)
{
listParts.add(msg);
}
}
// don't call (and close the poll) unless all partial responses have been received
if (!(msgRequest instanceof PartitionedCache.PartitionedQueryRequest) ||
msgRequest.getRepliesMask() == null ||
msgRequest.getRepliesMask().isEmpty() ||
((DistributedPartialResponse) msg).getException() != null)
{
super.onResponse(msg);
}
}
// Declared at the super level
/**
* Preprocess the response to this Poll.
*
* @return true iff the response message has been fully processed
* (onMessage was called)
*/
public boolean preprocessResponse(com.tangosol.coherence.component.net.Message msgResponse)
{
DistributedCacheRequest msgRequest = (DistributedCacheRequest) get_Module();
// for asynchronous operations, onCompletion() logic may require synchronization
// and calls into user's methods and is not a good fit for preprocessing
return !msgRequest.isAsyncOperation()
&& super.preprocessResponse(msgResponse);
}
protected void processAsyncResponse(com.tangosol.coherence.component.net.Message msg)
{
// this method needs to be overridden to be used
throw new UnsupportedOperationException();
}
// Accessor for the property "RequestRejected"
/**
* Setter for property RequestRejected.<p>
* False if the response carries any partial result; true if the request
* has been fully rejected.
*
* Note: this property is used only by the onResponse() method and any
* changes to its default value by sub-components should be done
* *before* super.onResponse() call is made.
*/
protected void setRequestRejected(boolean fRejected)
{
__m_RequestRejected = fRejected;
}
}
}
|
googleapis/google-cloud-java | 37,679 | java-workspaceevents/google-cloud-workspaceevents/src/main/java/com/google/apps/events/subscriptions/v1/stub/SubscriptionsServiceStubSettings.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.apps.events.subscriptions.v1.stub;
import static com.google.apps.events.subscriptions.v1.SubscriptionsServiceClient.ListSubscriptionsPagedResponse;
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.apps.events.subscriptions.v1.CreateSubscriptionMetadata;
import com.google.apps.events.subscriptions.v1.CreateSubscriptionRequest;
import com.google.apps.events.subscriptions.v1.DeleteSubscriptionMetadata;
import com.google.apps.events.subscriptions.v1.DeleteSubscriptionRequest;
import com.google.apps.events.subscriptions.v1.GetSubscriptionRequest;
import com.google.apps.events.subscriptions.v1.ListSubscriptionsRequest;
import com.google.apps.events.subscriptions.v1.ListSubscriptionsResponse;
import com.google.apps.events.subscriptions.v1.ReactivateSubscriptionMetadata;
import com.google.apps.events.subscriptions.v1.ReactivateSubscriptionRequest;
import com.google.apps.events.subscriptions.v1.Subscription;
import com.google.apps.events.subscriptions.v1.UpdateSubscriptionMetadata;
import com.google.apps.events.subscriptions.v1.UpdateSubscriptionRequest;
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 SubscriptionsServiceStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (workspaceevents.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 getSubscription:
*
* <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
* SubscriptionsServiceStubSettings.Builder subscriptionsServiceSettingsBuilder =
* SubscriptionsServiceStubSettings.newBuilder();
* subscriptionsServiceSettingsBuilder
* .getSubscriptionSettings()
* .setRetrySettings(
* subscriptionsServiceSettingsBuilder
* .getSubscriptionSettings()
* .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());
* SubscriptionsServiceStubSettings subscriptionsServiceSettings =
* subscriptionsServiceSettingsBuilder.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 createSubscription:
*
* <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
* SubscriptionsServiceStubSettings.Builder subscriptionsServiceSettingsBuilder =
* SubscriptionsServiceStubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* subscriptionsServiceSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class SubscriptionsServiceStubSettings
extends StubSettings<SubscriptionsServiceStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/chat.memberships")
.add("https://www.googleapis.com/auth/chat.memberships.readonly")
.add("https://www.googleapis.com/auth/chat.messages")
.add("https://www.googleapis.com/auth/chat.messages.reactions")
.add("https://www.googleapis.com/auth/chat.messages.reactions.readonly")
.add("https://www.googleapis.com/auth/chat.messages.readonly")
.add("https://www.googleapis.com/auth/chat.spaces")
.add("https://www.googleapis.com/auth/chat.spaces.readonly")
.add("https://www.googleapis.com/auth/meetings.space.created")
.add("https://www.googleapis.com/auth/meetings.space.readonly")
.build();
private final UnaryCallSettings<CreateSubscriptionRequest, Operation> createSubscriptionSettings;
private final OperationCallSettings<
CreateSubscriptionRequest, Subscription, CreateSubscriptionMetadata>
createSubscriptionOperationSettings;
private final UnaryCallSettings<DeleteSubscriptionRequest, Operation> deleteSubscriptionSettings;
private final OperationCallSettings<DeleteSubscriptionRequest, Empty, DeleteSubscriptionMetadata>
deleteSubscriptionOperationSettings;
private final UnaryCallSettings<GetSubscriptionRequest, Subscription> getSubscriptionSettings;
private final PagedCallSettings<
ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse>
listSubscriptionsSettings;
private final UnaryCallSettings<UpdateSubscriptionRequest, Operation> updateSubscriptionSettings;
private final OperationCallSettings<
UpdateSubscriptionRequest, Subscription, UpdateSubscriptionMetadata>
updateSubscriptionOperationSettings;
private final UnaryCallSettings<ReactivateSubscriptionRequest, Operation>
reactivateSubscriptionSettings;
private final OperationCallSettings<
ReactivateSubscriptionRequest, Subscription, ReactivateSubscriptionMetadata>
reactivateSubscriptionOperationSettings;
private static final PagedListDescriptor<
ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>
LIST_SUBSCRIPTIONS_PAGE_STR_DESC =
new PagedListDescriptor<
ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListSubscriptionsRequest injectToken(
ListSubscriptionsRequest payload, String token) {
return ListSubscriptionsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListSubscriptionsRequest injectPageSize(
ListSubscriptionsRequest payload, int pageSize) {
return ListSubscriptionsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListSubscriptionsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListSubscriptionsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Subscription> extractResources(ListSubscriptionsResponse payload) {
return payload.getSubscriptionsList();
}
};
private static final PagedListResponseFactory<
ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse>
LIST_SUBSCRIPTIONS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListSubscriptionsRequest,
ListSubscriptionsResponse,
ListSubscriptionsPagedResponse>() {
@Override
public ApiFuture<ListSubscriptionsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListSubscriptionsRequest, ListSubscriptionsResponse> callable,
ListSubscriptionsRequest request,
ApiCallContext context,
ApiFuture<ListSubscriptionsResponse> futureResponse) {
PageContext<ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>
pageContext =
PageContext.create(
callable, LIST_SUBSCRIPTIONS_PAGE_STR_DESC, request, context);
return ListSubscriptionsPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to createSubscription. */
public UnaryCallSettings<CreateSubscriptionRequest, Operation> createSubscriptionSettings() {
return createSubscriptionSettings;
}
/** Returns the object with the settings used for calls to createSubscription. */
public OperationCallSettings<CreateSubscriptionRequest, Subscription, CreateSubscriptionMetadata>
createSubscriptionOperationSettings() {
return createSubscriptionOperationSettings;
}
/** Returns the object with the settings used for calls to deleteSubscription. */
public UnaryCallSettings<DeleteSubscriptionRequest, Operation> deleteSubscriptionSettings() {
return deleteSubscriptionSettings;
}
/** Returns the object with the settings used for calls to deleteSubscription. */
public OperationCallSettings<DeleteSubscriptionRequest, Empty, DeleteSubscriptionMetadata>
deleteSubscriptionOperationSettings() {
return deleteSubscriptionOperationSettings;
}
/** Returns the object with the settings used for calls to getSubscription. */
public UnaryCallSettings<GetSubscriptionRequest, Subscription> getSubscriptionSettings() {
return getSubscriptionSettings;
}
/** Returns the object with the settings used for calls to listSubscriptions. */
public PagedCallSettings<
ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse>
listSubscriptionsSettings() {
return listSubscriptionsSettings;
}
/** Returns the object with the settings used for calls to updateSubscription. */
public UnaryCallSettings<UpdateSubscriptionRequest, Operation> updateSubscriptionSettings() {
return updateSubscriptionSettings;
}
/** Returns the object with the settings used for calls to updateSubscription. */
public OperationCallSettings<UpdateSubscriptionRequest, Subscription, UpdateSubscriptionMetadata>
updateSubscriptionOperationSettings() {
return updateSubscriptionOperationSettings;
}
/** Returns the object with the settings used for calls to reactivateSubscription. */
public UnaryCallSettings<ReactivateSubscriptionRequest, Operation>
reactivateSubscriptionSettings() {
return reactivateSubscriptionSettings;
}
/** Returns the object with the settings used for calls to reactivateSubscription. */
public OperationCallSettings<
ReactivateSubscriptionRequest, Subscription, ReactivateSubscriptionMetadata>
reactivateSubscriptionOperationSettings() {
return reactivateSubscriptionOperationSettings;
}
public SubscriptionsServiceStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcSubscriptionsServiceStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonSubscriptionsServiceStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "workspaceevents";
}
/** 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 "workspaceevents.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "workspaceevents.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(SubscriptionsServiceStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(SubscriptionsServiceStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return SubscriptionsServiceStubSettings.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 SubscriptionsServiceStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
createSubscriptionSettings = settingsBuilder.createSubscriptionSettings().build();
createSubscriptionOperationSettings =
settingsBuilder.createSubscriptionOperationSettings().build();
deleteSubscriptionSettings = settingsBuilder.deleteSubscriptionSettings().build();
deleteSubscriptionOperationSettings =
settingsBuilder.deleteSubscriptionOperationSettings().build();
getSubscriptionSettings = settingsBuilder.getSubscriptionSettings().build();
listSubscriptionsSettings = settingsBuilder.listSubscriptionsSettings().build();
updateSubscriptionSettings = settingsBuilder.updateSubscriptionSettings().build();
updateSubscriptionOperationSettings =
settingsBuilder.updateSubscriptionOperationSettings().build();
reactivateSubscriptionSettings = settingsBuilder.reactivateSubscriptionSettings().build();
reactivateSubscriptionOperationSettings =
settingsBuilder.reactivateSubscriptionOperationSettings().build();
}
/** Builder for SubscriptionsServiceStubSettings. */
public static class Builder
extends StubSettings.Builder<SubscriptionsServiceStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<CreateSubscriptionRequest, Operation>
createSubscriptionSettings;
private final OperationCallSettings.Builder<
CreateSubscriptionRequest, Subscription, CreateSubscriptionMetadata>
createSubscriptionOperationSettings;
private final UnaryCallSettings.Builder<DeleteSubscriptionRequest, Operation>
deleteSubscriptionSettings;
private final OperationCallSettings.Builder<
DeleteSubscriptionRequest, Empty, DeleteSubscriptionMetadata>
deleteSubscriptionOperationSettings;
private final UnaryCallSettings.Builder<GetSubscriptionRequest, Subscription>
getSubscriptionSettings;
private final PagedCallSettings.Builder<
ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse>
listSubscriptionsSettings;
private final UnaryCallSettings.Builder<UpdateSubscriptionRequest, Operation>
updateSubscriptionSettings;
private final OperationCallSettings.Builder<
UpdateSubscriptionRequest, Subscription, UpdateSubscriptionMetadata>
updateSubscriptionOperationSettings;
private final UnaryCallSettings.Builder<ReactivateSubscriptionRequest, Operation>
reactivateSubscriptionSettings;
private final OperationCallSettings.Builder<
ReactivateSubscriptionRequest, Subscription, ReactivateSubscriptionMetadata>
reactivateSubscriptionOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
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()
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("no_retry_1_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(1000L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(10000L))
.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);
createSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createSubscriptionOperationSettings = OperationCallSettings.newBuilder();
deleteSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteSubscriptionOperationSettings = OperationCallSettings.newBuilder();
getSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listSubscriptionsSettings = PagedCallSettings.newBuilder(LIST_SUBSCRIPTIONS_PAGE_STR_FACT);
updateSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateSubscriptionOperationSettings = OperationCallSettings.newBuilder();
reactivateSubscriptionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
reactivateSubscriptionOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
createSubscriptionSettings,
deleteSubscriptionSettings,
getSubscriptionSettings,
listSubscriptionsSettings,
updateSubscriptionSettings,
reactivateSubscriptionSettings);
initDefaults(this);
}
protected Builder(SubscriptionsServiceStubSettings settings) {
super(settings);
createSubscriptionSettings = settings.createSubscriptionSettings.toBuilder();
createSubscriptionOperationSettings =
settings.createSubscriptionOperationSettings.toBuilder();
deleteSubscriptionSettings = settings.deleteSubscriptionSettings.toBuilder();
deleteSubscriptionOperationSettings =
settings.deleteSubscriptionOperationSettings.toBuilder();
getSubscriptionSettings = settings.getSubscriptionSettings.toBuilder();
listSubscriptionsSettings = settings.listSubscriptionsSettings.toBuilder();
updateSubscriptionSettings = settings.updateSubscriptionSettings.toBuilder();
updateSubscriptionOperationSettings =
settings.updateSubscriptionOperationSettings.toBuilder();
reactivateSubscriptionSettings = settings.reactivateSubscriptionSettings.toBuilder();
reactivateSubscriptionOperationSettings =
settings.reactivateSubscriptionOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
createSubscriptionSettings,
deleteSubscriptionSettings,
getSubscriptionSettings,
listSubscriptionsSettings,
updateSubscriptionSettings,
reactivateSubscriptionSettings);
}
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
.createSubscriptionSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.deleteSubscriptionSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.getSubscriptionSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.listSubscriptionsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.updateSubscriptionSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.reactivateSubscriptionSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.createSubscriptionOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<CreateSubscriptionRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Subscription.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
CreateSubscriptionMetadata.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
.deleteSubscriptionOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<DeleteSubscriptionRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Empty.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
DeleteSubscriptionMetadata.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
.updateSubscriptionOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<UpdateSubscriptionRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Subscription.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
UpdateSubscriptionMetadata.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
.reactivateSubscriptionOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<ReactivateSubscriptionRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Subscription.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
ReactivateSubscriptionMetadata.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 createSubscription. */
public UnaryCallSettings.Builder<CreateSubscriptionRequest, Operation>
createSubscriptionSettings() {
return createSubscriptionSettings;
}
/** Returns the builder for the settings used for calls to createSubscription. */
public OperationCallSettings.Builder<
CreateSubscriptionRequest, Subscription, CreateSubscriptionMetadata>
createSubscriptionOperationSettings() {
return createSubscriptionOperationSettings;
}
/** Returns the builder for the settings used for calls to deleteSubscription. */
public UnaryCallSettings.Builder<DeleteSubscriptionRequest, Operation>
deleteSubscriptionSettings() {
return deleteSubscriptionSettings;
}
/** Returns the builder for the settings used for calls to deleteSubscription. */
public OperationCallSettings.Builder<
DeleteSubscriptionRequest, Empty, DeleteSubscriptionMetadata>
deleteSubscriptionOperationSettings() {
return deleteSubscriptionOperationSettings;
}
/** Returns the builder for the settings used for calls to getSubscription. */
public UnaryCallSettings.Builder<GetSubscriptionRequest, Subscription>
getSubscriptionSettings() {
return getSubscriptionSettings;
}
/** Returns the builder for the settings used for calls to listSubscriptions. */
public PagedCallSettings.Builder<
ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse>
listSubscriptionsSettings() {
return listSubscriptionsSettings;
}
/** Returns the builder for the settings used for calls to updateSubscription. */
public UnaryCallSettings.Builder<UpdateSubscriptionRequest, Operation>
updateSubscriptionSettings() {
return updateSubscriptionSettings;
}
/** Returns the builder for the settings used for calls to updateSubscription. */
public OperationCallSettings.Builder<
UpdateSubscriptionRequest, Subscription, UpdateSubscriptionMetadata>
updateSubscriptionOperationSettings() {
return updateSubscriptionOperationSettings;
}
/** Returns the builder for the settings used for calls to reactivateSubscription. */
public UnaryCallSettings.Builder<ReactivateSubscriptionRequest, Operation>
reactivateSubscriptionSettings() {
return reactivateSubscriptionSettings;
}
/** Returns the builder for the settings used for calls to reactivateSubscription. */
public OperationCallSettings.Builder<
ReactivateSubscriptionRequest, Subscription, ReactivateSubscriptionMetadata>
reactivateSubscriptionOperationSettings() {
return reactivateSubscriptionOperationSettings;
}
@Override
public SubscriptionsServiceStubSettings build() throws IOException {
return new SubscriptionsServiceStubSettings(this);
}
}
}
|
googleapis/google-cloud-java | 37,305 | java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/StatusCondition.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>
* StatusCondition describes why a cluster or a node pool has a certain status
* (e.g., ERROR or DEGRADED).
* </pre>
*
* Protobuf type {@code google.container.v1beta1.StatusCondition}
*/
public final class StatusCondition extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.container.v1beta1.StatusCondition)
StatusConditionOrBuilder {
private static final long serialVersionUID = 0L;
// Use StatusCondition.newBuilder() to construct.
private StatusCondition(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private StatusCondition() {
code_ = 0;
message_ = "";
canonicalCode_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new StatusCondition();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_StatusCondition_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_StatusCondition_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1beta1.StatusCondition.class,
com.google.container.v1beta1.StatusCondition.Builder.class);
}
/**
*
*
* <pre>
* Code for each condition
* </pre>
*
* Protobuf enum {@code google.container.v1beta1.StatusCondition.Code}
*/
@java.lang.Deprecated
public enum Code implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* UNKNOWN indicates a generic condition.
* </pre>
*
* <code>UNKNOWN = 0;</code>
*/
UNKNOWN(0),
/**
*
*
* <pre>
* GCE_STOCKOUT indicates that Google Compute Engine resources are
* temporarily unavailable.
* </pre>
*
* <code>GCE_STOCKOUT = 1;</code>
*/
GCE_STOCKOUT(1),
/**
*
*
* <pre>
* GKE_SERVICE_ACCOUNT_DELETED indicates that the user deleted their robot
* service account.
* </pre>
*
* <code>GKE_SERVICE_ACCOUNT_DELETED = 2;</code>
*/
GKE_SERVICE_ACCOUNT_DELETED(2),
/**
*
*
* <pre>
* Google Compute Engine quota was exceeded.
* </pre>
*
* <code>GCE_QUOTA_EXCEEDED = 3;</code>
*/
GCE_QUOTA_EXCEEDED(3),
/**
*
*
* <pre>
* Cluster state was manually changed by an SRE due to a system logic error.
* </pre>
*
* <code>SET_BY_OPERATOR = 4;</code>
*/
SET_BY_OPERATOR(4),
/**
*
*
* <pre>
* Unable to perform an encrypt operation against the CloudKMS key used for
* etcd level encryption.
* </pre>
*
* <code>CLOUD_KMS_KEY_ERROR = 7;</code>
*/
CLOUD_KMS_KEY_ERROR(7),
/**
*
*
* <pre>
* Cluster CA is expiring soon.
* </pre>
*
* <code>CA_EXPIRING = 9;</code>
*/
CA_EXPIRING(9),
/**
*
*
* <pre>
* Node service account is missing permissions.
* </pre>
*
* <code>NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS = 10;</code>
*/
NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS(10),
/**
*
*
* <pre>
* Cloud KMS key version used for etcd level encryption has been destroyed.
* This is a permanent error.
* </pre>
*
* <code>CLOUD_KMS_KEY_DESTROYED = 11;</code>
*/
CLOUD_KMS_KEY_DESTROYED(11),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* UNKNOWN indicates a generic condition.
* </pre>
*
* <code>UNKNOWN = 0;</code>
*/
public static final int UNKNOWN_VALUE = 0;
/**
*
*
* <pre>
* GCE_STOCKOUT indicates that Google Compute Engine resources are
* temporarily unavailable.
* </pre>
*
* <code>GCE_STOCKOUT = 1;</code>
*/
public static final int GCE_STOCKOUT_VALUE = 1;
/**
*
*
* <pre>
* GKE_SERVICE_ACCOUNT_DELETED indicates that the user deleted their robot
* service account.
* </pre>
*
* <code>GKE_SERVICE_ACCOUNT_DELETED = 2;</code>
*/
public static final int GKE_SERVICE_ACCOUNT_DELETED_VALUE = 2;
/**
*
*
* <pre>
* Google Compute Engine quota was exceeded.
* </pre>
*
* <code>GCE_QUOTA_EXCEEDED = 3;</code>
*/
public static final int GCE_QUOTA_EXCEEDED_VALUE = 3;
/**
*
*
* <pre>
* Cluster state was manually changed by an SRE due to a system logic error.
* </pre>
*
* <code>SET_BY_OPERATOR = 4;</code>
*/
public static final int SET_BY_OPERATOR_VALUE = 4;
/**
*
*
* <pre>
* Unable to perform an encrypt operation against the CloudKMS key used for
* etcd level encryption.
* </pre>
*
* <code>CLOUD_KMS_KEY_ERROR = 7;</code>
*/
public static final int CLOUD_KMS_KEY_ERROR_VALUE = 7;
/**
*
*
* <pre>
* Cluster CA is expiring soon.
* </pre>
*
* <code>CA_EXPIRING = 9;</code>
*/
public static final int CA_EXPIRING_VALUE = 9;
/**
*
*
* <pre>
* Node service account is missing permissions.
* </pre>
*
* <code>NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS = 10;</code>
*/
public static final int NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS_VALUE = 10;
/**
*
*
* <pre>
* Cloud KMS key version used for etcd level encryption has been destroyed.
* This is a permanent error.
* </pre>
*
* <code>CLOUD_KMS_KEY_DESTROYED = 11;</code>
*/
public static final int CLOUD_KMS_KEY_DESTROYED_VALUE = 11;
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 Code 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 Code forNumber(int value) {
switch (value) {
case 0:
return UNKNOWN;
case 1:
return GCE_STOCKOUT;
case 2:
return GKE_SERVICE_ACCOUNT_DELETED;
case 3:
return GCE_QUOTA_EXCEEDED;
case 4:
return SET_BY_OPERATOR;
case 7:
return CLOUD_KMS_KEY_ERROR;
case 9:
return CA_EXPIRING;
case 10:
return NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS;
case 11:
return CLOUD_KMS_KEY_DESTROYED;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Code> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<Code> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Code>() {
public Code findValueByNumber(int number) {
return Code.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.StatusCondition.getDescriptor().getEnumTypes().get(0);
}
private static final Code[] VALUES = values();
public static Code 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 Code(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.container.v1beta1.StatusCondition.Code)
}
public static final int CODE_FIELD_NUMBER = 1;
private int code_ = 0;
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @return The enum numeric value on the wire for code.
*/
@java.lang.Override
@java.lang.Deprecated
public int getCodeValue() {
return code_;
}
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @return The code.
*/
@java.lang.Override
@java.lang.Deprecated
public com.google.container.v1beta1.StatusCondition.Code getCode() {
com.google.container.v1beta1.StatusCondition.Code result =
com.google.container.v1beta1.StatusCondition.Code.forNumber(code_);
return result == null ? com.google.container.v1beta1.StatusCondition.Code.UNRECOGNIZED : result;
}
public static final int MESSAGE_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object message_ = "";
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @return The message.
*/
@java.lang.Override
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
}
}
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @return The bytes for message.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CANONICAL_CODE_FIELD_NUMBER = 3;
private int canonicalCode_ = 0;
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @return The enum numeric value on the wire for canonicalCode.
*/
@java.lang.Override
public int getCanonicalCodeValue() {
return canonicalCode_;
}
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @return The canonicalCode.
*/
@java.lang.Override
public com.google.rpc.Code getCanonicalCode() {
com.google.rpc.Code result = com.google.rpc.Code.forNumber(canonicalCode_);
return result == null ? com.google.rpc.Code.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 (code_ != com.google.container.v1beta1.StatusCondition.Code.UNKNOWN.getNumber()) {
output.writeEnum(1, code_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, message_);
}
if (canonicalCode_ != com.google.rpc.Code.OK.getNumber()) {
output.writeEnum(3, canonicalCode_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (code_ != com.google.container.v1beta1.StatusCondition.Code.UNKNOWN.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, code_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, message_);
}
if (canonicalCode_ != com.google.rpc.Code.OK.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, canonicalCode_);
}
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.StatusCondition)) {
return super.equals(obj);
}
com.google.container.v1beta1.StatusCondition other =
(com.google.container.v1beta1.StatusCondition) obj;
if (code_ != other.code_) return false;
if (!getMessage().equals(other.getMessage())) return false;
if (canonicalCode_ != other.canonicalCode_) 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) + CODE_FIELD_NUMBER;
hash = (53 * hash) + code_;
hash = (37 * hash) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessage().hashCode();
hash = (37 * hash) + CANONICAL_CODE_FIELD_NUMBER;
hash = (53 * hash) + canonicalCode_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.container.v1beta1.StatusCondition parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.StatusCondition 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.StatusCondition parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.StatusCondition 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.StatusCondition parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.StatusCondition parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1beta1.StatusCondition parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.StatusCondition 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.StatusCondition parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.StatusCondition 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.StatusCondition parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.StatusCondition 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.StatusCondition 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>
* StatusCondition describes why a cluster or a node pool has a certain status
* (e.g., ERROR or DEGRADED).
* </pre>
*
* Protobuf type {@code google.container.v1beta1.StatusCondition}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.container.v1beta1.StatusCondition)
com.google.container.v1beta1.StatusConditionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_StatusCondition_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_StatusCondition_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1beta1.StatusCondition.class,
com.google.container.v1beta1.StatusCondition.Builder.class);
}
// Construct using com.google.container.v1beta1.StatusCondition.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
code_ = 0;
message_ = "";
canonicalCode_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_StatusCondition_descriptor;
}
@java.lang.Override
public com.google.container.v1beta1.StatusCondition getDefaultInstanceForType() {
return com.google.container.v1beta1.StatusCondition.getDefaultInstance();
}
@java.lang.Override
public com.google.container.v1beta1.StatusCondition build() {
com.google.container.v1beta1.StatusCondition result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.container.v1beta1.StatusCondition buildPartial() {
com.google.container.v1beta1.StatusCondition result =
new com.google.container.v1beta1.StatusCondition(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.container.v1beta1.StatusCondition result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.code_ = code_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.message_ = message_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.canonicalCode_ = canonicalCode_;
}
}
@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.StatusCondition) {
return mergeFrom((com.google.container.v1beta1.StatusCondition) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.container.v1beta1.StatusCondition other) {
if (other == com.google.container.v1beta1.StatusCondition.getDefaultInstance()) return this;
if (other.code_ != 0) {
setCodeValue(other.getCodeValue());
}
if (!other.getMessage().isEmpty()) {
message_ = other.message_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.canonicalCode_ != 0) {
setCanonicalCodeValue(other.getCanonicalCodeValue());
}
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:
{
code_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18:
{
message_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
canonicalCode_ = 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 int code_ = 0;
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @return The enum numeric value on the wire for code.
*/
@java.lang.Override
@java.lang.Deprecated
public int getCodeValue() {
return code_;
}
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @param value The enum numeric value on the wire for code to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setCodeValue(int value) {
code_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @return The code.
*/
@java.lang.Override
@java.lang.Deprecated
public com.google.container.v1beta1.StatusCondition.Code getCode() {
com.google.container.v1beta1.StatusCondition.Code result =
com.google.container.v1beta1.StatusCondition.Code.forNumber(code_);
return result == null
? com.google.container.v1beta1.StatusCondition.Code.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @param value The code to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setCode(com.google.container.v1beta1.StatusCondition.Code value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
code_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Machine-friendly representation of the condition
* Deprecated. Use canonical_code instead.
* </pre>
*
* <code>.google.container.v1beta1.StatusCondition.Code code = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.StatusCondition.code is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=5949
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder clearCode() {
bitField0_ = (bitField0_ & ~0x00000001);
code_ = 0;
onChanged();
return this;
}
private java.lang.Object message_ = "";
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @return The message.
*/
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @return The bytes for message.
*/
public com.google.protobuf.ByteString getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @param value The message to set.
* @return This builder for chaining.
*/
public Builder setMessage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
message_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearMessage() {
message_ = getDefaultInstance().getMessage();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Human-friendly representation of the condition
* </pre>
*
* <code>string message = 2;</code>
*
* @param value The bytes for message to set.
* @return This builder for chaining.
*/
public Builder setMessageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
message_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int canonicalCode_ = 0;
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @return The enum numeric value on the wire for canonicalCode.
*/
@java.lang.Override
public int getCanonicalCodeValue() {
return canonicalCode_;
}
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @param value The enum numeric value on the wire for canonicalCode to set.
* @return This builder for chaining.
*/
public Builder setCanonicalCodeValue(int value) {
canonicalCode_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @return The canonicalCode.
*/
@java.lang.Override
public com.google.rpc.Code getCanonicalCode() {
com.google.rpc.Code result = com.google.rpc.Code.forNumber(canonicalCode_);
return result == null ? com.google.rpc.Code.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @param value The canonicalCode to set.
* @return This builder for chaining.
*/
public Builder setCanonicalCode(com.google.rpc.Code value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
canonicalCode_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Canonical code of the condition.
* </pre>
*
* <code>.google.rpc.Code canonical_code = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearCanonicalCode() {
bitField0_ = (bitField0_ & ~0x00000004);
canonicalCode_ = 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.StatusCondition)
}
// @@protoc_insertion_point(class_scope:google.container.v1beta1.StatusCondition)
private static final com.google.container.v1beta1.StatusCondition DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.container.v1beta1.StatusCondition();
}
public static com.google.container.v1beta1.StatusCondition getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<StatusCondition> PARSER =
new com.google.protobuf.AbstractParser<StatusCondition>() {
@java.lang.Override
public StatusCondition 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<StatusCondition> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<StatusCondition> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.container.v1beta1.StatusCondition getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 37,651 | jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java | /*
* Copyright (c) 2002, 2008, 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 javax.swing.plaf.synth;
import java.awt.*;
import java.lang.ref.WeakReference;
import java.net.*;
import javax.swing.*;
import sun.awt.AppContext;
import sun.swing.plaf.synth.Paint9Painter;
/**
* ImagePainter fills in the specified region using an Image. The Image
* is split into 9 segments: north, north east, east, south east, south,
* south west, west, north west and the center. The corners are defined
* by way of an insets, and the remaining regions are either tiled or
* scaled to fit.
*
* @author Scott Violet
*/
class ImagePainter extends SynthPainter {
private static final StringBuffer CACHE_KEY =
new StringBuffer("SynthCacheKey");
private Image image;
private Insets sInsets;
private Insets dInsets;
private URL path;
private boolean tiles;
private boolean paintCenter;
private Paint9Painter imageCache;
private boolean center;
private static Paint9Painter getPaint9Painter() {
// A SynthPainter is created per <imagePainter>. We want the
// cache to be shared by all, and we don't use a static because we
// don't want it to persist between look and feels. For that reason
// we use a AppContext specific Paint9Painter. It's backed via
// a WeakRef so that it can go away if the look and feel changes.
synchronized(CACHE_KEY) {
WeakReference<Paint9Painter> cacheRef =
(WeakReference<Paint9Painter>)AppContext.getAppContext().
get(CACHE_KEY);
Paint9Painter painter;
if (cacheRef == null || (painter = cacheRef.get()) == null) {
painter = new Paint9Painter(30);
cacheRef = new WeakReference<Paint9Painter>(painter);
AppContext.getAppContext().put(CACHE_KEY, cacheRef);
}
return painter;
}
}
ImagePainter(boolean tiles, boolean paintCenter,
Insets sourceInsets, Insets destinationInsets, URL path,
boolean center) {
if (sourceInsets != null) {
this.sInsets = (Insets)sourceInsets.clone();
}
if (destinationInsets == null) {
dInsets = sInsets;
}
else {
this.dInsets = (Insets)destinationInsets.clone();
}
this.tiles = tiles;
this.paintCenter = paintCenter;
this.imageCache = getPaint9Painter();
this.path = path;
this.center = center;
}
public boolean getTiles() {
return tiles;
}
public boolean getPaintsCenter() {
return paintCenter;
}
public boolean getCenter() {
return center;
}
public Insets getInsets(Insets insets) {
if (insets == null) {
return (Insets)this.dInsets.clone();
}
insets.left = this.dInsets.left;
insets.right = this.dInsets.right;
insets.top = this.dInsets.top;
insets.bottom = this.dInsets.bottom;
return insets;
}
public Image getImage() {
if (image == null) {
image = new ImageIcon(path, null).getImage();
}
return image;
}
private void paint(SynthContext context, Graphics g, int x, int y, int w,
int h) {
Image image = getImage();
if (Paint9Painter.validImage(image)) {
Paint9Painter.PaintType type;
if (getCenter()) {
type = Paint9Painter.PaintType.CENTER;
}
else if (!getTiles()) {
type = Paint9Painter.PaintType.PAINT9_STRETCH;
}
else {
type = Paint9Painter.PaintType.PAINT9_TILE;
}
int mask = Paint9Painter.PAINT_ALL;
if (!getCenter() && !getPaintsCenter()) {
mask |= Paint9Painter.PAINT_CENTER;
}
imageCache.paint(context.getComponent(), g, x, y, w, h,
image, sInsets, dInsets, type,
mask);
}
}
// SynthPainter
public void paintArrowButtonBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintArrowButtonBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintArrowButtonForeground(SynthContext context,
Graphics g, int x, int y,
int w, int h,
int direction) {
paint(context, g, x, y, w, h);
}
// BUTTON
public void paintButtonBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintButtonBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// CHECK_BOX_MENU_ITEM
public void paintCheckBoxMenuItemBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintCheckBoxMenuItemBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// CHECK_BOX
public void paintCheckBoxBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintCheckBoxBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// COLOR_CHOOSER
public void paintColorChooserBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintColorChooserBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// COMBO_BOX
public void paintComboBoxBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintComboBoxBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// DESKTOP_ICON
public void paintDesktopIconBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintDesktopIconBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// DESKTOP_PANE
public void paintDesktopPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintDesktopPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// EDITOR_PANE
public void paintEditorPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintEditorPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// FILE_CHOOSER
public void paintFileChooserBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintFileChooserBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// FORMATTED_TEXT_FIELD
public void paintFormattedTextFieldBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintFormattedTextFieldBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// INTERNAL_FRAME_TITLE_PANE
public void paintInternalFrameTitlePaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintInternalFrameTitlePaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// INTERNAL_FRAME
public void paintInternalFrameBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintInternalFrameBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// LABEL
public void paintLabelBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintLabelBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// LIST
public void paintListBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintListBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// MENU_BAR
public void paintMenuBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintMenuBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// MENU_ITEM
public void paintMenuItemBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintMenuItemBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// MENU
public void paintMenuBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintMenuBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// OPTION_PANE
public void paintOptionPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintOptionPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// PANEL
public void paintPanelBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintPanelBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// PANEL
public void paintPasswordFieldBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintPasswordFieldBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// POPUP_MENU
public void paintPopupMenuBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintPopupMenuBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// PROGRESS_BAR
public void paintProgressBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintProgressBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintProgressBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintProgressBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintProgressBarForeground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// RADIO_BUTTON_MENU_ITEM
public void paintRadioButtonMenuItemBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintRadioButtonMenuItemBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// RADIO_BUTTON
public void paintRadioButtonBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintRadioButtonBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// ROOT_PANE
public void paintRootPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintRootPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// SCROLL_BAR
public void paintScrollBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SCROLL_BAR_THUMB
public void paintScrollBarThumbBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarThumbBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SCROLL_BAR_TRACK
public void paintScrollBarTrackBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarTrackBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarTrackBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintScrollBarTrackBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SCROLL_PANE
public void paintScrollPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintScrollPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// SEPARATOR
public void paintSeparatorBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSeparatorBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSeparatorBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSeparatorBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSeparatorForeground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SLIDER
public void paintSliderBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSliderBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSliderBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSliderBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SLIDER_THUMB
public void paintSliderThumbBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSliderThumbBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SLIDER_TRACK
public void paintSliderTrackBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSliderTrackBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSliderTrackBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSliderTrackBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SPINNER
public void paintSpinnerBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSpinnerBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// SPLIT_PANE_DIVIDER
public void paintSplitPaneDividerBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSplitPaneDividerBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSplitPaneDividerForeground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintSplitPaneDragDivider(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// SPLIT_PANE
public void paintSplitPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintSplitPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TABBED_PANE
public void paintTabbedPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TABBED_PANE_TAB_AREA
public void paintTabbedPaneTabAreaBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneTabAreaBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneTabAreaBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneTabAreaBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// TABBED_PANE_TAB
public void paintTabbedPaneTabBackground(SynthContext context, Graphics g,
int x, int y, int w, int h,
int tabIndex) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneTabBackground(SynthContext context, Graphics g,
int x, int y, int w, int h,
int tabIndex, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneTabBorder(SynthContext context, Graphics g,
int x, int y, int w, int h,
int tabIndex) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneTabBorder(SynthContext context, Graphics g,
int x, int y, int w, int h,
int tabIndex, int orientation) {
paint(context, g, x, y, w, h);
}
// TABBED_PANE_CONTENT
public void paintTabbedPaneContentBackground(SynthContext context,
Graphics g, int x, int y, int w,
int h) {
paint(context, g, x, y, w, h);
}
public void paintTabbedPaneContentBorder(SynthContext context, Graphics g,
int x, int y, int w, int h) {
paint(context, g, x, y, w, h);
}
// TABLE_HEADER
public void paintTableHeaderBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTableHeaderBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TABLE
public void paintTableBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTableBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TEXT_AREA
public void paintTextAreaBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTextAreaBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TEXT_PANE
public void paintTextPaneBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTextPaneBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TEXT_FIELD
public void paintTextFieldBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTextFieldBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TOGGLE_BUTTON
public void paintToggleButtonBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToggleButtonBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TOOL_BAR
public void paintToolBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolBarBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintToolBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolBarBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// TOOL_BAR_CONTENT
public void paintToolBarContentBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolBarContentBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintToolBarContentBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolBarContentBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// TOOL_DRAG_WINDOW
public void paintToolBarDragWindowBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolBarDragWindowBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
public void paintToolBarDragWindowBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolBarDragWindowBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h, int orientation) {
paint(context, g, x, y, w, h);
}
// TOOL_TIP
public void paintToolTipBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintToolTipBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TREE
public void paintTreeBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTreeBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// TREE_CELL
public void paintTreeCellBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTreeCellBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintTreeCellFocus(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
// VIEWPORT
public void paintViewportBackground(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
public void paintViewportBorder(SynthContext context,
Graphics g, int x, int y,
int w, int h) {
paint(context, g, x, y, w, h);
}
}
|
googleapis/google-cloud-java | 37,390 | java-analytics-data/proto-google-analytics-data-v1beta/src/main/java/com/google/analytics/data/v1beta/BatchRunReportsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/analytics/data/v1beta/analytics_data_api.proto
// Protobuf Java Version: 3.25.8
package com.google.analytics.data.v1beta;
/**
*
*
* <pre>
* The batch response containing multiple reports.
* </pre>
*
* Protobuf type {@code google.analytics.data.v1beta.BatchRunReportsResponse}
*/
public final class BatchRunReportsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.BatchRunReportsResponse)
BatchRunReportsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use BatchRunReportsResponse.newBuilder() to construct.
private BatchRunReportsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BatchRunReportsResponse() {
reports_ = java.util.Collections.emptyList();
kind_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new BatchRunReportsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.data.v1beta.AnalyticsDataApiProto
.internal_static_google_analytics_data_v1beta_BatchRunReportsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.data.v1beta.AnalyticsDataApiProto
.internal_static_google_analytics_data_v1beta_BatchRunReportsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.data.v1beta.BatchRunReportsResponse.class,
com.google.analytics.data.v1beta.BatchRunReportsResponse.Builder.class);
}
public static final int REPORTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.analytics.data.v1beta.RunReportResponse> reports_;
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.analytics.data.v1beta.RunReportResponse> getReportsList() {
return reports_;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.analytics.data.v1beta.RunReportResponseOrBuilder>
getReportsOrBuilderList() {
return reports_;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
@java.lang.Override
public int getReportsCount() {
return reports_.size();
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
@java.lang.Override
public com.google.analytics.data.v1beta.RunReportResponse getReports(int index) {
return reports_.get(index);
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
@java.lang.Override
public com.google.analytics.data.v1beta.RunReportResponseOrBuilder getReportsOrBuilder(
int index) {
return reports_.get(index);
}
public static final int KIND_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object kind_ = "";
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @return The kind.
*/
@java.lang.Override
public java.lang.String getKind() {
java.lang.Object ref = kind_;
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();
kind_ = s;
return s;
}
}
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @return The bytes for kind.
*/
@java.lang.Override
public com.google.protobuf.ByteString getKindBytes() {
java.lang.Object ref = kind_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
kind_ = 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 < reports_.size(); i++) {
output.writeMessage(1, reports_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kind_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, kind_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < reports_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, reports_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kind_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, kind_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.analytics.data.v1beta.BatchRunReportsResponse)) {
return super.equals(obj);
}
com.google.analytics.data.v1beta.BatchRunReportsResponse other =
(com.google.analytics.data.v1beta.BatchRunReportsResponse) obj;
if (!getReportsList().equals(other.getReportsList())) return false;
if (!getKind().equals(other.getKind())) 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 (getReportsCount() > 0) {
hash = (37 * hash) + REPORTS_FIELD_NUMBER;
hash = (53 * hash) + getReportsList().hashCode();
}
hash = (37 * hash) + KIND_FIELD_NUMBER;
hash = (53 * hash) + getKind().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.analytics.data.v1beta.BatchRunReportsResponse 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 batch response containing multiple reports.
* </pre>
*
* Protobuf type {@code google.analytics.data.v1beta.BatchRunReportsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.BatchRunReportsResponse)
com.google.analytics.data.v1beta.BatchRunReportsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.data.v1beta.AnalyticsDataApiProto
.internal_static_google_analytics_data_v1beta_BatchRunReportsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.data.v1beta.AnalyticsDataApiProto
.internal_static_google_analytics_data_v1beta_BatchRunReportsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.data.v1beta.BatchRunReportsResponse.class,
com.google.analytics.data.v1beta.BatchRunReportsResponse.Builder.class);
}
// Construct using com.google.analytics.data.v1beta.BatchRunReportsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (reportsBuilder_ == null) {
reports_ = java.util.Collections.emptyList();
} else {
reports_ = null;
reportsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
kind_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.data.v1beta.AnalyticsDataApiProto
.internal_static_google_analytics_data_v1beta_BatchRunReportsResponse_descriptor;
}
@java.lang.Override
public com.google.analytics.data.v1beta.BatchRunReportsResponse getDefaultInstanceForType() {
return com.google.analytics.data.v1beta.BatchRunReportsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.data.v1beta.BatchRunReportsResponse build() {
com.google.analytics.data.v1beta.BatchRunReportsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.data.v1beta.BatchRunReportsResponse buildPartial() {
com.google.analytics.data.v1beta.BatchRunReportsResponse result =
new com.google.analytics.data.v1beta.BatchRunReportsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.analytics.data.v1beta.BatchRunReportsResponse result) {
if (reportsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
reports_ = java.util.Collections.unmodifiableList(reports_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.reports_ = reports_;
} else {
result.reports_ = reportsBuilder_.build();
}
}
private void buildPartial0(com.google.analytics.data.v1beta.BatchRunReportsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.kind_ = kind_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.analytics.data.v1beta.BatchRunReportsResponse) {
return mergeFrom((com.google.analytics.data.v1beta.BatchRunReportsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.data.v1beta.BatchRunReportsResponse other) {
if (other == com.google.analytics.data.v1beta.BatchRunReportsResponse.getDefaultInstance())
return this;
if (reportsBuilder_ == null) {
if (!other.reports_.isEmpty()) {
if (reports_.isEmpty()) {
reports_ = other.reports_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureReportsIsMutable();
reports_.addAll(other.reports_);
}
onChanged();
}
} else {
if (!other.reports_.isEmpty()) {
if (reportsBuilder_.isEmpty()) {
reportsBuilder_.dispose();
reportsBuilder_ = null;
reports_ = other.reports_;
bitField0_ = (bitField0_ & ~0x00000001);
reportsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getReportsFieldBuilder()
: null;
} else {
reportsBuilder_.addAllMessages(other.reports_);
}
}
}
if (!other.getKind().isEmpty()) {
kind_ = other.kind_;
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.analytics.data.v1beta.RunReportResponse m =
input.readMessage(
com.google.analytics.data.v1beta.RunReportResponse.parser(),
extensionRegistry);
if (reportsBuilder_ == null) {
ensureReportsIsMutable();
reports_.add(m);
} else {
reportsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
kind_ = 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.analytics.data.v1beta.RunReportResponse> reports_ =
java.util.Collections.emptyList();
private void ensureReportsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
reports_ =
new java.util.ArrayList<com.google.analytics.data.v1beta.RunReportResponse>(reports_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.data.v1beta.RunReportResponse,
com.google.analytics.data.v1beta.RunReportResponse.Builder,
com.google.analytics.data.v1beta.RunReportResponseOrBuilder>
reportsBuilder_;
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public java.util.List<com.google.analytics.data.v1beta.RunReportResponse> getReportsList() {
if (reportsBuilder_ == null) {
return java.util.Collections.unmodifiableList(reports_);
} else {
return reportsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public int getReportsCount() {
if (reportsBuilder_ == null) {
return reports_.size();
} else {
return reportsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public com.google.analytics.data.v1beta.RunReportResponse getReports(int index) {
if (reportsBuilder_ == null) {
return reports_.get(index);
} else {
return reportsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder setReports(int index, com.google.analytics.data.v1beta.RunReportResponse value) {
if (reportsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureReportsIsMutable();
reports_.set(index, value);
onChanged();
} else {
reportsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder setReports(
int index, com.google.analytics.data.v1beta.RunReportResponse.Builder builderForValue) {
if (reportsBuilder_ == null) {
ensureReportsIsMutable();
reports_.set(index, builderForValue.build());
onChanged();
} else {
reportsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder addReports(com.google.analytics.data.v1beta.RunReportResponse value) {
if (reportsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureReportsIsMutable();
reports_.add(value);
onChanged();
} else {
reportsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder addReports(int index, com.google.analytics.data.v1beta.RunReportResponse value) {
if (reportsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureReportsIsMutable();
reports_.add(index, value);
onChanged();
} else {
reportsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder addReports(
com.google.analytics.data.v1beta.RunReportResponse.Builder builderForValue) {
if (reportsBuilder_ == null) {
ensureReportsIsMutable();
reports_.add(builderForValue.build());
onChanged();
} else {
reportsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder addReports(
int index, com.google.analytics.data.v1beta.RunReportResponse.Builder builderForValue) {
if (reportsBuilder_ == null) {
ensureReportsIsMutable();
reports_.add(index, builderForValue.build());
onChanged();
} else {
reportsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder addAllReports(
java.lang.Iterable<? extends com.google.analytics.data.v1beta.RunReportResponse> values) {
if (reportsBuilder_ == null) {
ensureReportsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, reports_);
onChanged();
} else {
reportsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder clearReports() {
if (reportsBuilder_ == null) {
reports_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
reportsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public Builder removeReports(int index) {
if (reportsBuilder_ == null) {
ensureReportsIsMutable();
reports_.remove(index);
onChanged();
} else {
reportsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public com.google.analytics.data.v1beta.RunReportResponse.Builder getReportsBuilder(int index) {
return getReportsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public com.google.analytics.data.v1beta.RunReportResponseOrBuilder getReportsOrBuilder(
int index) {
if (reportsBuilder_ == null) {
return reports_.get(index);
} else {
return reportsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public java.util.List<? extends com.google.analytics.data.v1beta.RunReportResponseOrBuilder>
getReportsOrBuilderList() {
if (reportsBuilder_ != null) {
return reportsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(reports_);
}
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public com.google.analytics.data.v1beta.RunReportResponse.Builder addReportsBuilder() {
return getReportsFieldBuilder()
.addBuilder(com.google.analytics.data.v1beta.RunReportResponse.getDefaultInstance());
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public com.google.analytics.data.v1beta.RunReportResponse.Builder addReportsBuilder(int index) {
return getReportsFieldBuilder()
.addBuilder(
index, com.google.analytics.data.v1beta.RunReportResponse.getDefaultInstance());
}
/**
*
*
* <pre>
* Individual responses. Each response has a separate report request.
* </pre>
*
* <code>repeated .google.analytics.data.v1beta.RunReportResponse reports = 1;</code>
*/
public java.util.List<com.google.analytics.data.v1beta.RunReportResponse.Builder>
getReportsBuilderList() {
return getReportsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.data.v1beta.RunReportResponse,
com.google.analytics.data.v1beta.RunReportResponse.Builder,
com.google.analytics.data.v1beta.RunReportResponseOrBuilder>
getReportsFieldBuilder() {
if (reportsBuilder_ == null) {
reportsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.data.v1beta.RunReportResponse,
com.google.analytics.data.v1beta.RunReportResponse.Builder,
com.google.analytics.data.v1beta.RunReportResponseOrBuilder>(
reports_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
reports_ = null;
}
return reportsBuilder_;
}
private java.lang.Object kind_ = "";
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @return The kind.
*/
public java.lang.String getKind() {
java.lang.Object ref = kind_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
kind_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @return The bytes for kind.
*/
public com.google.protobuf.ByteString getKindBytes() {
java.lang.Object ref = kind_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
kind_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @param value The kind to set.
* @return This builder for chaining.
*/
public Builder setKind(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
kind_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearKind() {
kind_ = getDefaultInstance().getKind();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Identifies what kind of resource this message is. This `kind` is always the
* fixed string "analyticsData#batchRunReports". Useful to distinguish between
* response types in JSON.
* </pre>
*
* <code>string kind = 2;</code>
*
* @param value The bytes for kind to set.
* @return This builder for chaining.
*/
public Builder setKindBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
kind_ = 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.analytics.data.v1beta.BatchRunReportsResponse)
}
// @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.BatchRunReportsResponse)
private static final com.google.analytics.data.v1beta.BatchRunReportsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.BatchRunReportsResponse();
}
public static com.google.analytics.data.v1beta.BatchRunReportsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BatchRunReportsResponse> PARSER =
new com.google.protobuf.AbstractParser<BatchRunReportsResponse>() {
@java.lang.Override
public BatchRunReportsResponse 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<BatchRunReportsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BatchRunReportsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.data.v1beta.BatchRunReportsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 36,200 | jdk/src/share/classes/sun/swing/plaf/WindowsKeybindings.java | /*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.swing.plaf;
import javax.swing.JTextField;
import javax.swing.UIDefaults;
import javax.swing.text.DefaultEditorKit;
/**
* WindowsKeybindings - The standard set of keymaps for the Windows Platform
*
* @author Jasper Potts
*/
public class WindowsKeybindings {
/**
* Install all Windows keybindings into the provided UIDefaults table
*
* @param table The UiDefaults table to install into
*/
public static void installKeybindings(UIDefaults table) {
// *** Text
Object fieldInputMap = new UIDefaults.LazyInputMap(new Object[]{
"control C", DefaultEditorKit.copyAction,
"control V", DefaultEditorKit.pasteAction,
"control X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"control A", DefaultEditorKit.selectAllAction,
"control BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"control LEFT", DefaultEditorKit.previousWordAction,
"control RIGHT", DefaultEditorKit.nextWordAction,
"control shift LEFT", DefaultEditorKit.selectionPreviousWordAction,
"control shift RIGHT", DefaultEditorKit.selectionNextWordAction,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"ctrl DELETE", DefaultEditorKit.deleteNextWordAction,
"ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"ENTER", JTextField.notifyAction,
"control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/
});
Object passwordInputMap = new UIDefaults.LazyInputMap(new Object[]{
"control C", DefaultEditorKit.copyAction,
"control V", DefaultEditorKit.pasteAction,
"control X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"control A", DefaultEditorKit.selectAllAction,
"control BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"control LEFT", DefaultEditorKit.beginLineAction,
"control RIGHT", DefaultEditorKit.endLineAction,
"control shift LEFT", DefaultEditorKit.selectionBeginLineAction,
"control shift RIGHT", DefaultEditorKit.selectionEndLineAction,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"ENTER", JTextField.notifyAction,
"control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/
});
Object multilineInputMap = new UIDefaults.LazyInputMap(new Object[]{
"control C", DefaultEditorKit.copyAction,
"control V", DefaultEditorKit.pasteAction,
"control X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"control LEFT", DefaultEditorKit.previousWordAction,
"control RIGHT", DefaultEditorKit.nextWordAction,
"control shift LEFT", DefaultEditorKit.selectionPreviousWordAction,
"control shift RIGHT", DefaultEditorKit.selectionNextWordAction,
"control A", DefaultEditorKit.selectAllAction,
"control BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"control HOME", DefaultEditorKit.beginAction,
"control END", DefaultEditorKit.endAction,
"control shift HOME", DefaultEditorKit.selectionBeginAction,
"control shift END", DefaultEditorKit.selectionEndAction,
"UP", DefaultEditorKit.upAction,
"DOWN", DefaultEditorKit.downAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"ctrl DELETE", DefaultEditorKit.deleteNextWordAction,
"ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"PAGE_UP", DefaultEditorKit.pageUpAction,
"PAGE_DOWN", DefaultEditorKit.pageDownAction,
"shift PAGE_UP", "selection-page-up",
"shift PAGE_DOWN", "selection-page-down",
"ctrl shift PAGE_UP", "selection-page-left",
"ctrl shift PAGE_DOWN", "selection-page-right",
"shift UP", DefaultEditorKit.selectionUpAction,
"shift DOWN", DefaultEditorKit.selectionDownAction,
"ENTER", DefaultEditorKit.insertBreakAction,
"TAB", DefaultEditorKit.insertTabAction,
"control T", "next-link-action",
"control shift T", "previous-link-action",
"control SPACE", "activate-link-action",
"control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/
});
Object[] defaults = {
"TextField.focusInputMap", fieldInputMap,
"PasswordField.focusInputMap", passwordInputMap,
"TextArea.focusInputMap", multilineInputMap,
"TextPane.focusInputMap", multilineInputMap,
"EditorPane.focusInputMap", multilineInputMap,
"Button.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"SPACE", "pressed",
"released SPACE", "released"
}),
"CheckBox.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"SPACE", "pressed",
"released SPACE", "released"
}),
"ComboBox.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[]{
"ESCAPE", "hidePopup",
"PAGE_UP", "pageUpPassThrough",
"PAGE_DOWN", "pageDownPassThrough",
"HOME", "homePassThrough",
"END", "endPassThrough",
"DOWN", "selectNext2",
"KP_DOWN", "selectNext2",
"UP", "selectPrevious2",
"KP_UP", "selectPrevious2",
"ENTER", "enterPressed",
"F4", "togglePopup",
"alt DOWN", "togglePopup",
"alt KP_DOWN", "togglePopup",
"alt UP", "togglePopup",
"alt KP_UP", "togglePopup"
}),
"Desktop.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ctrl F5", "restore",
"ctrl F4", "close",
"ctrl F7", "move",
"ctrl F8", "resize",
"RIGHT", "right",
"KP_RIGHT", "right",
"LEFT", "left",
"KP_LEFT", "left",
"UP", "up",
"KP_UP", "up",
"DOWN", "down",
"KP_DOWN", "down",
"ESCAPE", "escape",
"ctrl F9", "minimize",
"ctrl F10", "maximize",
"ctrl F6", "selectNextFrame",
"ctrl TAB", "selectNextFrame",
"ctrl alt F6", "selectNextFrame",
"shift ctrl alt F6", "selectPreviousFrame",
"ctrl F12", "navigateNext",
"shift ctrl F12", "navigatePrevious"
}),
"FileChooser.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ESCAPE", "cancelSelection",
"F2", "editFileName",
"F5", "refresh",
"BACK_SPACE", "Go Up",
"ENTER", "approveSelection",
"ctrl ENTER", "approveSelection"
}),
"InternalFrame.windowBindings", new Object[]{
"shift ESCAPE", "showSystemMenu",
"ctrl SPACE", "showSystemMenu",
"ESCAPE", "hideSystemMenu"
},
"List.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"UP", "selectPreviousRow",
"KP_UP", "selectPreviousRow",
"shift UP", "selectPreviousRowExtendSelection",
"shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl shift UP", "selectPreviousRowExtendSelection",
"ctrl shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl UP", "selectPreviousRowChangeLead",
"ctrl KP_UP", "selectPreviousRowChangeLead",
"DOWN", "selectNextRow",
"KP_DOWN", "selectNextRow",
"shift DOWN", "selectNextRowExtendSelection",
"shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl shift DOWN", "selectNextRowExtendSelection",
"ctrl shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl DOWN", "selectNextRowChangeLead",
"ctrl KP_DOWN", "selectNextRowChangeLead",
"LEFT", "selectPreviousColumn",
"KP_LEFT", "selectPreviousColumn",
"shift LEFT", "selectPreviousColumnExtendSelection",
"shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl LEFT", "selectPreviousColumnChangeLead",
"ctrl KP_LEFT", "selectPreviousColumnChangeLead",
"RIGHT", "selectNextColumn",
"KP_RIGHT", "selectNextColumn",
"shift RIGHT", "selectNextColumnExtendSelection",
"shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl shift RIGHT", "selectNextColumnExtendSelection",
"ctrl shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl RIGHT", "selectNextColumnChangeLead",
"ctrl KP_RIGHT", "selectNextColumnChangeLead",
"HOME", "selectFirstRow",
"shift HOME", "selectFirstRowExtendSelection",
"ctrl shift HOME", "selectFirstRowExtendSelection",
"ctrl HOME", "selectFirstRowChangeLead",
"END", "selectLastRow",
"shift END", "selectLastRowExtendSelection",
"ctrl shift END", "selectLastRowExtendSelection",
"ctrl END", "selectLastRowChangeLead",
"PAGE_UP", "scrollUp",
"shift PAGE_UP", "scrollUpExtendSelection",
"ctrl shift PAGE_UP", "scrollUpExtendSelection",
"ctrl PAGE_UP", "scrollUpChangeLead",
"PAGE_DOWN", "scrollDown",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl PAGE_DOWN", "scrollDownChangeLead",
"ctrl A", "selectAll",
"ctrl SLASH", "selectAll",
"ctrl BACK_SLASH", "clearSelection",
"SPACE", "addToSelection",
"ctrl SPACE", "toggleAndAnchor",
"shift SPACE", "extendTo",
"ctrl shift SPACE", "moveSelectionTo"
}),
"MenuBar.windowBindings", new Object[]{
"F10", "takeFocus"
},
"RadioButton.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"SPACE", "pressed",
"released SPACE", "released"
}),
"OptionPane.windowBindings", new Object[]{
"ESCAPE", "close"
},
"FormattedTextField.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ctrl C", DefaultEditorKit.copyAction,
"ctrl V", DefaultEditorKit.pasteAction,
"ctrl X", DefaultEditorKit.cutAction,
"COPY", DefaultEditorKit.copyAction,
"PASTE", DefaultEditorKit.pasteAction,
"CUT", DefaultEditorKit.cutAction,
"control INSERT", DefaultEditorKit.copyAction,
"shift INSERT", DefaultEditorKit.pasteAction,
"shift DELETE", DefaultEditorKit.cutAction,
"shift LEFT", DefaultEditorKit.selectionBackwardAction,
"shift KP_LEFT", DefaultEditorKit.selectionBackwardAction,
"shift RIGHT", DefaultEditorKit.selectionForwardAction,
"shift KP_RIGHT", DefaultEditorKit.selectionForwardAction,
"ctrl LEFT", DefaultEditorKit.previousWordAction,
"ctrl KP_LEFT", DefaultEditorKit.previousWordAction,
"ctrl RIGHT", DefaultEditorKit.nextWordAction,
"ctrl KP_RIGHT", DefaultEditorKit.nextWordAction,
"ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction,
"ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction,
"ctrl A", DefaultEditorKit.selectAllAction,
"HOME", DefaultEditorKit.beginLineAction,
"END", DefaultEditorKit.endLineAction,
"shift HOME", DefaultEditorKit.selectionBeginLineAction,
"shift END", DefaultEditorKit.selectionEndLineAction,
"BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction,
"ctrl H", DefaultEditorKit.deletePrevCharAction,
"DELETE", DefaultEditorKit.deleteNextCharAction,
"ctrl DELETE", DefaultEditorKit.deleteNextWordAction,
"ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction,
"RIGHT", DefaultEditorKit.forwardAction,
"LEFT", DefaultEditorKit.backwardAction,
"KP_RIGHT", DefaultEditorKit.forwardAction,
"KP_LEFT", DefaultEditorKit.backwardAction,
"ENTER", JTextField.notifyAction,
"ctrl BACK_SLASH", "unselect",
"control shift O", "toggle-componentOrientation",
"ESCAPE", "reset-field-edit",
"UP", "increment",
"KP_UP", "increment",
"DOWN", "decrement",
"KP_DOWN", "decrement",
}),
"RootPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"shift F10", "postPopup",
"CONTEXT_MENU", "postPopup"
}),
// These bindings are only enabled when there is a default
// button set on the rootpane.
"RootPane.defaultButtonWindowKeyBindings", new Object[]{
"ENTER", "press",
"released ENTER", "release",
"ctrl ENTER", "press",
"ctrl released ENTER", "release"
},
"ScrollBar.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"RIGHT", "positiveUnitIncrement",
"KP_RIGHT", "positiveUnitIncrement",
"DOWN", "positiveUnitIncrement",
"KP_DOWN", "positiveUnitIncrement",
"PAGE_DOWN", "positiveBlockIncrement",
"ctrl PAGE_DOWN", "positiveBlockIncrement",
"LEFT", "negativeUnitIncrement",
"KP_LEFT", "negativeUnitIncrement",
"UP", "negativeUnitIncrement",
"KP_UP", "negativeUnitIncrement",
"PAGE_UP", "negativeBlockIncrement",
"ctrl PAGE_UP", "negativeBlockIncrement",
"HOME", "minScroll",
"END", "maxScroll"
}),
"ScrollPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"RIGHT", "unitScrollRight",
"KP_RIGHT", "unitScrollRight",
"DOWN", "unitScrollDown",
"KP_DOWN", "unitScrollDown",
"LEFT", "unitScrollLeft",
"KP_LEFT", "unitScrollLeft",
"UP", "unitScrollUp",
"KP_UP", "unitScrollUp",
"PAGE_UP", "scrollUp",
"PAGE_DOWN", "scrollDown",
"ctrl PAGE_UP", "scrollLeft",
"ctrl PAGE_DOWN", "scrollRight",
"ctrl HOME", "scrollHome",
"ctrl END", "scrollEnd"
}),
"Slider.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"RIGHT", "positiveUnitIncrement",
"KP_RIGHT", "positiveUnitIncrement",
"DOWN", "negativeUnitIncrement",
"KP_DOWN", "negativeUnitIncrement",
"PAGE_DOWN", "negativeBlockIncrement",
"LEFT", "negativeUnitIncrement",
"KP_LEFT", "negativeUnitIncrement",
"UP", "positiveUnitIncrement",
"KP_UP", "positiveUnitIncrement",
"PAGE_UP", "positiveBlockIncrement",
"HOME", "minScroll",
"END", "maxScroll"
}),
"Spinner.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"UP", "increment",
"KP_UP", "increment",
"DOWN", "decrement",
"KP_DOWN", "decrement",
}),
"SplitPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"UP", "negativeIncrement",
"DOWN", "positiveIncrement",
"LEFT", "negativeIncrement",
"RIGHT", "positiveIncrement",
"KP_UP", "negativeIncrement",
"KP_DOWN", "positiveIncrement",
"KP_LEFT", "negativeIncrement",
"KP_RIGHT", "positiveIncrement",
"HOME", "selectMin",
"END", "selectMax",
"F8", "startResize",
"F6", "toggleFocus",
"ctrl TAB", "focusOutForward",
"ctrl shift TAB", "focusOutBackward"
}),
"TabbedPane.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"RIGHT", "navigateRight",
"KP_RIGHT", "navigateRight",
"LEFT", "navigateLeft",
"KP_LEFT", "navigateLeft",
"UP", "navigateUp",
"KP_UP", "navigateUp",
"DOWN", "navigateDown",
"KP_DOWN", "navigateDown",
"ctrl DOWN", "requestFocusForVisibleComponent",
"ctrl KP_DOWN", "requestFocusForVisibleComponent",
}),
"TabbedPane.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ctrl TAB", "navigateNext",
"ctrl shift TAB", "navigatePrevious",
"ctrl PAGE_DOWN", "navigatePageDown",
"ctrl PAGE_UP", "navigatePageUp",
"ctrl UP", "requestFocus",
"ctrl KP_UP", "requestFocus",
}),
"TableHeader.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[] {
"SPACE", "toggleSortOrder",
"LEFT", "selectColumnToLeft",
"KP_LEFT", "selectColumnToLeft",
"RIGHT", "selectColumnToRight",
"KP_RIGHT", "selectColumnToRight",
"alt LEFT", "moveColumnLeft",
"alt KP_LEFT", "moveColumnLeft",
"alt RIGHT", "moveColumnRight",
"alt KP_RIGHT", "moveColumnRight",
"alt shift LEFT", "resizeLeft",
"alt shift KP_LEFT", "resizeLeft",
"alt shift RIGHT", "resizeRight",
"alt shift KP_RIGHT", "resizeRight",
"ESCAPE", "focusTable",
}),
"Table.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"RIGHT", "selectNextColumn",
"KP_RIGHT", "selectNextColumn",
"shift RIGHT", "selectNextColumnExtendSelection",
"shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl shift RIGHT", "selectNextColumnExtendSelection",
"ctrl shift KP_RIGHT", "selectNextColumnExtendSelection",
"ctrl RIGHT", "selectNextColumnChangeLead",
"ctrl KP_RIGHT", "selectNextColumnChangeLead",
"LEFT", "selectPreviousColumn",
"KP_LEFT", "selectPreviousColumn",
"shift LEFT", "selectPreviousColumnExtendSelection",
"shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift LEFT", "selectPreviousColumnExtendSelection",
"ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection",
"ctrl LEFT", "selectPreviousColumnChangeLead",
"ctrl KP_LEFT", "selectPreviousColumnChangeLead",
"DOWN", "selectNextRow",
"KP_DOWN", "selectNextRow",
"shift DOWN", "selectNextRowExtendSelection",
"shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl shift DOWN", "selectNextRowExtendSelection",
"ctrl shift KP_DOWN", "selectNextRowExtendSelection",
"ctrl DOWN", "selectNextRowChangeLead",
"ctrl KP_DOWN", "selectNextRowChangeLead",
"UP", "selectPreviousRow",
"KP_UP", "selectPreviousRow",
"shift UP", "selectPreviousRowExtendSelection",
"shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl shift UP", "selectPreviousRowExtendSelection",
"ctrl shift KP_UP", "selectPreviousRowExtendSelection",
"ctrl UP", "selectPreviousRowChangeLead",
"ctrl KP_UP", "selectPreviousRowChangeLead",
"HOME", "selectFirstColumn",
"shift HOME", "selectFirstColumnExtendSelection",
"ctrl shift HOME", "selectFirstRowExtendSelection",
"ctrl HOME", "selectFirstRow",
"END", "selectLastColumn",
"shift END", "selectLastColumnExtendSelection",
"ctrl shift END", "selectLastRowExtendSelection",
"ctrl END", "selectLastRow",
"PAGE_UP", "scrollUpChangeSelection",
"shift PAGE_UP", "scrollUpExtendSelection",
"ctrl shift PAGE_UP", "scrollLeftExtendSelection",
"ctrl PAGE_UP", "scrollLeftChangeSelection",
"PAGE_DOWN", "scrollDownChangeSelection",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl shift PAGE_DOWN", "scrollRightExtendSelection",
"ctrl PAGE_DOWN", "scrollRightChangeSelection",
"TAB", "selectNextColumnCell",
"shift TAB", "selectPreviousColumnCell",
"ENTER", "selectNextRowCell",
"shift ENTER", "selectPreviousRowCell",
"ctrl A", "selectAll",
"ctrl SLASH", "selectAll",
"ctrl BACK_SLASH", "clearSelection",
"ESCAPE", "cancel",
"F2", "startEditing",
"SPACE", "addToSelection",
"ctrl SPACE", "toggleAndAnchor",
"shift SPACE", "extendTo",
"ctrl shift SPACE", "moveSelectionTo",
"F8", "focusHeader"
}),
"ToggleButton.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"SPACE", "pressed",
"released SPACE", "released"
}),
"ToolBar.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"UP", "navigateUp",
"KP_UP", "navigateUp",
"DOWN", "navigateDown",
"KP_DOWN", "navigateDown",
"LEFT", "navigateLeft",
"KP_LEFT", "navigateLeft",
"RIGHT", "navigateRight",
"KP_RIGHT", "navigateRight"
}),
"Tree.focusInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ADD", "expand",
"SUBTRACT", "collapse",
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"UP", "selectPrevious",
"KP_UP", "selectPrevious",
"shift UP", "selectPreviousExtendSelection",
"shift KP_UP", "selectPreviousExtendSelection",
"ctrl shift UP", "selectPreviousExtendSelection",
"ctrl shift KP_UP", "selectPreviousExtendSelection",
"ctrl UP", "selectPreviousChangeLead",
"ctrl KP_UP", "selectPreviousChangeLead",
"DOWN", "selectNext",
"KP_DOWN", "selectNext",
"shift DOWN", "selectNextExtendSelection",
"shift KP_DOWN", "selectNextExtendSelection",
"ctrl shift DOWN", "selectNextExtendSelection",
"ctrl shift KP_DOWN", "selectNextExtendSelection",
"ctrl DOWN", "selectNextChangeLead",
"ctrl KP_DOWN", "selectNextChangeLead",
"RIGHT", "selectChild",
"KP_RIGHT", "selectChild",
"LEFT", "selectParent",
"KP_LEFT", "selectParent",
"PAGE_UP", "scrollUpChangeSelection",
"shift PAGE_UP", "scrollUpExtendSelection",
"ctrl shift PAGE_UP", "scrollUpExtendSelection",
"ctrl PAGE_UP", "scrollUpChangeLead",
"PAGE_DOWN", "scrollDownChangeSelection",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl shift PAGE_DOWN", "scrollDownExtendSelection",
"ctrl PAGE_DOWN", "scrollDownChangeLead",
"HOME", "selectFirst",
"shift HOME", "selectFirstExtendSelection",
"ctrl shift HOME", "selectFirstExtendSelection",
"ctrl HOME", "selectFirstChangeLead",
"END", "selectLast",
"shift END", "selectLastExtendSelection",
"ctrl shift END", "selectLastExtendSelection",
"ctrl END", "selectLastChangeLead",
"F2", "startEditing",
"ctrl A", "selectAll",
"ctrl SLASH", "selectAll",
"ctrl BACK_SLASH", "clearSelection",
"ctrl LEFT", "scrollLeft",
"ctrl KP_LEFT", "scrollLeft",
"ctrl RIGHT", "scrollRight",
"ctrl KP_RIGHT", "scrollRight",
"SPACE", "addToSelection",
"ctrl SPACE", "toggleAndAnchor",
"shift SPACE", "extendTo",
"ctrl shift SPACE", "moveSelectionTo"
}),
"Tree.ancestorInputMap",
new UIDefaults.LazyInputMap(new Object[]{
"ESCAPE", "cancel"
}),
};
table.putDefaults(defaults);
}
}
|
apache/derby | 36,734 | java/org.apache.derby.engine/org/apache/derby/iapi/jdbc/InternalDriver.java | /*
Derby - Class org.apache.derby.iapi.jdbc.InternalDriver
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.iapi.jdbc;
import java.security.AccessController;
import java.security.AccessControlException;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import javax.sql.PooledConnection;
import javax.sql.XAConnection;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.reference.Attribute;
import org.apache.derby.shared.common.reference.MessageId;
import org.apache.derby.shared.common.reference.Module;
import org.apache.derby.shared.common.reference.Property;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.iapi.security.SecurityUtil;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.shared.common.i18n.MessageService;
import org.apache.derby.iapi.services.io.FormatableProperties;
import org.apache.derby.iapi.services.jmx.ManagementService;
import org.apache.derby.iapi.services.monitor.ModuleControl;
import org.apache.derby.iapi.services.monitor.ModuleFactory;
import org.apache.derby.iapi.services.monitor.Monitor;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;
import org.apache.derby.iapi.sql.ResultSet;
import org.apache.derby.iapi.util.InterruptStatus;
import org.apache.derby.impl.jdbc.*;
import org.apache.derby.mbeans.JDBCMBean;
import org.apache.derby.shared.common.security.SystemPermission;
/**
* Factory class and API for JDBC objects.
*/
public class InternalDriver implements ModuleControl, Driver {
private static final Object syncMe = new Object();
private static InternalDriver activeDriver;
private Object mbean;
protected boolean active;
private ContextService contextServiceFactory;
private AuthenticationService authenticationService;
/**
* Tells whether or not {@code AutoloadedDriver} should deregister itself
* on shutdown. This flag is true unless the deregister attribute has been
* set to false by the user (DERBY-2905).
*/
private static boolean deregister = true;
/**
* <p>
* An executor service used for executing connection attempts when a
* login timeout has been specified.
* </p>
*
* <p>
* DERBY-6107: Core pool size and keep alive timeout should be zero so
* that no threads are cached. By creating a fresh thread each time a
* task is submitted, we make sure that the task will run in a thread
* with the same context class loader as the thread that submitted the
* task. This is important for example when connecting to a database
* using the classpath subsubprotocol, and the database lives in the
* context class loader. If threads are cached, a task may execute in
* a thread that has a different context class loader.
* </p>
*/
private static final ExecutorService _executorPool =
new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), new DaemonThreadFactory());
public static final InternalDriver activeDriver()
{
return activeDriver;
}
public InternalDriver() {
contextServiceFactory = getContextService();
}
/*
** Methods from ModuleControl
*/
public void boot(boolean create, Properties properties) throws StandardException {
synchronized (InternalDriver.syncMe)
{
InternalDriver.activeDriver = this;
}
active = true;
mbean = ((ManagementService)
getSystemModule(Module.JMX)).registerMBean(
new JDBC(this),
JDBCMBean.class,
"type=JDBC");
// Register with the driver manager
AutoloadedDriver.registerDriverModule(this);
}
public void stop() {
synchronized (InternalDriver.syncMe)
{
InternalDriver.activeDriver = null;
}
((ManagementService)
getSystemModule(Module.JMX)).unregisterMBean(
mbean);
active = false;
contextServiceFactory = null;
AutoloadedDriver.unregisterDriverModule();
}
/*
** Methods from java.sql.Driver
*/
public boolean acceptsURL(String url) throws SQLException
{
return active && embeddedDriverAcceptsURL( url );
}
/*
** This method can be called by AutoloadedDriver so that we
** don't accidentally boot Derby while answering the question "Can
** you handle this URL?"
*/
public static boolean embeddedDriverAcceptsURL(String url) throws SQLException
{
if ( url == null )
{
throw Util.generateCsSQLException( SQLState.MALFORMED_URL, "null" );
}
return
// need to reject network driver's URL's
!url.startsWith(Attribute.JCC_PROTOCOL) && !url.startsWith(Attribute.DNC_PROTOCOL) &&
(url.startsWith(Attribute.PROTOCOL) || url.equals(Attribute.SQLJ_NESTED));
}
public Connection connect( String url, Properties info, int loginTimeoutSeconds )
throws SQLException
{
if (!acceptsURL(url)) { return null; }
/**
* If we are below the low memory watermark for obtaining
* a connection, then don't even try. Just throw an exception.
*/
if (EmbedConnection.memoryState.isLowMemory())
{
throw EmbedConnection.NO_MEM;
}
/*
** A url "jdbc:default:connection" means get the current
** connection. From within a method called from JSQL, the
** "current" connection is the one that is running the
** JSQL statement containing the method call.
*/
boolean current = url.equals(Attribute.SQLJ_NESTED);
/* If jdbc:default:connection, see if user already has a
* connection. All connection attributes are ignored.
*/
if (current) {
ConnectionContext connContext = getConnectionContext();
if (connContext != null) {
return connContext.getNestedConnection(false);
}
// there is no Derby connection, so
// return null, as we are not the driver to handle this
return null;
}
// convert the ;name=value attributes in the URL into
// properties.
FormatableProperties finfo = null;
try {
finfo = getAttributes(url, info);
info = null; // ensure we don't use this reference directly again.
/*
** A property "shutdown=true" means shut the system or database down
*/
boolean shutdown = Boolean.valueOf(finfo.getProperty(Attribute.SHUTDOWN_ATTR)).booleanValue();
if (shutdown) {
// If we are shutting down the system don't attempt to create
// a connection; but we validate users credentials if we have to.
// In case of datbase shutdown, we ask the database authentication
// service to authenticate the user. If it is a system shutdown,
// then we ask the Driver to do the authentication.
//
if (InternalDriver.getDatabaseName(url, finfo).length() == 0) {
//
// We need to authenticate the user if authentication is
// ON. Note that this is a system shutdown.
// check that we do have a authentication service
// it is _always_ expected.
if (this.getAuthenticationService() == null)
throw Util.generateCsSQLException(
SQLState.LOGIN_FAILED,
MessageService.getTextMessage(MessageId.AUTH_NO_SERVICE_FOR_SYSTEM));
if (!this.getAuthenticationService().authenticate((String) null, finfo)) {
// not a valid user
throw Util.generateCsSQLException(
SQLState.NET_CONNECT_AUTH_FAILED,
MessageService.
getTextMessage(MessageId.AUTH_INVALID));
}
// DERBY-2905, allow users to provide deregister attribute to
// leave AutoloadedDriver registered in DriverManager, default
// value is true
if (finfo.getProperty(Attribute.DEREGISTER_ATTR) != null) {
boolean deregister = Boolean.valueOf(
finfo.getProperty(Attribute.DEREGISTER_ATTR))
.booleanValue();
InternalDriver.setDeregister(deregister);
}
// check for shutdown privileges
// DERBY-3495: uncomment to enable system privileges checks
//final String user = IdUtil.getUserNameFromURLProps(finfo);
//checkShutdownPrivileges(user);
getMonitor().shutdown();
throw Util.generateCsSQLException(
SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN);
}
}
EmbedConnection conn;
if ( loginTimeoutSeconds <= 0 ) { conn = getNewEmbedConnection( url, finfo ); }
else { conn = timeLogin( url, finfo, loginTimeoutSeconds ); }
// if this is not the correct driver a EmbedConnection
// object is returned in the closed state.
if (conn.isClosed()) {
return null;
}
return conn;
}
catch (OutOfMemoryError noMemory)
{
EmbedConnection.memoryState.setLowMemory();
throw EmbedConnection.NO_MEM;
}
finally {
// break any link with the user's Properties set.
if (finfo != null)
finfo.clearDefaults();
}
}
/**
* Enforce the login timeout.
*/
private EmbedConnection timeLogin(
String url, Properties info, int loginTimeoutSeconds)
throws SQLException
{
try {
LoginCallable callable = new LoginCallable(this, url, info);
Future<EmbedConnection> task = _executorPool.submit(callable);
long now = System.currentTimeMillis();
long giveUp = now + loginTimeoutSeconds * 1000L;
while (now < giveUp) {
try {
return task.get(giveUp - now, TimeUnit.MILLISECONDS);
} catch (InterruptedException ie) {
InterruptStatus.setInterrupted();
now = System.currentTimeMillis();
continue;
} catch (ExecutionException ee) {
throw processException(ee);
} catch (TimeoutException te) {
throw Util.generateCsSQLException(SQLState.LOGIN_TIMEOUT);
}
}
// Timed out due to interrupts, throw.
throw Util.generateCsSQLException(SQLState.LOGIN_TIMEOUT);
} finally {
InterruptStatus.restoreIntrFlagIfSeen();
}
}
/** Process exceptions raised while running a timed login. */
private SQLException processException(Throwable t) {
Throwable cause = t.getCause();
if (cause instanceof SQLException) {
return (SQLException) cause;
} else {
return Util.javaException(t);
}
}
/**
* Thread factory to produce daemon threads which don't block VM shutdown.
*/
private static final class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread result = new Thread(r);
result.setDaemon(true);
return result;
}
}
/**
* This code is called in a thread which puts time limits on it.
*/
public static final class LoginCallable implements
Callable<EmbedConnection> {
private InternalDriver _driver;
private String _url;
private Properties _info;
public LoginCallable(InternalDriver driver, String url, Properties info) {
_driver = driver;
_url = url;
_info = info;
}
public EmbedConnection call() throws SQLException {
// Erase the state variables after we use them.
// Might be paranoid but there could be security-sensitive info
// in here.
String url = _url;
Properties info = _info;
InternalDriver driver = _driver;
_url = null;
_info = null;
_driver = null;
return driver.getNewEmbedConnection(url, info);
}
}
/**
* Checks for System Privileges.
*
* @param user The user to be checked for having the permission
* @param perm The permission to be checked
* @throws AccessControlException if permissions are missing
*/
public void checkSystemPrivileges(String user, Permission perm) {
SecurityUtil.checkUserHasPermission(user, perm);
}
/**
* Checks for shutdown System Privileges.
*
* To perform this check the following policy grant is required
* <ul>
* <li> to run the encapsulated test:
* permission javax.security.auth.AuthPermission "doAsPrivileged";
* </ul>
* or a SQLException will be raised detailing the cause.
* <p>
* In addition, for the test to succeed
* <ul>
* <li> the given user needs to be covered by a grant:
* principal org.apache.derby.authentication.SystemPrincipal "..." {}
* <li> that lists a shutdown permission:
* permission org.apache.derby.shared.common.security.SystemPermission "shutdown";
* </ul>
* or it will fail with a SQLException detailing the cause.
*
* @param user The user to be checked for shutdown privileges
* @throws SQLException if the privileges check fails
*/
private void checkShutdownPrivileges(String user) throws SQLException {
// approve action if not running under a security manager
if (System.getSecurityManager() == null) {
return;
}
// the check
try {
final Permission sp = new SystemPermission(
SystemPermission.ENGINE, SystemPermission.SHUTDOWN);
checkSystemPrivileges(user, sp);
} catch (AccessControlException ace) {
throw Util.generateCsSQLException(
SQLState.AUTH_SHUTDOWN_MISSING_PERMISSION,
user, (Object)ace); // overloaded method
} catch (Exception e) {
throw Util.generateCsSQLException(
SQLState.AUTH_SHUTDOWN_MISSING_PERMISSION,
user, (Object)e); // overloaded method
}
}
public int getMajorVersion() {
return getMonitor().getEngineVersion().getMajorVersion();
}
public int getMinorVersion() {
return getMonitor().getEngineVersion().getMinorVersion();
}
public boolean jdbcCompliant() {
return true;
}
/*
** URL manipulation
*/
/**
Convert all the attributes in the url into properties and
combine them with the set provided.
<BR>
If the caller passed in a set of attributes (info != null)
then we set that up as the default of the returned property
set as the user's set. This means we can easily break the link
with the user's set, ensuring that we don't hang onto the users object.
It also means that we don't add our attributes into the user's
own property object.
@param url The properties-bearing URL
@param info Existing properties
@return a Derby properties object
@exception SQLException thrown if URL form bad
*/
protected FormatableProperties getAttributes(String url, Properties info)
throws SQLException {
// We use FormatableProperties here to take advantage
// of the clearDefaults, method.
FormatableProperties finfo = new FormatableProperties(info);
info = null; // ensure we don't use this reference directly again.
StringTokenizer st = new StringTokenizer(url, ";");
st.nextToken(); // skip the first part of the url
while (st.hasMoreTokens()) {
String v = st.nextToken();
int eqPos = v.indexOf('=');
if (eqPos == -1)
throw Util.generateCsSQLException(
SQLState.MALFORMED_URL, url);
//if (eqPos != v.lastIndexOf('='))
// throw Util.malformedURL(url);
finfo.put((v.substring(0, eqPos)).trim(),
(v.substring(eqPos + 1)).trim()
);
}
// now validate any attributes we can
//
// Boolean attributes -
// dataEncryption,create,createSource,convertToSource,shutdown,upgrade,current
checkBoolean(finfo, Attribute.DATA_ENCRYPTION);
checkBoolean(finfo, Attribute.CREATE_ATTR);
checkBoolean(finfo, Attribute.SHUTDOWN_ATTR);
checkBoolean(finfo, Attribute.DEREGISTER_ATTR);
checkBoolean(finfo, Attribute.UPGRADE_ATTR);
return finfo;
}
private static void checkBoolean(Properties set, String attribute) throws SQLException
{
final String[] booleanChoices = {"true", "false"};
checkEnumeration( set, attribute, booleanChoices);
}
private static void checkEnumeration(Properties set, String attribute, String[] choices) throws SQLException
{
String value = set.getProperty(attribute);
if (value == null)
return;
for( int i = 0; i < choices.length; i++)
{
if( value.toUpperCase(java.util.Locale.ENGLISH).equals( choices[i].toUpperCase(java.util.Locale.ENGLISH)))
return;
}
// The attribute value is invalid. Construct a string giving the choices for
// display in the error message.
String choicesStr = "{";
for( int i = 0; i < choices.length; i++)
{
if( i > 0)
choicesStr += "|";
choicesStr += choices[i];
}
throw Util.generateCsSQLException(
SQLState.INVALID_ATTRIBUTE, attribute, value, choicesStr + "}");
}
/**
Get the database name from the url.
Copes with three forms
jdbc:derby:dbname
jdbc:derby:dbname;...
jdbc:derby:;subname=dbname
@param url The url being used for the connection
@param info The properties set being used for the connection, must include
the properties derived from the attributes in the url
@return a String containing the database name or an empty string ("") if
no database name is present in the URL.
*/
public static String getDatabaseName(String url, Properties info) {
if (url.equals(Attribute.SQLJ_NESTED))
{
return "";
}
// skip the jdbc:derby:
int attributeStart = url.indexOf(';');
String dbname;
if (attributeStart == -1)
dbname = url.substring(Attribute.PROTOCOL.length());
else
dbname = url.substring(Attribute.PROTOCOL.length(), attributeStart);
// For security reasons we rely on here an non-null string being
// taken as the database name, before the databaseName connection
// attribute. Specifically, even if dbname is blank we still we
// to use it rather than the connection attribute, even though
// it will end up, after the trim, as a zero-length string.
// See EmbeddedDataSource.update()
if (dbname.length() == 0) {
if (info != null)
dbname = info.getProperty(Attribute.DBNAME_ATTR, dbname);
}
// Beetle 4653 - trim database name to remove blanks that might make a difference on finding the database
// on unix platforms
dbname = dbname.trim();
return dbname;
}
public final ContextService getContextServiceFactory() {
return contextServiceFactory;
}
// returns the authenticationService handle
public AuthenticationService getAuthenticationService() {
//
// If authenticationService handle not cached in yet, then
// ask the monitor to find it for us and set it here in its
// attribute.
//
if (this.authenticationService == null) {
this.authenticationService = (AuthenticationService)
findService(AuthenticationService.MODULE,
"authentication"
);
}
return this.authenticationService;
}
/*
Methods to be overloaded in sub-implementations such as
a tracing driver.
*/
EmbedConnection getNewEmbedConnection( final String url, final Properties info)
throws SQLException
{
final InternalDriver myself = this;
try {
return AccessController.doPrivileged
(
new PrivilegedExceptionAction<EmbedConnection>()
{
public EmbedConnection run()
throws SQLException
{
return new EmbedConnection(myself, url, info);
}
}
);
} catch (PrivilegedActionException pae)
{
Throwable cause = pae.getCause();
if ( (cause != null) && (cause instanceof SQLException) )
{
throw (SQLException) cause;
}
else
{
throw Util.javaException( pae );
}
}
}
private ConnectionContext getConnectionContext() {
/*
** The current connection is the one in the current
** connection context, so get the context.
*/
ContextManager cm = getCurrentContextManager();
ConnectionContext localCC = null;
/*
cm is null the very first time, and whenever
we aren't actually nested.
*/
if (cm != null) {
localCC = (ConnectionContext)
(cm.getContext(ConnectionContext.CONTEXT_ID));
}
return localCC;
}
private ContextManager getCurrentContextManager() {
return getContextServiceFactory().getCurrentContextManager();
}
/**
Return true if this driver is active. Package private method.
@return true if this driver is active
*/
public boolean isActive() {
return active;
}
/**
* Get a new nested connection.
*
* @param conn The EmbedConnection.
*
* @return A nested connection object.
*
*/
public Connection getNewNestedConnection(EmbedConnection conn) {
return new EmbedConnection(conn);
}
/*
** methods to be overridden by subimplementations wishing to insert
** their classes into the mix.
*/
public Statement newEmbedStatement(
EmbedConnection conn,
boolean forMetaData,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
{
return new EmbedStatement(conn, forMetaData, resultSetType,
resultSetConcurrency, resultSetHoldability);
}
/**
@param conn Derby connection
@param stmt Statement text
@param forMetaData True if this is for metadata
@param resultSetType Type of ResultSet
@param resultSetConcurrency Concurrency setting
@param resultSetHoldability Holdability setting
@param autoGeneratedKeys The autogenerated keys
@param columnIndexes Column positions
@param columnNames The column names
@return a PreparedStatement
@exception SQLException if fails to create statement
*/
public PreparedStatement newEmbedPreparedStatement(
EmbedConnection conn,
String stmt,
boolean forMetaData,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability,
int autoGeneratedKeys,
int[] columnIndexes,
String[] columnNames)
throws SQLException
{
return new EmbedPreparedStatement(conn,
stmt, forMetaData, resultSetType, resultSetConcurrency,
resultSetHoldability, autoGeneratedKeys, columnIndexes,
columnNames);
}
/**
@param conn Derby connection
@param stmt Statement text
@param resultSetType Type of ResultSet
@param resultSetConcurrency Concurrency setting
@param resultSetHoldability Holdability setting
@return a CallableStatement
@exception SQLException if fails to create statement
*/
public CallableStatement newEmbedCallableStatement(
EmbedConnection conn,
String stmt,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws SQLException
{
return new EmbedCallableStatement(conn, stmt, resultSetType,
resultSetConcurrency, resultSetHoldability);
}
/**
* Return a new java.sql.DatabaseMetaData instance for this implementation.
*
* @param conn Derby connection
* @param dbname Database name
* @return a new java.sql.DatabaseMetaData instance for this implementation
* @exception SQLException on failure to create.
*/
public DatabaseMetaData newEmbedDatabaseMetaData(
EmbedConnection conn, String dbname) throws SQLException {
return new EmbedDatabaseMetaData(conn, dbname);
}
/**
* Return a new java.sql.ResultSet instance for this implementation.
* @param conn Owning connection
* @param results Top level of language result set tree
* @param forMetaData Is this for meta-data
* @param statement The statement that is creating the SQL ResultSet
* @param isAtomic True if the ResultSet is atomic
* @return a new java.sql.ResultSet
* @throws SQLException on error
*/
public EmbedResultSet newEmbedResultSet(EmbedConnection conn,
ResultSet results, boolean forMetaData, EmbedStatement statement,
boolean isAtomic) throws SQLException {
return new EmbedResultSet(conn, results, forMetaData, statement,
isAtomic);
}
/**
* Returns a new java.sql.ResultSetMetaData for this implementation
*
* @param columnInfo a ResultColumnDescriptor that stores information
* about the columns in a ResultSet
* @return ResultSet metadata
*/
public EmbedResultSetMetaData newEmbedResultSetMetaData(
ResultColumnDescriptor[] columnInfo) {
return new EmbedResultSetMetaData(columnInfo);
}
/**
* Return a new BrokeredConnection for this implementation.
*
* @param control Control variable
* @return a brokered connection
*
* @throws SQLException on error
*/
public BrokeredConnection newBrokeredConnection(
BrokeredConnectionControl control) throws SQLException {
return new BrokeredConnection(control);
}
private static final String[] BOOLEAN_CHOICES = {"false", "true"};
/**
* <p>The getPropertyInfo method is intended to allow a generic GUI tool to
* discover what properties it should prompt a human for in order to get
* enough information to connect to a database. Note that depending on
* the values the human has supplied so far, additional values may become
* necessary, so it may be necessary to iterate though several calls
* to getPropertyInfo.
*
* @param url The URL of the database to connect to.
* @param info A proposed list of tag/value pairs that will be sent on
* connect open.
* @return An array of DriverPropertyInfo objects describing possible
* properties. This array may be an empty array if no properties
* are required.
* @exception SQLException if a database-access error occurs.
*/
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
throws SQLException {
// RESOLVE other properties should be added into this method in the future ...
if (info != null) {
if (Boolean.valueOf(info.getProperty(Attribute.SHUTDOWN_ATTR)).booleanValue()) {
// no other options possible when shutdown is set to be true
return new DriverPropertyInfo[0];
}
}
// at this point we have databaseName,
String dbname = InternalDriver.getDatabaseName(url, info);
// convert the ;name=value attributes in the URL into
// properties.
FormatableProperties finfo = getAttributes(url, info);
info = null; // ensure we don't use this reference directly again.
boolean encryptDB = Boolean.valueOf(finfo.getProperty(Attribute.DATA_ENCRYPTION)).booleanValue();
String encryptpassword = finfo.getProperty(Attribute.BOOT_PASSWORD);
if (dbname.length() == 0 || (encryptDB && encryptpassword == null)) {
// with no database name we can have shutdown or a database name
// In future, if any new attribute info needs to be included in this
// method, it just has to be added to either string or boolean or secret array
// depending on whether it accepts string or boolean or secret(ie passwords) value.
String[][] connStringAttributes = {
{Attribute.DBNAME_ATTR, MessageId.CONN_DATABASE_IDENTITY},
{Attribute.CRYPTO_PROVIDER, MessageId.CONN_CRYPTO_PROVIDER},
{Attribute.CRYPTO_ALGORITHM, MessageId.CONN_CRYPTO_ALGORITHM},
{Attribute.CRYPTO_KEY_LENGTH, MessageId.CONN_CRYPTO_KEY_LENGTH},
{Attribute.CRYPTO_EXTERNAL_KEY, MessageId.CONN_CRYPTO_EXTERNAL_KEY},
{Attribute.TERRITORY, MessageId.CONN_LOCALE},
{Attribute.COLLATION, MessageId.CONN_COLLATION},
{Attribute.USERNAME_ATTR, MessageId.CONN_USERNAME_ATTR},
{Attribute.LOG_DEVICE, MessageId.CONN_LOG_DEVICE},
{Attribute.ROLL_FORWARD_RECOVERY_FROM, MessageId.CONN_ROLL_FORWARD_RECOVERY_FROM},
{Attribute.CREATE_FROM, MessageId.CONN_CREATE_FROM},
{Attribute.RESTORE_FROM, MessageId.CONN_RESTORE_FROM},
};
String[][] connBooleanAttributes = {
{Attribute.SHUTDOWN_ATTR, MessageId.CONN_SHUT_DOWN_CLOUDSCAPE},
{Attribute.DEREGISTER_ATTR, MessageId.CONN_DEREGISTER_AUTOLOADEDDRIVER},
{Attribute.CREATE_ATTR, MessageId.CONN_CREATE_DATABASE},
{Attribute.DATA_ENCRYPTION, MessageId.CONN_DATA_ENCRYPTION},
{Attribute.UPGRADE_ATTR, MessageId.CONN_UPGRADE_DATABASE},
};
String[][] connStringSecretAttributes = {
{Attribute.BOOT_PASSWORD, MessageId.CONN_BOOT_PASSWORD},
{Attribute.PASSWORD_ATTR, MessageId.CONN_PASSWORD_ATTR},
};
DriverPropertyInfo[] optionsNoDB = new DriverPropertyInfo[connStringAttributes.length+
connBooleanAttributes.length+
connStringSecretAttributes.length];
int attrIndex = 0;
for( int i = 0; i < connStringAttributes.length; i++, attrIndex++ )
{
optionsNoDB[attrIndex] = new DriverPropertyInfo(connStringAttributes[i][0],
finfo.getProperty(connStringAttributes[i][0]));
optionsNoDB[attrIndex].description = MessageService.getTextMessage(connStringAttributes[i][1]);
}
optionsNoDB[0].choices = getMonitor().getServiceList(Property.DATABASE_MODULE);
// since database name is not stored in FormatableProperties, we
// assign here explicitly
optionsNoDB[0].value = dbname;
for( int i = 0; i < connStringSecretAttributes.length; i++, attrIndex++ )
{
optionsNoDB[attrIndex] = new DriverPropertyInfo(connStringSecretAttributes[i][0],
(finfo.getProperty(connStringSecretAttributes[i][0]) == null? "" : "****"));
optionsNoDB[attrIndex].description = MessageService.getTextMessage(connStringSecretAttributes[i][1]);
}
for( int i = 0; i < connBooleanAttributes.length; i++, attrIndex++ )
{
optionsNoDB[attrIndex] = new DriverPropertyInfo(connBooleanAttributes[i][0],
Boolean.valueOf(finfo == null? "" : finfo.getProperty(connBooleanAttributes[i][0])).toString());
optionsNoDB[attrIndex].description = MessageService.getTextMessage(connBooleanAttributes[i][1]);
optionsNoDB[attrIndex].choices = BOOLEAN_CHOICES;
}
return optionsNoDB;
}
return new DriverPropertyInfo[0];
}
public Connection connect(String url, Properties info) throws SQLException {
return connect(url, info, DriverManager.getLoginTimeout());
}
////////////////////////////////////////////////////////////////////
//
// INTRODUCED BY JDBC 4.1 IN JAVA 7
//
////////////////////////////////////////////////////////////////////
public Logger getParentLogger()
throws SQLFeatureNotSupportedException {
throw (SQLFeatureNotSupportedException)
Util.notImplemented("getParentLogger()");
}
/**
* Indicate to {@code AutoloadedDriver} whether it should deregister
* itself on shutdown.
*
* @param deregister whether or not {@code AutoloadedDriver} should
* deregister itself
*/
public static void setDeregister(boolean deregister) {
InternalDriver.deregister = deregister;
}
/**
* Check whether {@code AutoloadedDriver} should deregister itself on
* shutdown.
*
* @return the deregister value
*/
public static boolean getDeregister() {
return InternalDriver.deregister;
}
/**
* Privileged lookup of the ContextService. Must be private so that user code
* can't call this entry point.
*/
private static ContextService getContextService()
{
return AccessController.doPrivileged
(
new PrivilegedAction<ContextService>()
{
public ContextService run()
{
return ContextService.getFactory();
}
}
);
}
/**
* Privileged Monitor lookup. Must be private so that user code
* can't call this entry point.
*/
private static ModuleFactory getMonitor()
{
return AccessController.doPrivileged
(
new PrivilegedAction<ModuleFactory>()
{
public ModuleFactory run()
{
return Monitor.getMonitor();
}
}
);
}
/**
* Privileged module lookup. Must be private so that user code
* can't call this entry point.
*/
private static Object getSystemModule( final String factoryInterface )
{
return AccessController.doPrivileged
(
new PrivilegedAction<Object>()
{
public Object run()
{
return Monitor.getSystemModule( factoryInterface );
}
}
);
}
/**
* Privileged service lookup. Must be private so that user code
* can't call this entry point.
*/
private static Object findService( final String factoryInterface, final String serviceName )
{
return AccessController.doPrivileged
(
new PrivilegedAction<Object>()
{
public Object run()
{
return Monitor.findService( factoryInterface, serviceName );
}
}
);
}
}
|
googleapis/google-cloud-java | 37,402 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/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/aiplatform/v1beta1/session_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [SessionService.ListSessions][google.cloud.aiplatform.v1beta1.SessionService.ListSessions].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListSessionsResponse}
*/
public final class ListSessionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.SessionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSessionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.SessionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSessionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse.Builder.class);
}
public static final int SESSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Session> sessions_;
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Session> getSessionsList() {
return sessions_;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.SessionOrBuilder>
getSessionsOrBuilderList() {
return sessions_;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
@java.lang.Override
public int getSessionsCount() {
return sessions_.size();
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Session getSessions(int index) {
return sessions_.get(index);
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.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>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < 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.aiplatform.v1beta1.ListSessionsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse other =
(com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListSessionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListSessionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.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 message for
* [SessionService.ListSessions][google.cloud.aiplatform.v1beta1.SessionService.ListSessions].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListSessionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListSessionsResponse)
com.google.cloud.aiplatform.v1beta1.ListSessionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.SessionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSessionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.SessionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSessionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.SessionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSessionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSessionsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListSessionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSessionsResponse build() {
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSessionsResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListSessionsResponse result =
new com.google.cloud.aiplatform.v1beta1.ListSessionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListSessionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListSessionsResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Session m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Session> sessions_ =
java.util.Collections.emptyList();
private void ensureSessionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
sessions_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Session>(sessions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Session,
com.google.cloud.aiplatform.v1beta1.Session.Builder,
com.google.cloud.aiplatform.v1beta1.SessionOrBuilder>
sessionsBuilder_;
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Session> getSessionsList() {
if (sessionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(sessions_);
} else {
return sessionsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public int getSessionsCount() {
if (sessionsBuilder_ == null) {
return sessions_.size();
} else {
return sessionsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Session getSessions(int index) {
if (sessionsBuilder_ == null) {
return sessions_.get(index);
} else {
return sessionsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder setSessions(int index, com.google.cloud.aiplatform.v1beta1.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>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder setSessions(
int index, com.google.cloud.aiplatform.v1beta1.Session.Builder builderForValue) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.set(index, builderForValue.build());
onChanged();
} else {
sessionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder addSessions(com.google.cloud.aiplatform.v1beta1.Session value) {
if (sessionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSessionsIsMutable();
sessions_.add(value);
onChanged();
} else {
sessionsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder addSessions(int index, com.google.cloud.aiplatform.v1beta1.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>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder addSessions(
com.google.cloud.aiplatform.v1beta1.Session.Builder builderForValue) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.add(builderForValue.build());
onChanged();
} else {
sessionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder addSessions(
int index, com.google.cloud.aiplatform.v1beta1.Session.Builder builderForValue) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.add(index, builderForValue.build());
onChanged();
} else {
sessionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder addAllSessions(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Session> values) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, sessions_);
onChanged();
} else {
sessionsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.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>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public Builder removeSessions(int index) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.remove(index);
onChanged();
} else {
sessionsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Session.Builder getSessionsBuilder(int index) {
return getSessionsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.SessionOrBuilder getSessionsOrBuilder(int index) {
if (sessionsBuilder_ == null) {
return sessions_.get(index);
} else {
return sessionsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.SessionOrBuilder>
getSessionsOrBuilderList() {
if (sessionsBuilder_ != null) {
return sessionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(sessions_);
}
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Session.Builder addSessionsBuilder() {
return getSessionsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Session.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Session.Builder addSessionsBuilder(int index) {
return getSessionsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Session.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of sessions matching the request.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Session sessions = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Session.Builder>
getSessionsBuilderList() {
return getSessionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Session,
com.google.cloud.aiplatform.v1beta1.Session.Builder,
com.google.cloud.aiplatform.v1beta1.SessionOrBuilder>
getSessionsFieldBuilder() {
if (sessionsBuilder_ == null) {
sessionsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Session,
com.google.cloud.aiplatform.v1beta1.Session.Builder,
com.google.cloud.aiplatform.v1beta1.SessionOrBuilder>(
sessions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
sessions_ = null;
}
return sessionsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListSessionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListSessionsRequest.page_token]
* to retrieve the next page. Absence of this field indicates there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ListSessionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListSessionsResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListSessionsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListSessionsResponse();
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListSessionsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/flink | 37,570 | flink-runtime/src/test/java/org/apache/flink/runtime/asyncprocessing/operators/AsyncIntervalJoinOperatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.asyncprocessing.operators;
import org.apache.flink.api.common.serialization.SerializerConfigImpl;
import org.apache.flink.api.common.state.v2.MapState;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.runtime.asyncprocessing.operators.co.AsyncIntervalJoinOperator;
import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.util.TestHarnessUtil;
import org.apache.flink.streaming.util.asyncprocessing.AsyncKeyedTwoInputStreamOperatorTestHarness;
import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension;
import org.apache.flink.testutils.junit.extensions.parameterized.Parameters;
import org.apache.flink.util.Collector;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.OutputTag;
import org.apache.flink.shaded.guava33.com.google.common.collect.Iterables;
import org.apache.flink.shaded.guava33.com.google.common.collect.Lists;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link AsyncIntervalJoinOperator}. Those tests cover correctness and cleaning of state
*/
@ExtendWith(ParameterizedTestExtension.class)
class AsyncIntervalJoinOperatorTest {
private final boolean lhsFasterThanRhs;
@Parameters(name = "lhs faster than rhs: {0}")
private static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{true}, {false}});
}
public AsyncIntervalJoinOperatorTest(boolean lhsFasterThanRhs) {
this.lhsFasterThanRhs = lhsFasterThanRhs;
}
@TestTemplate
void testImplementationMirrorsCorrectly() throws Exception {
long lowerBound = 1;
long upperBound = 3;
boolean lowerBoundInclusive = true;
boolean upperBoundInclusive = false;
setupHarness(lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 2),
streamRecordOf(1, 3),
streamRecordOf(2, 3),
streamRecordOf(2, 4),
streamRecordOf(3, 4))
.noLateRecords()
.close();
setupHarness(-1 * upperBound, upperBoundInclusive, -1 * lowerBound, lowerBoundInclusive)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(2, 1),
streamRecordOf(3, 1),
streamRecordOf(3, 2),
streamRecordOf(4, 2),
streamRecordOf(4, 3))
.noLateRecords()
.close();
}
@TestTemplate // lhs - 2 <= rhs <= rhs + 2
void testNegativeInclusiveAndNegativeInclusive() throws Exception {
setupHarness(-2, true, -1, true)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(2, 1),
streamRecordOf(3, 1),
streamRecordOf(3, 2),
streamRecordOf(4, 2),
streamRecordOf(4, 3))
.noLateRecords()
.close();
}
@TestTemplate // lhs - 1 <= rhs <= rhs + 1
void testNegativeInclusiveAndPositiveInclusive() throws Exception {
setupHarness(-1, true, 1, true)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 1),
streamRecordOf(1, 2),
streamRecordOf(2, 1),
streamRecordOf(2, 2),
streamRecordOf(2, 3),
streamRecordOf(3, 2),
streamRecordOf(3, 3),
streamRecordOf(3, 4),
streamRecordOf(4, 3),
streamRecordOf(4, 4))
.noLateRecords()
.close();
}
@TestTemplate // lhs + 1 <= rhs <= lhs + 2
void testPositiveInclusiveAndPositiveInclusive() throws Exception {
setupHarness(1, true, 2, true)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 2),
streamRecordOf(1, 3),
streamRecordOf(2, 3),
streamRecordOf(2, 4),
streamRecordOf(3, 4))
.noLateRecords()
.close();
}
@TestTemplate
void testNegativeExclusiveAndNegativeExlusive() throws Exception {
setupHarness(-3, false, -1, false)
.processElementsAndWatermarks(1, 4)
.andExpect(streamRecordOf(3, 1), streamRecordOf(4, 2))
.noLateRecords()
.close();
}
@TestTemplate
void testNegativeExclusiveAndPositiveExlusive() throws Exception {
setupHarness(-1, false, 1, false)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 1),
streamRecordOf(2, 2),
streamRecordOf(3, 3),
streamRecordOf(4, 4))
.noLateRecords()
.close();
}
@TestTemplate
void testPositiveExclusiveAndPositiveExlusive() throws Exception {
setupHarness(1, false, 3, false)
.processElementsAndWatermarks(1, 4)
.andExpect(streamRecordOf(1, 3), streamRecordOf(2, 4))
.noLateRecords()
.close();
}
@TestTemplate
void testStateCleanupNegativeInclusiveNegativeInclusive() throws Exception {
setupHarness(-1, true, 0, true)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(2, 3, 4, 5)
.assertRightBufferContainsOnly(1, 2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(5)
.assertRightBufferContainsOnly(4, 5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testStateCleanupNegativePositiveNegativeExlusive() throws Exception {
setupHarness(-2, false, 1, false)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(2, 3, 4, 5)
.assertRightBufferContainsOnly(1, 2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(5)
.assertRightBufferContainsOnly(4, 5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testStateCleanupPositiveInclusivePositiveInclusive() throws Exception {
setupHarness(0, true, 1, true)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(1, 2, 3, 4, 5)
.assertRightBufferContainsOnly(2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(4, 5)
.assertRightBufferContainsOnly(5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testStateCleanupPositiveExlusivePositiveExclusive() throws Exception {
setupHarness(-1, false, 2, false)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(1, 2, 3, 4, 5)
.assertRightBufferContainsOnly(2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(4, 5)
.assertRightBufferContainsOnly(5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testRestoreFromSnapshot() throws Exception {
// config
int lowerBound = -1;
boolean lowerBoundInclusive = true;
int upperBound = 1;
boolean upperBoundInclusive = true;
// create first test harness
OperatorSubtaskState handles;
List<StreamRecord<Tuple2<TestElem, TestElem>>> expectedOutput;
try (TestHarness testHarness =
createTestHarness(
lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)) {
testHarness.setup();
testHarness.open();
// process elements with first test harness
testHarness.processElement1(createStreamRecord(1, "lhs"));
testHarness.processWatermark1(new Watermark(1));
testHarness.processElement2(createStreamRecord(1, "rhs"));
testHarness.processWatermark2(new Watermark(1));
testHarness.processElement1(createStreamRecord(2, "lhs"));
testHarness.processWatermark1(new Watermark(2));
testHarness.processElement2(createStreamRecord(2, "rhs"));
testHarness.processWatermark2(new Watermark(2));
testHarness.processElement1(createStreamRecord(3, "lhs"));
testHarness.processWatermark1(new Watermark(3));
testHarness.processElement2(createStreamRecord(3, "rhs"));
testHarness.processWatermark2(new Watermark(3));
// snapshot and validate output
handles = testHarness.snapshot(0, 0);
expectedOutput =
Lists.newArrayList(
streamRecordOf(1, 1),
streamRecordOf(1, 2),
streamRecordOf(2, 1),
streamRecordOf(2, 2),
streamRecordOf(2, 3),
streamRecordOf(3, 2),
streamRecordOf(3, 3));
TestHarnessUtil.assertNoLateRecords(testHarness.getOutput());
assertOutput(expectedOutput, testHarness.getOutput());
}
try (TestHarness newTestHarness =
createTestHarness(
lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)) {
// create new test harness from snapshpt
newTestHarness.setup();
newTestHarness.initializeState(handles);
newTestHarness.open();
// process elements
newTestHarness.processElement1(createStreamRecord(4, "lhs"));
newTestHarness.processWatermark1(new Watermark(4));
newTestHarness.processElement2(createStreamRecord(4, "rhs"));
newTestHarness.processWatermark2(new Watermark(4));
// assert expected output
expectedOutput =
Lists.newArrayList(
streamRecordOf(3, 4), streamRecordOf(4, 3), streamRecordOf(4, 4));
TestHarnessUtil.assertNoLateRecords(newTestHarness.getOutput());
assertOutput(expectedOutput, newTestHarness.getOutput());
}
}
@TestTemplate
void testContextCorrectLeftTimestamp() throws Exception {
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new AsyncIntervalJoinOperator<>(
-1,
1,
true,
true,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
assertThat(ctx.getLeftTimestamp()).isEqualTo(left.ts);
}
});
try (TestHarness testHarness =
TestHarness.createOne(
op,
(elem) -> elem.key,
(elem) -> elem.key,
TypeInformation.of(String.class))) {
testHarness.setup();
testHarness.open();
processElementsAndWatermarks(testHarness);
}
}
@TestTemplate
void testReturnsCorrectTimestamp() throws Exception {
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new AsyncIntervalJoinOperator<>(
-1,
1,
true,
true,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
private static final long serialVersionUID = 1L;
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
assertThat(ctx.getTimestamp())
.isEqualTo(Math.max(left.ts, right.ts));
}
});
try (TestHarness testHarness =
TestHarness.createOne(
op,
(elem) -> elem.key,
(elem) -> elem.key,
TypeInformation.of(String.class))) {
testHarness.setup();
testHarness.open();
processElementsAndWatermarks(testHarness);
}
}
@TestTemplate
void testContextCorrectRightTimestamp() throws Exception {
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new AsyncIntervalJoinOperator<>(
-1,
1,
true,
true,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
assertThat(ctx.getRightTimestamp()).isEqualTo(right.ts);
}
});
try (TestHarness testHarness =
TestHarness.createOne(
op,
(elem) -> elem.key,
(elem) -> elem.key,
TypeInformation.of(String.class))) {
testHarness.setup();
testHarness.open();
processElementsAndWatermarks(testHarness);
}
}
@TestTemplate
void testFailsWithNoTimestampsLeft() throws Exception {
try (TestHarness newTestHarness = createTestHarness(0L, true, 0L, true)) {
newTestHarness.setup();
newTestHarness.open();
// note that the StreamRecord has no timestamp in constructor
assertThatThrownBy(
() ->
newTestHarness.processElement1(
new StreamRecord<>(new TestElem(0, "lhs"))))
.isInstanceOf(FlinkException.class);
}
}
@TestTemplate // (expected = FlinkException.class)
void testFailsWithNoTimestampsRight() throws Exception {
try (TestHarness newTestHarness = createTestHarness(0L, true, 0L, true)) {
newTestHarness.setup();
newTestHarness.open();
// note that the StreamRecord has no timestamp in constructor
assertThatThrownBy(
() ->
newTestHarness.processElement2(
new StreamRecord<>(new TestElem(0, "rhs"))))
.isInstanceOf(FlinkException.class);
}
}
@TestTemplate
void testDiscardsLateData() throws Exception {
setupHarness(-1, true, 1, true)
.processElement1(1)
.processElement2(1)
.processElement1(2)
.processElement2(2)
.processElement1(3)
.processElement2(3)
.processWatermark1(3)
.processWatermark2(3)
.processElement1(1) // this element is late and should not be joined again
.processElement1(4)
.processElement2(4)
.processElement1(5)
.processElement2(5)
.andExpect(
streamRecordOf(1, 1),
streamRecordOf(1, 2),
streamRecordOf(2, 1),
streamRecordOf(2, 2),
streamRecordOf(2, 3),
streamRecordOf(3, 2),
streamRecordOf(3, 3),
streamRecordOf(3, 4),
streamRecordOf(4, 3),
streamRecordOf(4, 4),
streamRecordOf(4, 5),
streamRecordOf(5, 4),
streamRecordOf(5, 5))
.noLateRecords()
.close();
}
@TestTemplate
void testLateData() throws Exception {
OutputTag<TestElem> leftLateTag = new OutputTag<TestElem>("left_late") {};
OutputTag<TestElem> rightLateTag = new OutputTag<TestElem>("right_late") {};
setupHarness(-1, true, 1, true, leftLateTag, rightLateTag)
.processElement1(3)
.processElement2(3)
.processWatermark1(3)
.processWatermark2(3)
.processElement1(4)
.processElement2(4)
.processElement1(1) // the left side element is late
.processElement2(2) // the right side element is late
.processElement1(5)
.processElement2(5)
.andExpect(
streamRecordOf(3, 3),
streamRecordOf(3, 4),
streamRecordOf(4, 3),
streamRecordOf(4, 4),
streamRecordOf(4, 5),
streamRecordOf(5, 4),
streamRecordOf(5, 5))
.expectLateRecords(leftLateTag, createStreamRecord(1, "lhs"))
.expectLateRecords(rightLateTag, createStreamRecord(2, "rhs"))
.close();
}
private void assertEmpty(MapState<Long, ?> state) throws Exception {
assertThat(state.keys()).isEmpty();
}
private void assertContainsOnly(MapState<Long, ?> state, long... ts) throws Exception {
for (long t : ts) {
String message =
"Keys not found in state. \n Expected: "
+ Arrays.toString(ts)
+ "\n Actual: "
+ state.keys();
assertThat(state.contains(t)).as(message).isTrue();
}
String message =
"Too many objects in state. \n Expected: "
+ Arrays.toString(ts)
+ "\n Actual: "
+ state.keys();
assertThat(state.keys()).as(message).hasSize(ts.length);
}
private <T1, T2> void assertOutput(
Iterable<StreamRecord<T1>> expectedOutput, Queue<T2> actualOutput) {
int actualSize =
actualOutput.stream()
.filter(elem -> elem instanceof StreamRecord)
.collect(Collectors.toList())
.size();
int expectedSize = Iterables.size(expectedOutput);
assertThat(actualSize)
.as("Expected and actual size of stream records different")
.isEqualTo(expectedSize);
for (StreamRecord<T1> record : expectedOutput) {
assertThat(actualOutput.contains(record)).isTrue();
}
}
private TestHarness createTestHarness(
long lowerBound,
boolean lowerBoundInclusive,
long upperBound,
boolean upperBoundInclusive)
throws Exception {
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> operator =
new AsyncIntervalJoinOperator<>(
lowerBound,
upperBound,
lowerBoundInclusive,
upperBoundInclusive,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new PassthroughFunction());
return TestHarness.createOne(
operator,
(elem) -> elem.key, // key
(elem) -> elem.key, // key
TypeInformation.of(String.class));
}
private JoinTestBuilder setupHarness(
long lowerBound,
boolean lowerBoundInclusive,
long upperBound,
boolean upperBoundInclusive,
OutputTag<TestElem> leftLateDataOutputTag,
OutputTag<TestElem> rightLateDataOutputTag)
throws Exception {
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> operator =
new AsyncIntervalJoinOperator<>(
lowerBound,
upperBound,
lowerBoundInclusive,
upperBoundInclusive,
leftLateDataOutputTag,
rightLateDataOutputTag,
TestElem.serializer(),
TestElem.serializer(),
new PassthroughFunction());
TestHarness t =
TestHarness.createOne(
operator,
(elem) -> elem.key, // key
(elem) -> elem.key, // key
TypeInformation.of(String.class));
return new JoinTestBuilder(t, operator);
}
private JoinTestBuilder setupHarness(
long lowerBound,
boolean lowerBoundInclusive,
long upperBound,
boolean upperBoundInclusive)
throws Exception {
return setupHarness(
lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive, null, null);
}
private class JoinTestBuilder {
private AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
operator;
private TestHarness testHarness;
public JoinTestBuilder(
TestHarness t,
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
operator)
throws Exception {
this.testHarness = t;
this.operator = operator;
t.open();
t.setup();
}
public TestHarness get() {
return testHarness;
}
public JoinTestBuilder processElement1(int ts) throws Exception {
testHarness.processElement1(createStreamRecord(ts, "lhs"));
return this;
}
public JoinTestBuilder processElement2(int ts) throws Exception {
testHarness.processElement2(createStreamRecord(ts, "rhs"));
return this;
}
public JoinTestBuilder processWatermark1(int ts) throws Exception {
testHarness.processWatermark1(new Watermark(ts));
return this;
}
public JoinTestBuilder processWatermark2(int ts) throws Exception {
testHarness.processWatermark2(new Watermark(ts));
return this;
}
public JoinTestBuilder processElementsAndWatermarks(int from, int to) throws Exception {
if (lhsFasterThanRhs) {
// add to lhs
for (int i = from; i <= to; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
// add to rhs
for (int i = from; i <= to; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
} else {
// add to rhs
for (int i = from; i <= to; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
// add to lhs
for (int i = from; i <= to; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
}
return this;
}
@SafeVarargs
public final JoinTestBuilder andExpect(StreamRecord<Tuple2<TestElem, TestElem>>... elems) {
assertOutput(Lists.newArrayList(elems), testHarness.getOutput());
return this;
}
public JoinTestBuilder assertLeftBufferContainsOnly(long... timestamps) {
try {
assertContainsOnly(operator.getLeftBuffer(), timestamps);
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertRightBufferContainsOnly(long... timestamps) {
try {
assertContainsOnly(operator.getRightBuffer(), timestamps);
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertLeftBufferEmpty() {
try {
assertEmpty(operator.getLeftBuffer());
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertRightBufferEmpty() {
try {
assertEmpty(operator.getRightBuffer());
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
@SafeVarargs
public final JoinTestBuilder expectLateRecords(
OutputTag<TestElem> tag, StreamRecord<TestElem>... elems) {
assertOutput(Lists.newArrayList(elems), testHarness.getSideOutput(tag));
return this;
}
public JoinTestBuilder noLateRecords() {
TestHarnessUtil.assertNoLateRecords(this.testHarness.getOutput());
return this;
}
public void close() throws Exception {
testHarness.close();
}
}
private static class PassthroughFunction
extends ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>> {
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
out.collect(Tuple2.of(left, right));
}
}
private StreamRecord<Tuple2<TestElem, TestElem>> streamRecordOf(long lhsTs, long rhsTs) {
TestElem lhs = new TestElem(lhsTs, "lhs");
TestElem rhs = new TestElem(rhsTs, "rhs");
long ts = Math.max(lhsTs, rhsTs);
return new StreamRecord<>(Tuple2.of(lhs, rhs), ts);
}
private static class TestElem {
String key;
long ts;
String source;
public TestElem(long ts, String source) {
this.key = "key";
this.ts = ts;
this.source = source;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestElem testElem = (TestElem) o;
if (ts != testElem.ts) {
return false;
}
if (key != null ? !key.equals(testElem.key) : testElem.key != null) {
return false;
}
return source != null ? source.equals(testElem.source) : testElem.source == null;
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (int) (ts ^ (ts >>> 32));
result = 31 * result + (source != null ? source.hashCode() : 0);
return result;
}
@Override
public String toString() {
return this.source + ":" + this.ts;
}
public static TypeSerializer<TestElem> serializer() {
return TypeInformation.of(new TypeHint<AsyncIntervalJoinOperatorTest.TestElem>() {})
.createSerializer(new SerializerConfigImpl());
}
}
private static StreamRecord<TestElem> createStreamRecord(long ts, String source) {
TestElem testElem = new TestElem(ts, source);
return new StreamRecord<>(testElem, ts);
}
private void processElementsAndWatermarks(TestHarness testHarness) throws Exception {
if (lhsFasterThanRhs) {
// add to lhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
// add to rhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
} else {
// add to rhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
// add to lhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
}
}
/** Custom test harness to avoid endless generics in all of the test code. */
private static class TestHarness
extends AsyncKeyedTwoInputStreamOperatorTestHarness<
String, TestElem, TestElem, Tuple2<TestElem, TestElem>> {
public TestHarness(
ExecutorService executor,
TwoInputStreamOperator<TestElem, TestElem, Tuple2<TestElem, TestElem>> operator,
KeySelector<TestElem, String> keySelector1,
KeySelector<TestElem, String> keySelector2,
TypeInformation<String> keyType)
throws Exception {
super(executor, operator, keySelector1, keySelector2, keyType, 1, 1, 0);
}
public static TestHarness createOne(
TwoInputStreamOperator<TestElem, TestElem, Tuple2<TestElem, TestElem>> operator,
KeySelector<TestElem, String> keySelector1,
KeySelector<TestElem, String> keySelector2,
TypeInformation<String> keyType)
throws Exception {
return AsyncKeyedTwoInputStreamOperatorTestHarness.create(
(executor) ->
new TestHarness(
executor, operator, keySelector1, keySelector2, keyType));
}
}
}
|
google/j2objc | 35,571 | jre_emul/android/platform/libcore/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/CalendarTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tests.java.util;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.apache.harmony.testframework.serialization.SerializationTest;
public class CalendarTest extends junit.framework.TestCase {
Locale defaultLocale;
/**
* java.util.Calendar#set(int, int)
*/
public void test_setII() {
// Test for correct result defined by the last set field
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
cal.clear();
cal.set(Calendar.YEAR, 2002);
assertTrue("Incorrect result 0: " + cal.getTime().getTime(), cal
.getTime().getTime() == 1009861200000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.MONTH, Calendar.MARCH);
assertTrue("Incorrect result 0a: " + cal.getTime(), cal.getTime()
.getTime() == 1014958800000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 24);
assertTrue("Incorrect result 0b: " + cal.getTime(), cal.getTime()
.getTime() == 1011848400000L);
cal.set(Calendar.MONTH, Calendar.OCTOBER);
cal.set(Calendar.DATE, 31);
cal.set(Calendar.MONTH, Calendar.NOVEMBER);
cal.set(Calendar.DATE, 26);
assertTrue("Incorrect month: " + cal.get(Calendar.MONTH), cal
.get(Calendar.MONTH) == Calendar.NOVEMBER);
int dow = cal.get(Calendar.DAY_OF_WEEK);
cal.set(Calendar.DATE, 27);
assertTrue("Incorrect DAY_OF_WEEK: " + cal.get(Calendar.DAY_OF_WEEK)
+ " expected: " + dow, cal.get(Calendar.DAY_OF_WEEK) != dow);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
assertTrue("Incorrect result 0c1: " + cal.getTime().getTime(), cal
.getTime().getTime() == 1010379600000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
assertTrue("Incorrect result 0c2: " + cal.getTime().getTime(), cal
.getTime().getTime() == 1009861200000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
assertTrue("Incorrect result 0c3: " + cal.getTime(), cal.getTime()
.getTime() == 1010034000000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_MONTH, 2);
assertTrue("Incorrect result 0d: " + cal.getTime(), cal.getTime()
.getTime() == 1010293200000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
assertTrue("Incorrect result 0e: " + cal.getTime(), cal.getTime()
.getTime() == 1010898000000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 11);
assertTrue("Incorrect result 0f: " + cal.getTime(), cal.getTime()
.getTime() == 1015736400000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.WEEK_OF_YEAR, 11);
assertTrue("Incorrect result 0g: " + cal.getTime(), cal.getTime()
.getTime() == 1011848400000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.get(Calendar.WEEK_OF_YEAR); // Force fields to compute
cal.set(Calendar.WEEK_OF_YEAR, 11);
assertTrue("Incorrect result 0h: " + cal.getTime(), cal.getTime()
.getTime() == 1015909200000L);
// WEEK_OF_YEAR has priority over MONTH/DATE
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_YEAR, 170);
cal.set(Calendar.WEEK_OF_YEAR, 11);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 5);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
assertTrue("Incorrect result 1: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// WEEK_OF_YEAR has priority over MONTH/DATE
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 11);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 5);
cal.set(Calendar.DAY_OF_YEAR, 170);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
assertTrue("Incorrect result 1a: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DAY_OF_WEEK has no effect when other fields not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
assertTrue("Incorrect result 1b: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// Regression for HARMONY-4384
// Set DAY_OF_WEEK without DATE
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
assertEquals("Incorrect result 1b: " + cal.getTime(), 1015304400000L, cal.getTime()
.getTime());
// WEEK_OF_MONTH has priority
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
cal.set(Calendar.WEEK_OF_MONTH, 3);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DATE, 5);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
assertTrue("Incorrect result 2: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DAY_OF_WEEK_IN_MONTH has priority over WEEK_OF_YEAR
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DATE, 5);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
assertTrue("Incorrect result 3: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// WEEK_OF_MONTH has priority, MONTH not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
cal.set(Calendar.WEEK_OF_MONTH, 3);
cal.set(Calendar.DATE, 25);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
assertTrue("Incorrect result 4: " + cal.getTime(), cal.getTime()
.getTime() == 1010984400000L);
// WEEK_OF_YEAR has priority when MONTH set last and DAY_OF_WEEK set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 11);
cal.set(Calendar.DATE, 25);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.MONTH, Calendar.JANUARY);
assertTrue("Incorrect result 5: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// Use MONTH/DATE when WEEK_OF_YEAR set but not DAY_OF_WEEK
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.MONTH, Calendar.MARCH);
assertTrue("Incorrect result 5a: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// Use MONTH/DATE when DAY_OF_WEEK is not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.WEEK_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.MARCH);
assertTrue("Incorrect result 5b: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// WEEK_OF_MONTH has priority
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DATE, 5);
cal.set(Calendar.WEEK_OF_MONTH, 3);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.MONTH, Calendar.MARCH);
assertTrue("Incorrect result 5c: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DATE has priority when set last
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DATE, 11);
assertTrue("Incorrect result 6: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DATE has priority when set last, MONTH not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 12);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.DATE, 14);
assertTrue("Incorrect result 7: " + cal.getTime(), cal.getTime()
.getTime() == 1010984400000L);
// DAY_OF_YEAR has priority when MONTH set last and DATE not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_YEAR, 70);
cal.set(Calendar.MONTH, Calendar.JANUARY);
assertTrue("Incorrect result 8: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DAY/MONTH has priority when DATE set after DAY_OF_YEAR
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_YEAR, 170);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.MONTH, Calendar.MARCH);
assertTrue("Incorrect result 8a: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DAY_OF_YEAR has priority when set after DATE
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 15);
cal.set(Calendar.DAY_OF_YEAR, 70);
cal.set(Calendar.MONTH, Calendar.JANUARY);
assertTrue("Incorrect result 8b: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DATE has priority when set last
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_YEAR, 70);
cal.set(Calendar.DATE, 14);
assertTrue("Incorrect result 9: " + cal.getTime(), cal.getTime()
.getTime() == 1010984400000L);
// DATE has priority when set last
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_YEAR, 15);
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
cal.set(Calendar.DATE, 14);
assertTrue("Incorrect result 9a: " + cal.getTime(), cal.getTime()
.getTime() == 1010984400000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.DATE, 14);
cal.set(Calendar.WEEK_OF_YEAR, 11);
assertTrue("Incorrect result 9b: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 14);
cal.set(Calendar.WEEK_OF_YEAR, 11);
assertTrue("Incorrect result 9c: " + cal.getTime(), cal.getTime()
.getTime() == 1010984400000L);
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.WEEK_OF_MONTH, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DATE, 11);
assertTrue("Incorrect result 9d: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// DAY_OF_YEAR has priority when DAY_OF_MONTH set last and other fields
// not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_YEAR, 70);
cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
assertTrue("Incorrect result 10: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// MONTH/DATE has priority when DAY_OF_WEEK_IN_MONTH set last but
// DAY_OF_WEEK not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
assertTrue("Incorrect result 11: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// MONTH/DATE has priority when WEEK_OF_YEAR set last but DAY_OF_WEEK
// not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.WEEK_OF_YEAR, 15);
assertTrue("Incorrect result 12: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// MONTH/DATE has priority when WEEK_OF_MONTH set last but DAY_OF_WEEK
// not set
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DATE, 11);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.WEEK_OF_MONTH, 1);
assertTrue("Incorrect result 13: " + cal.getTime(), cal.getTime()
.getTime() == 1015822800000L);
// Ensure last date field set is reset after computing
cal.clear();
cal.set(Calendar.YEAR, 2002);
cal.set(Calendar.DAY_OF_YEAR, 111);
cal.get(Calendar.YEAR);
cal.set(Calendar.MONTH, Calendar.MARCH);
cal.set(Calendar.AM_PM, Calendar.AM);
assertTrue("Incorrect result 14: " + cal.getTime(), cal.getTime()
.getTime() == 1016686800000L);
int hour = cal.get(Calendar.HOUR);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.AM_PM, Calendar.PM);
assertEquals("AM_PM not changed", Calendar.PM, cal.get(Calendar.AM_PM));
// setting AM_PM without HOUR should not have any affect
cal.set(Calendar.AM_PM, Calendar.AM);
assertEquals("AM_PM was changed 1",
Calendar.AM, cal.get(Calendar.AM_PM));
int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
hour = cal.get(Calendar.HOUR);
cal.set(Calendar.AM_PM, Calendar.PM);
assertEquals("AM_PM was changed 2",
Calendar.PM, cal.get(Calendar.AM_PM));
assertEquals(hour, cal.get(Calendar.HOUR));
assertEquals(hourOfDay + 12, cal.get(Calendar.HOUR_OF_DAY));
// regression test for Harmony-2122
cal = Calendar.getInstance();
int oldValue = cal.get(Calendar.AM_PM);
int newValue = (oldValue == Calendar.AM) ? Calendar.PM : Calendar.AM;
cal.set(Calendar.AM_PM, newValue);
newValue = cal.get(Calendar.AM_PM);
assertTrue(newValue != oldValue);
}
/**
* java.util.Calendar#setTime(java.util.Date)
*/
public void test_setTimeLjava_util_Date() {
Calendar cal = Calendar.getInstance();
// Use millisecond time for testing in Core
cal.setTime(new Date(884581200000L)); // (98, Calendar.JANUARY, 12)
assertEquals("incorrect millis", 884581200000L, cal.getTime().getTime());
cal.setTimeZone(TimeZone.getTimeZone("EST"));
cal.setTime(new Date(943506000000L)); // (99, Calendar.NOVEMBER, 25)
assertTrue("incorrect fields", cal.get(Calendar.YEAR) == 1999
&& cal.get(Calendar.MONTH) == Calendar.NOVEMBER
&& cal.get(Calendar.DATE) == 25);
}
/**
* java.util.Calendar#compareTo(Calendar)
*/
public void test_compareToLjava_util_Calendar_null() {
Calendar cal = Calendar.getInstance();
try {
cal.compareTo(null);
fail("should throw NullPointerException");
} catch (NullPointerException e) {
// expected
}
}
/**
* java.util.Calendar#compareTo(Calendar)
*/
public void test_compareToLjava_util_Calendar() {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1997, 12, 13, 23, 57);
Calendar anotherCal = Calendar.getInstance();
anotherCal.clear();
anotherCal.set(1997, 12, 13, 23, 57);
assertEquals(0, cal.compareTo(anotherCal));
anotherCal = Calendar.getInstance();
anotherCal.clear();
anotherCal.set(1997, 11, 13, 24, 57);
assertEquals(1, cal.compareTo(anotherCal));
anotherCal = Calendar.getInstance();
anotherCal.clear();
anotherCal.set(1997, 12, 13, 23, 58);
assertEquals(-1, cal.compareTo(anotherCal));
}
/**
* java.util.Calendar#clone()
*/
public void test_clone() {
// Regression for HARMONY-475
Calendar cal = Calendar.getInstance();
cal.set(2006, 5, 6, 11, 35);
Calendar anotherCal = (Calendar) cal.clone();
// should be deep clone
assertNotSame("getTimeZone", cal.getTimeZone(), anotherCal
.getTimeZone());
}
/**
* java.util.Calendar#getTimeInMillis()
*/
public void test_getTimeInMillis() {
Calendar cal = Calendar.getInstance();
int year = Integer.MIN_VALUE + 71;
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.set(Calendar.YEAR, year + 1900);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(6017546357372606464L, cal.getTimeInMillis());
}
private static final Locale[] locales = new Locale[] { Locale.getDefault(),
Locale.US, Locale.UK, Locale.TAIWAN, Locale.PRC, Locale.KOREA,
Locale.JAPAN, Locale.ITALIAN, Locale.GERMAN, Locale.ENGLISH,
Locale.CHINA, Locale.CANADA, Locale.FRANCE };
/**
* java.util.Calendar#before(Object)
* java.util.Calendar#after(Object)
*/
public void test_before_after() {
Calendar early = Calendar.getInstance();
Calendar late = Calendar.getInstance();
// test by second
early.set(2008, 3, 20, 17, 28, 12);
late.set(2008, 3, 20, 17, 28, 22);
// test before()
assertTrue(early.before(late));
assertFalse(early.before(early));
assertFalse(late.before(early));
// test after();
assertTrue(late.after(early));
assertFalse(late.after(late));
assertFalse(early.after(late));
// test by minute
early.set(2008, 3, 20, 17, 18, 12);
late.set(2008, 3, 20, 17, 28, 12);
// test before()
assertTrue(early.before(late));
assertFalse(early.before(early));
assertFalse(late.before(early));
// test after();
assertTrue(late.after(early));
assertFalse(late.after(late));
assertFalse(early.after(late));
// test by hour
early.set(2008, 3, 20, 17, 28, 12);
late.set(2008, 3, 20, 27, 28, 12);
// test before()
assertTrue(early.before(late));
assertFalse(early.before(early));
assertFalse(late.before(early));
// test after();
assertTrue(late.after(early));
assertFalse(late.after(late));
assertFalse(early.after(late));
// test by day
early.set(2008, 3, 10, 17, 28, 12);
late.set(2008, 3, 20, 17, 28, 12);
// test before()
assertTrue(early.before(late));
assertFalse(early.before(early));
assertFalse(late.before(early));
// test after();
assertTrue(late.after(early));
assertFalse(late.after(late));
assertFalse(early.after(late));
// test by month
early.set(2008, 2, 20, 17, 28, 12);
late.set(2008, 3, 20, 17, 28, 12);
// test before()
assertTrue(early.before(late));
assertFalse(early.before(early));
assertFalse(late.before(early));
// test after();
assertTrue(late.after(early));
assertFalse(late.after(late));
assertFalse(early.after(late));
// test by year
early.set(2007, 3, 20, 17, 28, 12);
late.set(2008, 3, 20, 17, 28, 12);
// test before()
assertTrue(early.before(late));
assertFalse(early.before(early));
assertFalse(late.before(early));
// test after();
assertTrue(late.after(early));
assertFalse(late.after(late));
assertFalse(early.after(late));
}
/**
* java.util.Calendar#clear()
* java.util.Calendar#clear(int)
*/
public void test_clear() {
Calendar calendar = Calendar.getInstance();
int count = 6;
int[] fields = new int[count];
int[] defaults = new int[count];
fields[0] = Calendar.YEAR;
fields[1] = Calendar.MONTH;
fields[2] = Calendar.DATE;
fields[3] = Calendar.HOUR_OF_DAY;
fields[4] = Calendar.MINUTE;
fields[5] = Calendar.SECOND;
defaults[0] = 1970;
defaults[1] = 0;
defaults[2] = 1;
defaults[3] = 0;
defaults[4] = 0;
defaults[5] = 0;
calendar.set(2008, 3, 20, 17, 28, 12);
// test clear(int)
for (int i = 0; i < fields.length; i++) {
int index = fields[i];
calendar.clear(index);
if (5 == index) {
// RI also doesn't change the value of DATE
assertEquals("Field " + index + " Should equal to 20.", 20,
calendar.get(index));
} else if (11 == index) {
// RI also doesn't change the value of HOUR
assertEquals("Field " + index + " Should equal to 17.", 17,
calendar.get(index));
} else {
// Other have been set to default values
assertEquals("Field " + index + " Should equal to "
+ defaults[i] + ".", defaults[i], calendar.get(index));
}
}
// test clear()
calendar.set(2008, 3, 20, 17, 28, 12);
calendar.clear();
for (int i = 0; i < fields.length; i++) {
int index = fields[i];
assertEquals("Field " + index + " Should equal to "
+ defaults[i] + ".", defaults[i], calendar.get(index));
}
}
/**
* java.util.Calendar#isSet(int)
*/
public void test_isSet() {
Calendar calendar = Calendar.getInstance();
calendar.clear();
for (int i = 0; i < Calendar.FIELD_COUNT; i++) {
assertFalse(calendar.isSet(i));
}
}
/**
* java.util.Calendar#getAvailableLocales()
*/
public void test_getAvailableLocales() {
Locale[] locales = Calendar.getAvailableLocales();
boolean exist = false;
for (int i = 0; i < locales.length; i++) {
Locale l = locales[i];
if (Locale.US.equals(l)) {
exist = true;
break;
}
}
assertTrue(exist);
}
/**
* java.util.Calendar#getInstance(Locale)
* java.util.Calendar#getInstance(TimeZone, Locale)
*/
public void test_getInstance() {
// test getInstance(Locale)
Calendar us_calendar = Calendar.getInstance(Locale.US);
Calendar de_calendar = Calendar.getInstance(Locale.GERMAN);
assertEquals(Calendar.SUNDAY, us_calendar
.getFirstDayOfWeek());
assertEquals(Calendar.MONDAY, de_calendar
.getFirstDayOfWeek());
// test getInstance(Locale, TimeZone)
Calendar gmt_calendar = Calendar.getInstance(TimeZone
.getTimeZone("GMT"), Locale.US);
assertEquals(TimeZone.getTimeZone("GMT"),
gmt_calendar.getTimeZone());
Calendar est_calendar = Calendar.getInstance(TimeZone
.getTimeZone("EST"), Locale.US);
assertEquals(TimeZone.getTimeZone("EST")
.getID(), est_calendar.getTimeZone().getID());
}
/**
* java.util.Calendar#internalGet(int)
*/
public void test_internalGet() {
MockGregorianCalendar c = new MockGregorianCalendar();
c.clear(Calendar.YEAR);
assertEquals(0, c.internal_get(Calendar.YEAR));
}
/**
* java.util.Calendar#hashCode()
*/
public void test_hashcode() {
Calendar calendar = Calendar.getInstance(Locale.JAPAN);
assertTrue(calendar.hashCode() == calendar.hashCode());
}
/**
* java.util.Calendar#roll(int, int)
*/
public void test_roll() {
Calendar calendar = Calendar.getInstance();
calendar.set(2008, 3, 20, 17, 28, 12);
// roll up
calendar.roll(Calendar.DATE, 5);
assertEquals(25, calendar.get(Calendar.DATE));
// roll down
calendar.roll(Calendar.DATE, -5);
assertEquals(20, calendar.get(Calendar.DATE));
// roll 0
calendar.roll(Calendar.DATE, 0);
assertEquals(20, calendar.get(Calendar.DATE));
// roll overweight
calendar.set(2008, 1, 31, 17, 28, 12);
calendar.roll(Calendar.MONTH, 1);
assertEquals(2, calendar.get(Calendar.DATE));
}
/**
* java.util.Calendar#toString()
*/
public void test_toString() {
Calendar calendar = Calendar.getInstance();
//Should be the current time with no interrogation in the string.
assertTrue(calendar.toString() instanceof String);
assertEquals(-1, calendar.toString().indexOf("?"));
calendar.clear();
assertTrue(calendar.toString() instanceof String);
assertTrue(0 <= calendar.toString().indexOf("?"));
}
/**
* serialization/deserialization.
* J2ObjC: Calendar/TimeZone serialization is broken. (b/34764665)
public void testSerializationSelf() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.set(2008, 3, 20, 17, 28, 12);
SerializationTest.verifySelf(calendar);
}*/
private class MockGregorianCalendar extends GregorianCalendar {
public int internal_get(int field) {
return super.internalGet(field);
}
}
private class MockCalendar extends Calendar {
public MockCalendar() {
super();
}
@Override
public void add(int field, int value) {
}
@Override
protected void computeFields() {
}
@Override
protected void computeTime() {
}
@Override
public int getGreatestMinimum(int field) {
return 0;
}
@Override
public int getLeastMaximum(int field) {
return 0;
}
@Override
public int getMaximum(int field) {
return 0;
}
@Override
public int getMinimum(int field) {
return 0;
}
@Override
public void roll(int field, boolean increment) {
}
}
/**
* {@link java.util.Calendar#getDisplayName(int, int, Locale)}
* @since 1.6
*/
public void test_getDisplayNameIILjava_util_Locale() {
Calendar cal = Calendar.getInstance();
for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
for (Locale locale : locales) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String value = null;
switch (field) {
case Calendar.AM_PM:
cal.set(Calendar.AM_PM, Calendar.AM);
value = symbols.getAmPmStrings()[0];
assertEquals(cal.getDisplayName(field, Calendar.SHORT,
locale), value);
assertEquals(cal.getDisplayName(field, Calendar.LONG,
locale), value);
cal.set(Calendar.AM_PM, Calendar.PM);
value = symbols.getAmPmStrings()[1];
assertEquals(cal.getDisplayName(field, Calendar.SHORT,
locale), value);
assertEquals(cal.getDisplayName(field, Calendar.LONG,
locale), value);
break;
case Calendar.ERA:
cal.set(Calendar.ERA, GregorianCalendar.BC);
value = symbols.getEras()[0];
assertEquals(cal.getDisplayName(field, Calendar.SHORT,
locale), value);
assertEquals(cal.getDisplayName(field, Calendar.LONG,
locale), value);
cal.set(Calendar.ERA, GregorianCalendar.AD);
value = symbols.getEras()[1];
assertEquals(cal.getDisplayName(field, Calendar.SHORT,
locale), value);
assertEquals(cal.getDisplayName(field, Calendar.LONG,
locale), value);
break;
case Calendar.MONTH:
cal.set(Calendar.DAY_OF_MONTH, 1);
for (int month = 0; month <= 11; month++) {
cal.set(Calendar.MONTH, month);
value = symbols.getShortMonths()[month];
assertEquals(cal.getDisplayName(field, Calendar.SHORT,
locale), value);
value = symbols.getMonths()[month];
assertEquals(cal.getDisplayName(field, Calendar.LONG,
locale), value);
}
break;
case Calendar.DAY_OF_WEEK:
for (int day = 1; day <= 7; day++) {
cal.set(Calendar.DAY_OF_WEEK, day);
value = symbols.getShortWeekdays()[day];
assertEquals(cal.getDisplayName(field, Calendar.SHORT,
locale), value);
value = symbols.getWeekdays()[day];
assertEquals(cal.getDisplayName(field, Calendar.LONG,
locale), value);
}
break;
default:
assertNull(cal
.getDisplayName(field, Calendar.SHORT, locale));
assertNull(cal.getDisplayName(field, Calendar.LONG, locale));
}
}
}
cal.setLenient(true);
try {
cal.getDisplayName(-1, Calendar.SHORT, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayName(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayName(Calendar.MONTH, -1, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayName(Calendar.MONTH, 3, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, null);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
// expected
}
try {
cal.getDisplayName(-1, Calendar.SHORT, null);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayName(Calendar.MONTH, -1, null);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
// in lenient mode, following cases pass
cal.set(Calendar.SECOND, 999);
cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
// test for ALL_STYLES, it is equal to use SHORT
for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
for (Locale locale : locales) {
String result = cal.getDisplayName(field, Calendar.ALL_STYLES,
locale);
if (field == Calendar.AM_PM || field == Calendar.ERA
|| field == Calendar.MONTH
|| field == Calendar.DAY_OF_WEEK) {
assertEquals(result, cal.getDisplayName(field,
Calendar.SHORT, locale));
} else {
assertNull(result);
}
}
}
// invalid value for an un-related field when the calendar is not
// lenient
cal.setLenient(false);
assertNotNull(cal.getDisplayName(Calendar.MONTH, Calendar.SHORT,
Locale.US));
cal.set(Calendar.SECOND, 999);
try {
cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayName(Calendar.MONTH, Calendar.ALL_STYLES, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
/**
* {@link java.util.Calendar#getDisplayNames(int, int, Locale)}
* @since 1.6
*/
public void test_getDisplayNamesIILjava_util_Locale() {
assertEquals(0, Calendar.ALL_STYLES);
assertEquals(1, Calendar.SHORT);
assertEquals(2, Calendar.LONG);
Calendar cal = Calendar.getInstance(Locale.US);
for (int field = 0; field < Calendar.FIELD_COUNT; field++) {
for (Locale locale : locales) {
Map<String, Integer> shortResult = cal.getDisplayNames(field,
Calendar.SHORT, locale);
Map<String, Integer> longResult = cal.getDisplayNames(field,
Calendar.LONG, locale);
Map<String, Integer> allResult = cal.getDisplayNames(field,
Calendar.ALL_STYLES, locale);
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] values = null;
switch (field) {
case Calendar.AM_PM:
case Calendar.ERA:
values = (field == Calendar.AM_PM) ? symbols
.getAmPmStrings() : symbols.getEras();
assertDisplayNameMap(values, shortResult, 0);
assertDisplayNameMap(values, longResult, 0);
assertTrue(allResult.size() >= shortResult.size());
assertTrue(allResult.size() >= longResult.size());
break;
case Calendar.MONTH:
values = symbols.getShortMonths();
assertDisplayNameMap(values, shortResult, 0);
values = symbols.getMonths();
assertDisplayNameMap(values, longResult, 0);
assertTrue(allResult.size() >= shortResult.size());
assertTrue(allResult.size() >= longResult.size());
break;
case Calendar.DAY_OF_WEEK:
values = symbols.getShortWeekdays();
assertDisplayNameMap(values, shortResult, 1);
values = symbols.getWeekdays();
assertDisplayNameMap(values, longResult, 1);
assertTrue(allResult.size() >= shortResult.size());
assertTrue(allResult.size() >= longResult.size());
break;
default:
assertNull(shortResult);
assertNull(longResult);
assertNull(allResult);
}
}
}
cal.setLenient(true);
try {
cal.getDisplayNames(-1, Calendar.SHORT, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayNames(Calendar.FIELD_COUNT, Calendar.LONG, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayNames(Calendar.MONTH, -1, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayNames(Calendar.MONTH, 3, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, null);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
// expected
}
try {
cal.getDisplayNames(-1, Calendar.SHORT, null);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
cal.getDisplayNames(Calendar.MONTH, -1, null);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
cal.set(Calendar.SECOND, 999);
cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US);
// RI fails here
// invalid value for an un-related field when the calendar is not
// lenient
cal.setLenient(false);
cal.set(Calendar.SECOND, 999);
try {
cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, Locale.US);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
private void assertDisplayNameMap(String[] values,
Map<String, Integer> result, int shift) {
List<String> trimValue = new ArrayList<String>();
for (String value : values) {
if (value.trim().length() > 0) {
trimValue.add(value);
}
}
assertEquals(trimValue.size(), result.size());
for (int i = 0; i < trimValue.size(); i++) {
assertEquals(i + shift, result.get(trimValue.get(i)).intValue());
}
}
/**
* {@link java.util.Calendar#getActualMaximum(int)}
*/
public void test_getActualMaximum_I() {
Calendar c = new MockCalendar();
assertEquals("should be equal to 0", 0, c.getActualMaximum(0));
}
/**
* {@link java.util.Calendar#getActualMinimum(int)}
*/
public void test_getActualMinimum_I() {
Calendar c = new MockCalendar();
assertEquals("should be equal to 0", 0, c.getActualMinimum(0));
}
protected void setUp() {
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
}
protected void tearDown() {
Locale.setDefault(defaultLocale);
}
}
|
googleapis/google-cloud-java | 37,416 | java-appengine-admin/proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/ListAuthorizedCertificatesResponse.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>
* Response message for `AuthorizedCertificates.ListAuthorizedCertificates`.
* </pre>
*
* Protobuf type {@code google.appengine.v1.ListAuthorizedCertificatesResponse}
*/
public final class ListAuthorizedCertificatesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.appengine.v1.ListAuthorizedCertificatesResponse)
ListAuthorizedCertificatesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAuthorizedCertificatesResponse.newBuilder() to construct.
private ListAuthorizedCertificatesResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAuthorizedCertificatesResponse() {
certificates_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAuthorizedCertificatesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedCertificatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedCertificatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.appengine.v1.ListAuthorizedCertificatesResponse.class,
com.google.appengine.v1.ListAuthorizedCertificatesResponse.Builder.class);
}
public static final int CERTIFICATES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.appengine.v1.AuthorizedCertificate> certificates_;
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.appengine.v1.AuthorizedCertificate> getCertificatesList() {
return certificates_;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.appengine.v1.AuthorizedCertificateOrBuilder>
getCertificatesOrBuilderList() {
return certificates_;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
@java.lang.Override
public int getCertificatesCount() {
return certificates_.size();
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
@java.lang.Override
public com.google.appengine.v1.AuthorizedCertificate getCertificates(int index) {
return certificates_.get(index);
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
@java.lang.Override
public com.google.appengine.v1.AuthorizedCertificateOrBuilder getCertificatesOrBuilder(
int index) {
return certificates_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation token for fetching 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 for fetching 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 < certificates_.size(); i++) {
output.writeMessage(1, certificates_.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 < certificates_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, certificates_.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.appengine.v1.ListAuthorizedCertificatesResponse)) {
return super.equals(obj);
}
com.google.appengine.v1.ListAuthorizedCertificatesResponse other =
(com.google.appengine.v1.ListAuthorizedCertificatesResponse) obj;
if (!getCertificatesList().equals(other.getCertificatesList())) 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 (getCertificatesCount() > 0) {
hash = (37 * hash) + CERTIFICATES_FIELD_NUMBER;
hash = (53 * hash) + getCertificatesList().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.appengine.v1.ListAuthorizedCertificatesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse 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.ListAuthorizedCertificatesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse 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.ListAuthorizedCertificatesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse 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.ListAuthorizedCertificatesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse 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.ListAuthorizedCertificatesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse 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.ListAuthorizedCertificatesResponse 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 `AuthorizedCertificates.ListAuthorizedCertificates`.
* </pre>
*
* Protobuf type {@code google.appengine.v1.ListAuthorizedCertificatesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.appengine.v1.ListAuthorizedCertificatesResponse)
com.google.appengine.v1.ListAuthorizedCertificatesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedCertificatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedCertificatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.appengine.v1.ListAuthorizedCertificatesResponse.class,
com.google.appengine.v1.ListAuthorizedCertificatesResponse.Builder.class);
}
// Construct using com.google.appengine.v1.ListAuthorizedCertificatesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (certificatesBuilder_ == null) {
certificates_ = java.util.Collections.emptyList();
} else {
certificates_ = null;
certificatesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListAuthorizedCertificatesResponse_descriptor;
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedCertificatesResponse getDefaultInstanceForType() {
return com.google.appengine.v1.ListAuthorizedCertificatesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedCertificatesResponse build() {
com.google.appengine.v1.ListAuthorizedCertificatesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedCertificatesResponse buildPartial() {
com.google.appengine.v1.ListAuthorizedCertificatesResponse result =
new com.google.appengine.v1.ListAuthorizedCertificatesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.appengine.v1.ListAuthorizedCertificatesResponse result) {
if (certificatesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
certificates_ = java.util.Collections.unmodifiableList(certificates_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.certificates_ = certificates_;
} else {
result.certificates_ = certificatesBuilder_.build();
}
}
private void buildPartial0(com.google.appengine.v1.ListAuthorizedCertificatesResponse 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.appengine.v1.ListAuthorizedCertificatesResponse) {
return mergeFrom((com.google.appengine.v1.ListAuthorizedCertificatesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.appengine.v1.ListAuthorizedCertificatesResponse other) {
if (other == com.google.appengine.v1.ListAuthorizedCertificatesResponse.getDefaultInstance())
return this;
if (certificatesBuilder_ == null) {
if (!other.certificates_.isEmpty()) {
if (certificates_.isEmpty()) {
certificates_ = other.certificates_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCertificatesIsMutable();
certificates_.addAll(other.certificates_);
}
onChanged();
}
} else {
if (!other.certificates_.isEmpty()) {
if (certificatesBuilder_.isEmpty()) {
certificatesBuilder_.dispose();
certificatesBuilder_ = null;
certificates_ = other.certificates_;
bitField0_ = (bitField0_ & ~0x00000001);
certificatesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCertificatesFieldBuilder()
: null;
} else {
certificatesBuilder_.addAllMessages(other.certificates_);
}
}
}
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.appengine.v1.AuthorizedCertificate m =
input.readMessage(
com.google.appengine.v1.AuthorizedCertificate.parser(), extensionRegistry);
if (certificatesBuilder_ == null) {
ensureCertificatesIsMutable();
certificates_.add(m);
} else {
certificatesBuilder_.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.appengine.v1.AuthorizedCertificate> certificates_ =
java.util.Collections.emptyList();
private void ensureCertificatesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
certificates_ =
new java.util.ArrayList<com.google.appengine.v1.AuthorizedCertificate>(certificates_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.AuthorizedCertificate,
com.google.appengine.v1.AuthorizedCertificate.Builder,
com.google.appengine.v1.AuthorizedCertificateOrBuilder>
certificatesBuilder_;
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public java.util.List<com.google.appengine.v1.AuthorizedCertificate> getCertificatesList() {
if (certificatesBuilder_ == null) {
return java.util.Collections.unmodifiableList(certificates_);
} else {
return certificatesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public int getCertificatesCount() {
if (certificatesBuilder_ == null) {
return certificates_.size();
} else {
return certificatesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public com.google.appengine.v1.AuthorizedCertificate getCertificates(int index) {
if (certificatesBuilder_ == null) {
return certificates_.get(index);
} else {
return certificatesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder setCertificates(int index, com.google.appengine.v1.AuthorizedCertificate value) {
if (certificatesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCertificatesIsMutable();
certificates_.set(index, value);
onChanged();
} else {
certificatesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder setCertificates(
int index, com.google.appengine.v1.AuthorizedCertificate.Builder builderForValue) {
if (certificatesBuilder_ == null) {
ensureCertificatesIsMutable();
certificates_.set(index, builderForValue.build());
onChanged();
} else {
certificatesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder addCertificates(com.google.appengine.v1.AuthorizedCertificate value) {
if (certificatesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCertificatesIsMutable();
certificates_.add(value);
onChanged();
} else {
certificatesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder addCertificates(int index, com.google.appengine.v1.AuthorizedCertificate value) {
if (certificatesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCertificatesIsMutable();
certificates_.add(index, value);
onChanged();
} else {
certificatesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder addCertificates(
com.google.appengine.v1.AuthorizedCertificate.Builder builderForValue) {
if (certificatesBuilder_ == null) {
ensureCertificatesIsMutable();
certificates_.add(builderForValue.build());
onChanged();
} else {
certificatesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder addCertificates(
int index, com.google.appengine.v1.AuthorizedCertificate.Builder builderForValue) {
if (certificatesBuilder_ == null) {
ensureCertificatesIsMutable();
certificates_.add(index, builderForValue.build());
onChanged();
} else {
certificatesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder addAllCertificates(
java.lang.Iterable<? extends com.google.appengine.v1.AuthorizedCertificate> values) {
if (certificatesBuilder_ == null) {
ensureCertificatesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, certificates_);
onChanged();
} else {
certificatesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder clearCertificates() {
if (certificatesBuilder_ == null) {
certificates_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
certificatesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public Builder removeCertificates(int index) {
if (certificatesBuilder_ == null) {
ensureCertificatesIsMutable();
certificates_.remove(index);
onChanged();
} else {
certificatesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public com.google.appengine.v1.AuthorizedCertificate.Builder getCertificatesBuilder(int index) {
return getCertificatesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public com.google.appengine.v1.AuthorizedCertificateOrBuilder getCertificatesOrBuilder(
int index) {
if (certificatesBuilder_ == null) {
return certificates_.get(index);
} else {
return certificatesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public java.util.List<? extends com.google.appengine.v1.AuthorizedCertificateOrBuilder>
getCertificatesOrBuilderList() {
if (certificatesBuilder_ != null) {
return certificatesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(certificates_);
}
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public com.google.appengine.v1.AuthorizedCertificate.Builder addCertificatesBuilder() {
return getCertificatesFieldBuilder()
.addBuilder(com.google.appengine.v1.AuthorizedCertificate.getDefaultInstance());
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public com.google.appengine.v1.AuthorizedCertificate.Builder addCertificatesBuilder(int index) {
return getCertificatesFieldBuilder()
.addBuilder(index, com.google.appengine.v1.AuthorizedCertificate.getDefaultInstance());
}
/**
*
*
* <pre>
* The SSL certificates the user is authorized to administer.
* </pre>
*
* <code>repeated .google.appengine.v1.AuthorizedCertificate certificates = 1;</code>
*/
public java.util.List<com.google.appengine.v1.AuthorizedCertificate.Builder>
getCertificatesBuilderList() {
return getCertificatesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.AuthorizedCertificate,
com.google.appengine.v1.AuthorizedCertificate.Builder,
com.google.appengine.v1.AuthorizedCertificateOrBuilder>
getCertificatesFieldBuilder() {
if (certificatesBuilder_ == null) {
certificatesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.AuthorizedCertificate,
com.google.appengine.v1.AuthorizedCertificate.Builder,
com.google.appengine.v1.AuthorizedCertificateOrBuilder>(
certificates_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
certificates_ = null;
}
return certificatesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation token for fetching 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 for fetching 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 for fetching 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 for fetching 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 for fetching 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.appengine.v1.ListAuthorizedCertificatesResponse)
}
// @@protoc_insertion_point(class_scope:google.appengine.v1.ListAuthorizedCertificatesResponse)
private static final com.google.appengine.v1.ListAuthorizedCertificatesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.appengine.v1.ListAuthorizedCertificatesResponse();
}
public static com.google.appengine.v1.ListAuthorizedCertificatesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAuthorizedCertificatesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAuthorizedCertificatesResponse>() {
@java.lang.Override
public ListAuthorizedCertificatesResponse 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<ListAuthorizedCertificatesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAuthorizedCertificatesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.appengine.v1.ListAuthorizedCertificatesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/sdk-platform-java | 37,486 | java-showcase/gapic-showcase/src/test/java/com/google/showcase/v1beta1/EchoClientTest.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.showcase.v1beta1;
import static com.google.showcase.v1beta1.EchoClient.ListLocationsPagedResponse;
import static com.google.showcase.v1beta1.EchoClient.PagedExpandLegacyMappedPagedResponse;
import static com.google.showcase.v1beta1.EchoClient.PagedExpandPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.grpc.testing.MockStreamObserver;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ApiStreamObserver;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.ClientStreamingCallable;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StatusCode;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.common.collect.Lists;
import com.google.iam.v1.AuditConfig;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.GetPolicyOptions;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.Operation;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.rpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@Generated("by gapic-generator-java")
public class EchoClientTest {
private static MockEcho mockEcho;
private static MockIAMPolicy mockIAMPolicy;
private static MockLocations mockLocations;
private static MockServiceHelper mockServiceHelper;
private LocalChannelProvider channelProvider;
private EchoClient client;
@BeforeClass
public static void startStaticServer() {
mockEcho = new MockEcho();
mockLocations = new MockLocations();
mockIAMPolicy = new MockIAMPolicy();
mockServiceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(),
Arrays.<MockGrpcService>asList(mockEcho, mockLocations, mockIAMPolicy));
mockServiceHelper.start();
}
@AfterClass
public static void stopServer() {
mockServiceHelper.stop();
}
@Before
public void setUp() throws IOException {
mockServiceHelper.reset();
channelProvider = mockServiceHelper.createChannelProvider();
EchoSettings settings =
EchoSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = EchoClient.create(settings);
}
@After
public void tearDown() throws Exception {
client.close();
}
@Test
public void echoTest() throws Exception {
EchoResponse expectedResponse =
EchoResponse.newBuilder()
.setContent("content951530617")
.setSeverity(Severity.forNumber(0))
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
mockEcho.addResponse(expectedResponse);
EchoRequest request =
EchoRequest.newBuilder()
.setSeverity(Severity.forNumber(0))
.setHeader("header-1221270899")
.setOtherHeader("otherHeader-2026585667")
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
EchoResponse actualResponse = client.echo(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
EchoRequest actualRequest = ((EchoRequest) actualRequests.get(0));
Assert.assertEquals(request.getContent(), actualRequest.getContent());
Assert.assertEquals(request.getError(), actualRequest.getError());
Assert.assertEquals(request.getSeverity(), actualRequest.getSeverity());
Assert.assertEquals(request.getHeader(), actualRequest.getHeader());
Assert.assertEquals(request.getOtherHeader(), actualRequest.getOtherHeader());
Assert.assertEquals(request.getRequestId(), actualRequest.getRequestId());
Assert.assertEquals(request.getOtherRequestId(), actualRequest.getOtherRequestId());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void echoExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
EchoRequest request =
EchoRequest.newBuilder()
.setSeverity(Severity.forNumber(0))
.setHeader("header-1221270899")
.setOtherHeader("otherHeader-2026585667")
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
client.echo(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void echoErrorDetailsTest() throws Exception {
EchoErrorDetailsResponse expectedResponse =
EchoErrorDetailsResponse.newBuilder()
.setSingleDetail(EchoErrorDetailsResponse.SingleDetail.newBuilder().build())
.setMultipleDetails(EchoErrorDetailsResponse.MultipleDetails.newBuilder().build())
.build();
mockEcho.addResponse(expectedResponse);
EchoErrorDetailsRequest request =
EchoErrorDetailsRequest.newBuilder()
.setSingleDetailText("singleDetailText1774380934")
.addAllMultiDetailText(new ArrayList<String>())
.build();
EchoErrorDetailsResponse actualResponse = client.echoErrorDetails(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
EchoErrorDetailsRequest actualRequest = ((EchoErrorDetailsRequest) actualRequests.get(0));
Assert.assertEquals(request.getSingleDetailText(), actualRequest.getSingleDetailText());
Assert.assertEquals(request.getMultiDetailTextList(), actualRequest.getMultiDetailTextList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void echoErrorDetailsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
EchoErrorDetailsRequest request =
EchoErrorDetailsRequest.newBuilder()
.setSingleDetailText("singleDetailText1774380934")
.addAllMultiDetailText(new ArrayList<String>())
.build();
client.echoErrorDetails(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void failEchoWithDetailsTest() throws Exception {
FailEchoWithDetailsResponse expectedResponse = FailEchoWithDetailsResponse.newBuilder().build();
mockEcho.addResponse(expectedResponse);
FailEchoWithDetailsRequest request =
FailEchoWithDetailsRequest.newBuilder().setMessage("message954925063").build();
FailEchoWithDetailsResponse actualResponse = client.failEchoWithDetails(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
FailEchoWithDetailsRequest actualRequest = ((FailEchoWithDetailsRequest) actualRequests.get(0));
Assert.assertEquals(request.getMessage(), actualRequest.getMessage());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void failEchoWithDetailsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
FailEchoWithDetailsRequest request =
FailEchoWithDetailsRequest.newBuilder().setMessage("message954925063").build();
client.failEchoWithDetails(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void expandTest() throws Exception {
EchoResponse expectedResponse =
EchoResponse.newBuilder()
.setContent("content951530617")
.setSeverity(Severity.forNumber(0))
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
mockEcho.addResponse(expectedResponse);
ExpandRequest request =
ExpandRequest.newBuilder()
.setContent("content951530617")
.setError(Status.newBuilder().build())
.setStreamWaitTime(Duration.newBuilder().build())
.build();
MockStreamObserver<EchoResponse> responseObserver = new MockStreamObserver<>();
ServerStreamingCallable<ExpandRequest, EchoResponse> callable = client.expandCallable();
callable.serverStreamingCall(request, responseObserver);
List<EchoResponse> actualResponses = responseObserver.future().get();
Assert.assertEquals(1, actualResponses.size());
Assert.assertEquals(expectedResponse, actualResponses.get(0));
}
@Test
public void expandExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
ExpandRequest request =
ExpandRequest.newBuilder()
.setContent("content951530617")
.setError(Status.newBuilder().build())
.setStreamWaitTime(Duration.newBuilder().build())
.build();
MockStreamObserver<EchoResponse> responseObserver = new MockStreamObserver<>();
ServerStreamingCallable<ExpandRequest, EchoResponse> callable = client.expandCallable();
callable.serverStreamingCall(request, responseObserver);
try {
List<EchoResponse> actualResponses = responseObserver.future().get();
Assert.fail("No exception thrown");
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof InvalidArgumentException);
InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
}
}
@Test
public void collectTest() throws Exception {
EchoResponse expectedResponse =
EchoResponse.newBuilder()
.setContent("content951530617")
.setSeverity(Severity.forNumber(0))
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
mockEcho.addResponse(expectedResponse);
EchoRequest request =
EchoRequest.newBuilder()
.setSeverity(Severity.forNumber(0))
.setHeader("header-1221270899")
.setOtherHeader("otherHeader-2026585667")
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
MockStreamObserver<EchoResponse> responseObserver = new MockStreamObserver<>();
ClientStreamingCallable<EchoRequest, EchoResponse> callable = client.collectCallable();
ApiStreamObserver<EchoRequest> requestObserver = callable.clientStreamingCall(responseObserver);
requestObserver.onNext(request);
requestObserver.onCompleted();
List<EchoResponse> actualResponses = responseObserver.future().get();
Assert.assertEquals(1, actualResponses.size());
Assert.assertEquals(expectedResponse, actualResponses.get(0));
}
@Test
public void collectExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
EchoRequest request =
EchoRequest.newBuilder()
.setSeverity(Severity.forNumber(0))
.setHeader("header-1221270899")
.setOtherHeader("otherHeader-2026585667")
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
MockStreamObserver<EchoResponse> responseObserver = new MockStreamObserver<>();
ClientStreamingCallable<EchoRequest, EchoResponse> callable = client.collectCallable();
ApiStreamObserver<EchoRequest> requestObserver = callable.clientStreamingCall(responseObserver);
requestObserver.onNext(request);
try {
List<EchoResponse> actualResponses = responseObserver.future().get();
Assert.fail("No exception thrown");
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof InvalidArgumentException);
InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
}
}
@Test
public void chatTest() throws Exception {
EchoResponse expectedResponse =
EchoResponse.newBuilder()
.setContent("content951530617")
.setSeverity(Severity.forNumber(0))
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
mockEcho.addResponse(expectedResponse);
EchoRequest request =
EchoRequest.newBuilder()
.setSeverity(Severity.forNumber(0))
.setHeader("header-1221270899")
.setOtherHeader("otherHeader-2026585667")
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
MockStreamObserver<EchoResponse> responseObserver = new MockStreamObserver<>();
BidiStreamingCallable<EchoRequest, EchoResponse> callable = client.chatCallable();
ApiStreamObserver<EchoRequest> requestObserver = callable.bidiStreamingCall(responseObserver);
requestObserver.onNext(request);
requestObserver.onCompleted();
List<EchoResponse> actualResponses = responseObserver.future().get();
Assert.assertEquals(1, actualResponses.size());
Assert.assertEquals(expectedResponse, actualResponses.get(0));
}
@Test
public void chatExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
EchoRequest request =
EchoRequest.newBuilder()
.setSeverity(Severity.forNumber(0))
.setHeader("header-1221270899")
.setOtherHeader("otherHeader-2026585667")
.setRequestId("requestId693933066")
.setOtherRequestId("otherRequestId1248995034")
.build();
MockStreamObserver<EchoResponse> responseObserver = new MockStreamObserver<>();
BidiStreamingCallable<EchoRequest, EchoResponse> callable = client.chatCallable();
ApiStreamObserver<EchoRequest> requestObserver = callable.bidiStreamingCall(responseObserver);
requestObserver.onNext(request);
try {
List<EchoResponse> actualResponses = responseObserver.future().get();
Assert.fail("No exception thrown");
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof InvalidArgumentException);
InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
}
}
@Test
public void pagedExpandTest() throws Exception {
EchoResponse responsesElement = EchoResponse.newBuilder().build();
PagedExpandResponse expectedResponse =
PagedExpandResponse.newBuilder()
.setNextPageToken("")
.addAllResponses(Arrays.asList(responsesElement))
.build();
mockEcho.addResponse(expectedResponse);
PagedExpandRequest request =
PagedExpandRequest.newBuilder()
.setContent("content951530617")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
PagedExpandPagedResponse pagedListResponse = client.pagedExpand(request);
List<EchoResponse> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getResponsesList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
PagedExpandRequest actualRequest = ((PagedExpandRequest) actualRequests.get(0));
Assert.assertEquals(request.getContent(), actualRequest.getContent());
Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize());
Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void pagedExpandExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
PagedExpandRequest request =
PagedExpandRequest.newBuilder()
.setContent("content951530617")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
client.pagedExpand(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void pagedExpandLegacyTest() throws Exception {
PagedExpandResponse expectedResponse =
PagedExpandResponse.newBuilder()
.addAllResponses(new ArrayList<EchoResponse>())
.setNextPageToken("nextPageToken-1386094857")
.build();
mockEcho.addResponse(expectedResponse);
PagedExpandLegacyRequest request =
PagedExpandLegacyRequest.newBuilder()
.setContent("content951530617")
.setMaxResults(1128457243)
.setPageToken("pageToken873572522")
.build();
PagedExpandResponse actualResponse = client.pagedExpandLegacy(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
PagedExpandLegacyRequest actualRequest = ((PagedExpandLegacyRequest) actualRequests.get(0));
Assert.assertEquals(request.getContent(), actualRequest.getContent());
Assert.assertEquals(request.getMaxResults(), actualRequest.getMaxResults());
Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void pagedExpandLegacyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
PagedExpandLegacyRequest request =
PagedExpandLegacyRequest.newBuilder()
.setContent("content951530617")
.setMaxResults(1128457243)
.setPageToken("pageToken873572522")
.build();
client.pagedExpandLegacy(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void pagedExpandLegacyMappedTest() throws Exception {
PagedExpandResponseList responsesElement = PagedExpandResponseList.newBuilder().build();
PagedExpandLegacyMappedResponse expectedResponse =
PagedExpandLegacyMappedResponse.newBuilder()
.setNextPageToken("")
.putAllAlphabetized(Collections.singletonMap("alphabetized", responsesElement))
.build();
mockEcho.addResponse(expectedResponse);
PagedExpandRequest request =
PagedExpandRequest.newBuilder()
.setContent("content951530617")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
PagedExpandLegacyMappedPagedResponse pagedListResponse =
client.pagedExpandLegacyMapped(request);
List<Map.Entry<String, PagedExpandResponseList>> resources =
Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(
expectedResponse.getAlphabetizedMap().entrySet().iterator().next(), resources.get(0));
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
PagedExpandRequest actualRequest = ((PagedExpandRequest) actualRequests.get(0));
Assert.assertEquals(request.getContent(), actualRequest.getContent());
Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize());
Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void pagedExpandLegacyMappedExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
PagedExpandRequest request =
PagedExpandRequest.newBuilder()
.setContent("content951530617")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
client.pagedExpandLegacyMapped(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void waitTest() throws Exception {
WaitResponse expectedResponse =
WaitResponse.newBuilder().setContent("content951530617").build();
Operation resultOperation =
Operation.newBuilder()
.setName("waitTest")
.setDone(true)
.setResponse(Any.pack(expectedResponse))
.build();
mockEcho.addResponse(resultOperation);
WaitRequest request = WaitRequest.newBuilder().build();
WaitResponse actualResponse = client.waitAsync(request).get();
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
WaitRequest actualRequest = ((WaitRequest) actualRequests.get(0));
Assert.assertEquals(request.getEndTime(), actualRequest.getEndTime());
Assert.assertEquals(request.getTtl(), actualRequest.getTtl());
Assert.assertEquals(request.getError(), actualRequest.getError());
Assert.assertEquals(request.getSuccess(), actualRequest.getSuccess());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void waitExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
WaitRequest request = WaitRequest.newBuilder().build();
client.waitAsync(request).get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass());
InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
}
}
@Test
public void blockTest() throws Exception {
BlockResponse expectedResponse =
BlockResponse.newBuilder().setContent("content951530617").build();
mockEcho.addResponse(expectedResponse);
BlockRequest request =
BlockRequest.newBuilder().setResponseDelay(Duration.newBuilder().build()).build();
BlockResponse actualResponse = client.block(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockEcho.getRequests();
Assert.assertEquals(1, actualRequests.size());
BlockRequest actualRequest = ((BlockRequest) actualRequests.get(0));
Assert.assertEquals(request.getResponseDelay(), actualRequest.getResponseDelay());
Assert.assertEquals(request.getError(), actualRequest.getError());
Assert.assertEquals(request.getSuccess(), actualRequest.getSuccess());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void blockExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockEcho.addException(exception);
try {
BlockRequest request =
BlockRequest.newBuilder().setResponseDelay(Duration.newBuilder().build()).build();
client.block(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listLocationsTest() throws Exception {
Location responsesElement = Location.newBuilder().build();
ListLocationsResponse expectedResponse =
ListLocationsResponse.newBuilder()
.setNextPageToken("")
.addAllLocations(Arrays.asList(responsesElement))
.build();
mockLocations.addResponse(expectedResponse);
ListLocationsRequest request =
ListLocationsRequest.newBuilder()
.setName("name3373707")
.setFilter("filter-1274492040")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
ListLocationsPagedResponse pagedListResponse = client.listLocations(request);
List<Location> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getLocationsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockLocations.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListLocationsRequest actualRequest = ((ListLocationsRequest) actualRequests.get(0));
Assert.assertEquals(request.getName(), actualRequest.getName());
Assert.assertEquals(request.getFilter(), actualRequest.getFilter());
Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize());
Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listLocationsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockLocations.addException(exception);
try {
ListLocationsRequest request =
ListLocationsRequest.newBuilder()
.setName("name3373707")
.setFilter("filter-1274492040")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
client.listLocations(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getLocationTest() throws Exception {
Location expectedResponse =
Location.newBuilder()
.setName("name3373707")
.setLocationId("locationId1541836720")
.setDisplayName("displayName1714148973")
.putAllLabels(new HashMap<String, String>())
.setMetadata(Any.newBuilder().build())
.build();
mockLocations.addResponse(expectedResponse);
GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
Location actualResponse = client.getLocation(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockLocations.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetLocationRequest actualRequest = ((GetLocationRequest) actualRequests.get(0));
Assert.assertEquals(request.getName(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getLocationExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockLocations.addException(exception);
try {
GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
client.getLocation(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void setIamPolicyTest() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockIAMPolicy.addResponse(expectedResponse);
SetIamPolicyRequest request =
SetIamPolicyRequest.newBuilder()
.setResource(BlurbName.ofRoomBlurbName("[ROOM]", "[BLURB]").toString())
.setPolicy(Policy.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
Policy actualResponse = client.setIamPolicy(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests();
Assert.assertEquals(1, actualRequests.size());
SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(request.getResource(), actualRequest.getResource());
Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy());
Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void setIamPolicyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockIAMPolicy.addException(exception);
try {
SetIamPolicyRequest request =
SetIamPolicyRequest.newBuilder()
.setResource(BlurbName.ofRoomBlurbName("[ROOM]", "[BLURB]").toString())
.setPolicy(Policy.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
client.setIamPolicy(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getIamPolicyTest() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockIAMPolicy.addResponse(expectedResponse);
GetIamPolicyRequest request =
GetIamPolicyRequest.newBuilder()
.setResource(BlurbName.ofRoomBlurbName("[ROOM]", "[BLURB]").toString())
.setOptions(GetPolicyOptions.newBuilder().build())
.build();
Policy actualResponse = client.getIamPolicy(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(request.getResource(), actualRequest.getResource());
Assert.assertEquals(request.getOptions(), actualRequest.getOptions());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getIamPolicyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockIAMPolicy.addException(exception);
try {
GetIamPolicyRequest request =
GetIamPolicyRequest.newBuilder()
.setResource(BlurbName.ofRoomBlurbName("[ROOM]", "[BLURB]").toString())
.setOptions(GetPolicyOptions.newBuilder().build())
.build();
client.getIamPolicy(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void testIamPermissionsTest() throws Exception {
TestIamPermissionsResponse expectedResponse =
TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList<String>()).build();
mockIAMPolicy.addResponse(expectedResponse);
TestIamPermissionsRequest request =
TestIamPermissionsRequest.newBuilder()
.setResource(BlurbName.ofRoomBlurbName("[ROOM]", "[BLURB]").toString())
.addAllPermissions(new ArrayList<String>())
.build();
TestIamPermissionsResponse actualResponse = client.testIamPermissions(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests();
Assert.assertEquals(1, actualRequests.size());
TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0));
Assert.assertEquals(request.getResource(), actualRequest.getResource());
Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void testIamPermissionsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockIAMPolicy.addException(exception);
try {
TestIamPermissionsRequest request =
TestIamPermissionsRequest.newBuilder()
.setResource(BlurbName.ofRoomBlurbName("[ROOM]", "[BLURB]").toString())
.addAllPermissions(new ArrayList<String>())
.build();
client.testIamPermissions(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
googleads/google-ads-java | 37,529 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/errors/PolicyViolationDetails.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/errors/errors.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.errors;
/**
* <pre>
* Error returned as part of a mutate response.
* This error indicates single policy violation by some text
* in one of the fields.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.errors.PolicyViolationDetails}
*/
public final class PolicyViolationDetails extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.errors.PolicyViolationDetails)
PolicyViolationDetailsOrBuilder {
private static final long serialVersionUID = 0L;
// Use PolicyViolationDetails.newBuilder() to construct.
private PolicyViolationDetails(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PolicyViolationDetails() {
externalPolicyDescription_ = "";
externalPolicyName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new PolicyViolationDetails();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.errors.ErrorsProto.internal_static_google_ads_googleads_v19_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.errors.ErrorsProto.internal_static_google_ads_googleads_v19_errors_PolicyViolationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.errors.PolicyViolationDetails.class, com.google.ads.googleads.v19.errors.PolicyViolationDetails.Builder.class);
}
private int bitField0_;
public static final int EXTERNAL_POLICY_DESCRIPTION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object externalPolicyDescription_ = "";
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The externalPolicyDescription.
*/
@java.lang.Override
public java.lang.String getExternalPolicyDescription() {
java.lang.Object ref = externalPolicyDescription_;
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();
externalPolicyDescription_ = s;
return s;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The bytes for externalPolicyDescription.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getExternalPolicyDescriptionBytes() {
java.lang.Object ref = externalPolicyDescription_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyDescription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int KEY_FIELD_NUMBER = 4;
private com.google.ads.googleads.v19.common.PolicyViolationKey key_;
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
* @return Whether the key field is set.
*/
@java.lang.Override
public boolean hasKey() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
* @return The key.
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.PolicyViolationKey getKey() {
return key_ == null ? com.google.ads.googleads.v19.common.PolicyViolationKey.getDefaultInstance() : key_;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.PolicyViolationKeyOrBuilder getKeyOrBuilder() {
return key_ == null ? com.google.ads.googleads.v19.common.PolicyViolationKey.getDefaultInstance() : key_;
}
public static final int EXTERNAL_POLICY_NAME_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object externalPolicyName_ = "";
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The externalPolicyName.
*/
@java.lang.Override
public java.lang.String getExternalPolicyName() {
java.lang.Object ref = externalPolicyName_;
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();
externalPolicyName_ = s;
return s;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The bytes for externalPolicyName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getExternalPolicyNameBytes() {
java.lang.Object ref = externalPolicyName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IS_EXEMPTIBLE_FIELD_NUMBER = 6;
private boolean isExemptible_ = false;
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return The isExemptible.
*/
@java.lang.Override
public boolean getIsExemptible() {
return isExemptible_;
}
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(externalPolicyDescription_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, externalPolicyDescription_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPolicyName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, externalPolicyName_);
}
if (isExemptible_ != false) {
output.writeBool(6, isExemptible_);
}
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(externalPolicyDescription_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, externalPolicyDescription_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPolicyName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, externalPolicyName_);
}
if (isExemptible_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(6, isExemptible_);
}
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.errors.PolicyViolationDetails)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.errors.PolicyViolationDetails other = (com.google.ads.googleads.v19.errors.PolicyViolationDetails) obj;
if (!getExternalPolicyDescription()
.equals(other.getExternalPolicyDescription())) return false;
if (hasKey() != other.hasKey()) return false;
if (hasKey()) {
if (!getKey()
.equals(other.getKey())) return false;
}
if (!getExternalPolicyName()
.equals(other.getExternalPolicyName())) return false;
if (getIsExemptible()
!= other.getIsExemptible()) 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) + EXTERNAL_POLICY_DESCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getExternalPolicyDescription().hashCode();
if (hasKey()) {
hash = (37 * hash) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
}
hash = (37 * hash) + EXTERNAL_POLICY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getExternalPolicyName().hashCode();
hash = (37 * hash) + IS_EXEMPTIBLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getIsExemptible());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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>
* Error returned as part of a mutate response.
* This error indicates single policy violation by some text
* in one of the fields.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.errors.PolicyViolationDetails}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.errors.PolicyViolationDetails)
com.google.ads.googleads.v19.errors.PolicyViolationDetailsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.errors.ErrorsProto.internal_static_google_ads_googleads_v19_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.errors.ErrorsProto.internal_static_google_ads_googleads_v19_errors_PolicyViolationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.errors.PolicyViolationDetails.class, com.google.ads.googleads.v19.errors.PolicyViolationDetails.Builder.class);
}
// Construct using com.google.ads.googleads.v19.errors.PolicyViolationDetails.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getKeyFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
externalPolicyDescription_ = "";
key_ = null;
if (keyBuilder_ != null) {
keyBuilder_.dispose();
keyBuilder_ = null;
}
externalPolicyName_ = "";
isExemptible_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.errors.ErrorsProto.internal_static_google_ads_googleads_v19_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.PolicyViolationDetails getDefaultInstanceForType() {
return com.google.ads.googleads.v19.errors.PolicyViolationDetails.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.PolicyViolationDetails build() {
com.google.ads.googleads.v19.errors.PolicyViolationDetails result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.PolicyViolationDetails buildPartial() {
com.google.ads.googleads.v19.errors.PolicyViolationDetails result = new com.google.ads.googleads.v19.errors.PolicyViolationDetails(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.errors.PolicyViolationDetails result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.externalPolicyDescription_ = externalPolicyDescription_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.key_ = keyBuilder_ == null
? key_
: keyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.externalPolicyName_ = externalPolicyName_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.isExemptible_ = isExemptible_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v19.errors.PolicyViolationDetails) {
return mergeFrom((com.google.ads.googleads.v19.errors.PolicyViolationDetails)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.errors.PolicyViolationDetails other) {
if (other == com.google.ads.googleads.v19.errors.PolicyViolationDetails.getDefaultInstance()) return this;
if (!other.getExternalPolicyDescription().isEmpty()) {
externalPolicyDescription_ = other.externalPolicyDescription_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasKey()) {
mergeKey(other.getKey());
}
if (!other.getExternalPolicyName().isEmpty()) {
externalPolicyName_ = other.externalPolicyName_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.getIsExemptible() != false) {
setIsExemptible(other.getIsExemptible());
}
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: {
externalPolicyDescription_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 18
case 34: {
input.readMessage(
getKeyFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 42: {
externalPolicyName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 42
case 48: {
isExemptible_ = input.readBool();
bitField0_ |= 0x00000008;
break;
} // case 48
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 externalPolicyDescription_ = "";
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The externalPolicyDescription.
*/
public java.lang.String getExternalPolicyDescription() {
java.lang.Object ref = externalPolicyDescription_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
externalPolicyDescription_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The bytes for externalPolicyDescription.
*/
public com.google.protobuf.ByteString
getExternalPolicyDescriptionBytes() {
java.lang.Object ref = externalPolicyDescription_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyDescription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @param value The externalPolicyDescription to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyDescription(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
externalPolicyDescription_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return This builder for chaining.
*/
public Builder clearExternalPolicyDescription() {
externalPolicyDescription_ = getDefaultInstance().getExternalPolicyDescription();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @param value The bytes for externalPolicyDescription to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyDescriptionBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
externalPolicyDescription_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v19.common.PolicyViolationKey key_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.PolicyViolationKey, com.google.ads.googleads.v19.common.PolicyViolationKey.Builder, com.google.ads.googleads.v19.common.PolicyViolationKeyOrBuilder> keyBuilder_;
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
* @return Whether the key field is set.
*/
public boolean hasKey() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
* @return The key.
*/
public com.google.ads.googleads.v19.common.PolicyViolationKey getKey() {
if (keyBuilder_ == null) {
return key_ == null ? com.google.ads.googleads.v19.common.PolicyViolationKey.getDefaultInstance() : key_;
} else {
return keyBuilder_.getMessage();
}
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
public Builder setKey(com.google.ads.googleads.v19.common.PolicyViolationKey value) {
if (keyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
} else {
keyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
public Builder setKey(
com.google.ads.googleads.v19.common.PolicyViolationKey.Builder builderForValue) {
if (keyBuilder_ == null) {
key_ = builderForValue.build();
} else {
keyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
public Builder mergeKey(com.google.ads.googleads.v19.common.PolicyViolationKey value) {
if (keyBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
key_ != null &&
key_ != com.google.ads.googleads.v19.common.PolicyViolationKey.getDefaultInstance()) {
getKeyBuilder().mergeFrom(value);
} else {
key_ = value;
}
} else {
keyBuilder_.mergeFrom(value);
}
if (key_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
public Builder clearKey() {
bitField0_ = (bitField0_ & ~0x00000002);
key_ = null;
if (keyBuilder_ != null) {
keyBuilder_.dispose();
keyBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
public com.google.ads.googleads.v19.common.PolicyViolationKey.Builder getKeyBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getKeyFieldBuilder().getBuilder();
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
public com.google.ads.googleads.v19.common.PolicyViolationKeyOrBuilder getKeyOrBuilder() {
if (keyBuilder_ != null) {
return keyBuilder_.getMessageOrBuilder();
} else {
return key_ == null ?
com.google.ads.googleads.v19.common.PolicyViolationKey.getDefaultInstance() : key_;
}
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v19.common.PolicyViolationKey key = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.PolicyViolationKey, com.google.ads.googleads.v19.common.PolicyViolationKey.Builder, com.google.ads.googleads.v19.common.PolicyViolationKeyOrBuilder>
getKeyFieldBuilder() {
if (keyBuilder_ == null) {
keyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.PolicyViolationKey, com.google.ads.googleads.v19.common.PolicyViolationKey.Builder, com.google.ads.googleads.v19.common.PolicyViolationKeyOrBuilder>(
getKey(),
getParentForChildren(),
isClean());
key_ = null;
}
return keyBuilder_;
}
private java.lang.Object externalPolicyName_ = "";
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The externalPolicyName.
*/
public java.lang.String getExternalPolicyName() {
java.lang.Object ref = externalPolicyName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
externalPolicyName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The bytes for externalPolicyName.
*/
public com.google.protobuf.ByteString
getExternalPolicyNameBytes() {
java.lang.Object ref = externalPolicyName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @param value The externalPolicyName to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
externalPolicyName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return This builder for chaining.
*/
public Builder clearExternalPolicyName() {
externalPolicyName_ = getDefaultInstance().getExternalPolicyName();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @param value The bytes for externalPolicyName to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
externalPolicyName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private boolean isExemptible_ ;
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return The isExemptible.
*/
@java.lang.Override
public boolean getIsExemptible() {
return isExemptible_;
}
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @param value The isExemptible to set.
* @return This builder for chaining.
*/
public Builder setIsExemptible(boolean value) {
isExemptible_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return This builder for chaining.
*/
public Builder clearIsExemptible() {
bitField0_ = (bitField0_ & ~0x00000008);
isExemptible_ = 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.errors.PolicyViolationDetails)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.errors.PolicyViolationDetails)
private static final com.google.ads.googleads.v19.errors.PolicyViolationDetails DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.errors.PolicyViolationDetails();
}
public static com.google.ads.googleads.v19.errors.PolicyViolationDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PolicyViolationDetails>
PARSER = new com.google.protobuf.AbstractParser<PolicyViolationDetails>() {
@java.lang.Override
public PolicyViolationDetails 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<PolicyViolationDetails> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PolicyViolationDetails> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.errors.PolicyViolationDetails getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 37,529 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/errors/PolicyViolationDetails.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/errors/errors.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.errors;
/**
* <pre>
* Error returned as part of a mutate response.
* This error indicates single policy violation by some text
* in one of the fields.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.errors.PolicyViolationDetails}
*/
public final class PolicyViolationDetails extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.errors.PolicyViolationDetails)
PolicyViolationDetailsOrBuilder {
private static final long serialVersionUID = 0L;
// Use PolicyViolationDetails.newBuilder() to construct.
private PolicyViolationDetails(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PolicyViolationDetails() {
externalPolicyDescription_ = "";
externalPolicyName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new PolicyViolationDetails();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.errors.ErrorsProto.internal_static_google_ads_googleads_v20_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.errors.ErrorsProto.internal_static_google_ads_googleads_v20_errors_PolicyViolationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.errors.PolicyViolationDetails.class, com.google.ads.googleads.v20.errors.PolicyViolationDetails.Builder.class);
}
private int bitField0_;
public static final int EXTERNAL_POLICY_DESCRIPTION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object externalPolicyDescription_ = "";
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The externalPolicyDescription.
*/
@java.lang.Override
public java.lang.String getExternalPolicyDescription() {
java.lang.Object ref = externalPolicyDescription_;
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();
externalPolicyDescription_ = s;
return s;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The bytes for externalPolicyDescription.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getExternalPolicyDescriptionBytes() {
java.lang.Object ref = externalPolicyDescription_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyDescription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int KEY_FIELD_NUMBER = 4;
private com.google.ads.googleads.v20.common.PolicyViolationKey key_;
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
* @return Whether the key field is set.
*/
@java.lang.Override
public boolean hasKey() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
* @return The key.
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.PolicyViolationKey getKey() {
return key_ == null ? com.google.ads.googleads.v20.common.PolicyViolationKey.getDefaultInstance() : key_;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.PolicyViolationKeyOrBuilder getKeyOrBuilder() {
return key_ == null ? com.google.ads.googleads.v20.common.PolicyViolationKey.getDefaultInstance() : key_;
}
public static final int EXTERNAL_POLICY_NAME_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object externalPolicyName_ = "";
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The externalPolicyName.
*/
@java.lang.Override
public java.lang.String getExternalPolicyName() {
java.lang.Object ref = externalPolicyName_;
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();
externalPolicyName_ = s;
return s;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The bytes for externalPolicyName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getExternalPolicyNameBytes() {
java.lang.Object ref = externalPolicyName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IS_EXEMPTIBLE_FIELD_NUMBER = 6;
private boolean isExemptible_ = false;
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return The isExemptible.
*/
@java.lang.Override
public boolean getIsExemptible() {
return isExemptible_;
}
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(externalPolicyDescription_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, externalPolicyDescription_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPolicyName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, externalPolicyName_);
}
if (isExemptible_ != false) {
output.writeBool(6, isExemptible_);
}
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(externalPolicyDescription_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, externalPolicyDescription_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPolicyName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, externalPolicyName_);
}
if (isExemptible_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(6, isExemptible_);
}
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.errors.PolicyViolationDetails)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.errors.PolicyViolationDetails other = (com.google.ads.googleads.v20.errors.PolicyViolationDetails) obj;
if (!getExternalPolicyDescription()
.equals(other.getExternalPolicyDescription())) return false;
if (hasKey() != other.hasKey()) return false;
if (hasKey()) {
if (!getKey()
.equals(other.getKey())) return false;
}
if (!getExternalPolicyName()
.equals(other.getExternalPolicyName())) return false;
if (getIsExemptible()
!= other.getIsExemptible()) 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) + EXTERNAL_POLICY_DESCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getExternalPolicyDescription().hashCode();
if (hasKey()) {
hash = (37 * hash) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
}
hash = (37 * hash) + EXTERNAL_POLICY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getExternalPolicyName().hashCode();
hash = (37 * hash) + IS_EXEMPTIBLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getIsExemptible());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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>
* Error returned as part of a mutate response.
* This error indicates single policy violation by some text
* in one of the fields.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.errors.PolicyViolationDetails}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.errors.PolicyViolationDetails)
com.google.ads.googleads.v20.errors.PolicyViolationDetailsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.errors.ErrorsProto.internal_static_google_ads_googleads_v20_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.errors.ErrorsProto.internal_static_google_ads_googleads_v20_errors_PolicyViolationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.errors.PolicyViolationDetails.class, com.google.ads.googleads.v20.errors.PolicyViolationDetails.Builder.class);
}
// Construct using com.google.ads.googleads.v20.errors.PolicyViolationDetails.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getKeyFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
externalPolicyDescription_ = "";
key_ = null;
if (keyBuilder_ != null) {
keyBuilder_.dispose();
keyBuilder_ = null;
}
externalPolicyName_ = "";
isExemptible_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.errors.ErrorsProto.internal_static_google_ads_googleads_v20_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.PolicyViolationDetails getDefaultInstanceForType() {
return com.google.ads.googleads.v20.errors.PolicyViolationDetails.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.PolicyViolationDetails build() {
com.google.ads.googleads.v20.errors.PolicyViolationDetails result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.PolicyViolationDetails buildPartial() {
com.google.ads.googleads.v20.errors.PolicyViolationDetails result = new com.google.ads.googleads.v20.errors.PolicyViolationDetails(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.errors.PolicyViolationDetails result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.externalPolicyDescription_ = externalPolicyDescription_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.key_ = keyBuilder_ == null
? key_
: keyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.externalPolicyName_ = externalPolicyName_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.isExemptible_ = isExemptible_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v20.errors.PolicyViolationDetails) {
return mergeFrom((com.google.ads.googleads.v20.errors.PolicyViolationDetails)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.errors.PolicyViolationDetails other) {
if (other == com.google.ads.googleads.v20.errors.PolicyViolationDetails.getDefaultInstance()) return this;
if (!other.getExternalPolicyDescription().isEmpty()) {
externalPolicyDescription_ = other.externalPolicyDescription_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasKey()) {
mergeKey(other.getKey());
}
if (!other.getExternalPolicyName().isEmpty()) {
externalPolicyName_ = other.externalPolicyName_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.getIsExemptible() != false) {
setIsExemptible(other.getIsExemptible());
}
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: {
externalPolicyDescription_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 18
case 34: {
input.readMessage(
getKeyFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 42: {
externalPolicyName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 42
case 48: {
isExemptible_ = input.readBool();
bitField0_ |= 0x00000008;
break;
} // case 48
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 externalPolicyDescription_ = "";
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The externalPolicyDescription.
*/
public java.lang.String getExternalPolicyDescription() {
java.lang.Object ref = externalPolicyDescription_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
externalPolicyDescription_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The bytes for externalPolicyDescription.
*/
public com.google.protobuf.ByteString
getExternalPolicyDescriptionBytes() {
java.lang.Object ref = externalPolicyDescription_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyDescription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @param value The externalPolicyDescription to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyDescription(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
externalPolicyDescription_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return This builder for chaining.
*/
public Builder clearExternalPolicyDescription() {
externalPolicyDescription_ = getDefaultInstance().getExternalPolicyDescription();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @param value The bytes for externalPolicyDescription to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyDescriptionBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
externalPolicyDescription_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v20.common.PolicyViolationKey key_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.PolicyViolationKey, com.google.ads.googleads.v20.common.PolicyViolationKey.Builder, com.google.ads.googleads.v20.common.PolicyViolationKeyOrBuilder> keyBuilder_;
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
* @return Whether the key field is set.
*/
public boolean hasKey() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
* @return The key.
*/
public com.google.ads.googleads.v20.common.PolicyViolationKey getKey() {
if (keyBuilder_ == null) {
return key_ == null ? com.google.ads.googleads.v20.common.PolicyViolationKey.getDefaultInstance() : key_;
} else {
return keyBuilder_.getMessage();
}
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
public Builder setKey(com.google.ads.googleads.v20.common.PolicyViolationKey value) {
if (keyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
} else {
keyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
public Builder setKey(
com.google.ads.googleads.v20.common.PolicyViolationKey.Builder builderForValue) {
if (keyBuilder_ == null) {
key_ = builderForValue.build();
} else {
keyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
public Builder mergeKey(com.google.ads.googleads.v20.common.PolicyViolationKey value) {
if (keyBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
key_ != null &&
key_ != com.google.ads.googleads.v20.common.PolicyViolationKey.getDefaultInstance()) {
getKeyBuilder().mergeFrom(value);
} else {
key_ = value;
}
} else {
keyBuilder_.mergeFrom(value);
}
if (key_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
public Builder clearKey() {
bitField0_ = (bitField0_ & ~0x00000002);
key_ = null;
if (keyBuilder_ != null) {
keyBuilder_.dispose();
keyBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
public com.google.ads.googleads.v20.common.PolicyViolationKey.Builder getKeyBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getKeyFieldBuilder().getBuilder();
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
public com.google.ads.googleads.v20.common.PolicyViolationKeyOrBuilder getKeyOrBuilder() {
if (keyBuilder_ != null) {
return keyBuilder_.getMessageOrBuilder();
} else {
return key_ == null ?
com.google.ads.googleads.v20.common.PolicyViolationKey.getDefaultInstance() : key_;
}
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v20.common.PolicyViolationKey key = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.PolicyViolationKey, com.google.ads.googleads.v20.common.PolicyViolationKey.Builder, com.google.ads.googleads.v20.common.PolicyViolationKeyOrBuilder>
getKeyFieldBuilder() {
if (keyBuilder_ == null) {
keyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.PolicyViolationKey, com.google.ads.googleads.v20.common.PolicyViolationKey.Builder, com.google.ads.googleads.v20.common.PolicyViolationKeyOrBuilder>(
getKey(),
getParentForChildren(),
isClean());
key_ = null;
}
return keyBuilder_;
}
private java.lang.Object externalPolicyName_ = "";
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The externalPolicyName.
*/
public java.lang.String getExternalPolicyName() {
java.lang.Object ref = externalPolicyName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
externalPolicyName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The bytes for externalPolicyName.
*/
public com.google.protobuf.ByteString
getExternalPolicyNameBytes() {
java.lang.Object ref = externalPolicyName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @param value The externalPolicyName to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
externalPolicyName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return This builder for chaining.
*/
public Builder clearExternalPolicyName() {
externalPolicyName_ = getDefaultInstance().getExternalPolicyName();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @param value The bytes for externalPolicyName to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
externalPolicyName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private boolean isExemptible_ ;
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return The isExemptible.
*/
@java.lang.Override
public boolean getIsExemptible() {
return isExemptible_;
}
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @param value The isExemptible to set.
* @return This builder for chaining.
*/
public Builder setIsExemptible(boolean value) {
isExemptible_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return This builder for chaining.
*/
public Builder clearIsExemptible() {
bitField0_ = (bitField0_ & ~0x00000008);
isExemptible_ = 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.errors.PolicyViolationDetails)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.errors.PolicyViolationDetails)
private static final com.google.ads.googleads.v20.errors.PolicyViolationDetails DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.errors.PolicyViolationDetails();
}
public static com.google.ads.googleads.v20.errors.PolicyViolationDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PolicyViolationDetails>
PARSER = new com.google.protobuf.AbstractParser<PolicyViolationDetails>() {
@java.lang.Override
public PolicyViolationDetails 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<PolicyViolationDetails> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PolicyViolationDetails> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.errors.PolicyViolationDetails getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 37,529 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/errors/PolicyViolationDetails.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/errors/errors.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.errors;
/**
* <pre>
* Error returned as part of a mutate response.
* This error indicates single policy violation by some text
* in one of the fields.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.errors.PolicyViolationDetails}
*/
public final class PolicyViolationDetails extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.errors.PolicyViolationDetails)
PolicyViolationDetailsOrBuilder {
private static final long serialVersionUID = 0L;
// Use PolicyViolationDetails.newBuilder() to construct.
private PolicyViolationDetails(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PolicyViolationDetails() {
externalPolicyDescription_ = "";
externalPolicyName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new PolicyViolationDetails();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.errors.ErrorsProto.internal_static_google_ads_googleads_v21_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.errors.ErrorsProto.internal_static_google_ads_googleads_v21_errors_PolicyViolationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.errors.PolicyViolationDetails.class, com.google.ads.googleads.v21.errors.PolicyViolationDetails.Builder.class);
}
private int bitField0_;
public static final int EXTERNAL_POLICY_DESCRIPTION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object externalPolicyDescription_ = "";
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The externalPolicyDescription.
*/
@java.lang.Override
public java.lang.String getExternalPolicyDescription() {
java.lang.Object ref = externalPolicyDescription_;
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();
externalPolicyDescription_ = s;
return s;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The bytes for externalPolicyDescription.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getExternalPolicyDescriptionBytes() {
java.lang.Object ref = externalPolicyDescription_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyDescription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int KEY_FIELD_NUMBER = 4;
private com.google.ads.googleads.v21.common.PolicyViolationKey key_;
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
* @return Whether the key field is set.
*/
@java.lang.Override
public boolean hasKey() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
* @return The key.
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.PolicyViolationKey getKey() {
return key_ == null ? com.google.ads.googleads.v21.common.PolicyViolationKey.getDefaultInstance() : key_;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.PolicyViolationKeyOrBuilder getKeyOrBuilder() {
return key_ == null ? com.google.ads.googleads.v21.common.PolicyViolationKey.getDefaultInstance() : key_;
}
public static final int EXTERNAL_POLICY_NAME_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object externalPolicyName_ = "";
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The externalPolicyName.
*/
@java.lang.Override
public java.lang.String getExternalPolicyName() {
java.lang.Object ref = externalPolicyName_;
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();
externalPolicyName_ = s;
return s;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The bytes for externalPolicyName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getExternalPolicyNameBytes() {
java.lang.Object ref = externalPolicyName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IS_EXEMPTIBLE_FIELD_NUMBER = 6;
private boolean isExemptible_ = false;
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return The isExemptible.
*/
@java.lang.Override
public boolean getIsExemptible() {
return isExemptible_;
}
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(externalPolicyDescription_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, externalPolicyDescription_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPolicyName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, externalPolicyName_);
}
if (isExemptible_ != false) {
output.writeBool(6, isExemptible_);
}
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(externalPolicyDescription_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, externalPolicyDescription_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(externalPolicyName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, externalPolicyName_);
}
if (isExemptible_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(6, isExemptible_);
}
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.errors.PolicyViolationDetails)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.errors.PolicyViolationDetails other = (com.google.ads.googleads.v21.errors.PolicyViolationDetails) obj;
if (!getExternalPolicyDescription()
.equals(other.getExternalPolicyDescription())) return false;
if (hasKey() != other.hasKey()) return false;
if (hasKey()) {
if (!getKey()
.equals(other.getKey())) return false;
}
if (!getExternalPolicyName()
.equals(other.getExternalPolicyName())) return false;
if (getIsExemptible()
!= other.getIsExemptible()) 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) + EXTERNAL_POLICY_DESCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getExternalPolicyDescription().hashCode();
if (hasKey()) {
hash = (37 * hash) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
}
hash = (37 * hash) + EXTERNAL_POLICY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getExternalPolicyName().hashCode();
hash = (37 * hash) + IS_EXEMPTIBLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getIsExemptible());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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.errors.PolicyViolationDetails 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>
* Error returned as part of a mutate response.
* This error indicates single policy violation by some text
* in one of the fields.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.errors.PolicyViolationDetails}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.errors.PolicyViolationDetails)
com.google.ads.googleads.v21.errors.PolicyViolationDetailsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.errors.ErrorsProto.internal_static_google_ads_googleads_v21_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.errors.ErrorsProto.internal_static_google_ads_googleads_v21_errors_PolicyViolationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.errors.PolicyViolationDetails.class, com.google.ads.googleads.v21.errors.PolicyViolationDetails.Builder.class);
}
// Construct using com.google.ads.googleads.v21.errors.PolicyViolationDetails.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getKeyFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
externalPolicyDescription_ = "";
key_ = null;
if (keyBuilder_ != null) {
keyBuilder_.dispose();
keyBuilder_ = null;
}
externalPolicyName_ = "";
isExemptible_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.errors.ErrorsProto.internal_static_google_ads_googleads_v21_errors_PolicyViolationDetails_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.PolicyViolationDetails getDefaultInstanceForType() {
return com.google.ads.googleads.v21.errors.PolicyViolationDetails.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.PolicyViolationDetails build() {
com.google.ads.googleads.v21.errors.PolicyViolationDetails result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.PolicyViolationDetails buildPartial() {
com.google.ads.googleads.v21.errors.PolicyViolationDetails result = new com.google.ads.googleads.v21.errors.PolicyViolationDetails(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.errors.PolicyViolationDetails result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.externalPolicyDescription_ = externalPolicyDescription_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.key_ = keyBuilder_ == null
? key_
: keyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.externalPolicyName_ = externalPolicyName_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.isExemptible_ = isExemptible_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v21.errors.PolicyViolationDetails) {
return mergeFrom((com.google.ads.googleads.v21.errors.PolicyViolationDetails)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.errors.PolicyViolationDetails other) {
if (other == com.google.ads.googleads.v21.errors.PolicyViolationDetails.getDefaultInstance()) return this;
if (!other.getExternalPolicyDescription().isEmpty()) {
externalPolicyDescription_ = other.externalPolicyDescription_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasKey()) {
mergeKey(other.getKey());
}
if (!other.getExternalPolicyName().isEmpty()) {
externalPolicyName_ = other.externalPolicyName_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.getIsExemptible() != false) {
setIsExemptible(other.getIsExemptible());
}
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: {
externalPolicyDescription_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 18
case 34: {
input.readMessage(
getKeyFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 42: {
externalPolicyName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 42
case 48: {
isExemptible_ = input.readBool();
bitField0_ |= 0x00000008;
break;
} // case 48
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 externalPolicyDescription_ = "";
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The externalPolicyDescription.
*/
public java.lang.String getExternalPolicyDescription() {
java.lang.Object ref = externalPolicyDescription_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
externalPolicyDescription_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return The bytes for externalPolicyDescription.
*/
public com.google.protobuf.ByteString
getExternalPolicyDescriptionBytes() {
java.lang.Object ref = externalPolicyDescription_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyDescription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @param value The externalPolicyDescription to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyDescription(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
externalPolicyDescription_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @return This builder for chaining.
*/
public Builder clearExternalPolicyDescription() {
externalPolicyDescription_ = getDefaultInstance().getExternalPolicyDescription();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Human readable description of policy violation.
* </pre>
*
* <code>string external_policy_description = 2;</code>
* @param value The bytes for externalPolicyDescription to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyDescriptionBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
externalPolicyDescription_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v21.common.PolicyViolationKey key_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.PolicyViolationKey, com.google.ads.googleads.v21.common.PolicyViolationKey.Builder, com.google.ads.googleads.v21.common.PolicyViolationKeyOrBuilder> keyBuilder_;
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
* @return Whether the key field is set.
*/
public boolean hasKey() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
* @return The key.
*/
public com.google.ads.googleads.v21.common.PolicyViolationKey getKey() {
if (keyBuilder_ == null) {
return key_ == null ? com.google.ads.googleads.v21.common.PolicyViolationKey.getDefaultInstance() : key_;
} else {
return keyBuilder_.getMessage();
}
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
public Builder setKey(com.google.ads.googleads.v21.common.PolicyViolationKey value) {
if (keyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
} else {
keyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
public Builder setKey(
com.google.ads.googleads.v21.common.PolicyViolationKey.Builder builderForValue) {
if (keyBuilder_ == null) {
key_ = builderForValue.build();
} else {
keyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
public Builder mergeKey(com.google.ads.googleads.v21.common.PolicyViolationKey value) {
if (keyBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
key_ != null &&
key_ != com.google.ads.googleads.v21.common.PolicyViolationKey.getDefaultInstance()) {
getKeyBuilder().mergeFrom(value);
} else {
key_ = value;
}
} else {
keyBuilder_.mergeFrom(value);
}
if (key_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
public Builder clearKey() {
bitField0_ = (bitField0_ & ~0x00000002);
key_ = null;
if (keyBuilder_ != null) {
keyBuilder_.dispose();
keyBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
public com.google.ads.googleads.v21.common.PolicyViolationKey.Builder getKeyBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getKeyFieldBuilder().getBuilder();
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
public com.google.ads.googleads.v21.common.PolicyViolationKeyOrBuilder getKeyOrBuilder() {
if (keyBuilder_ != null) {
return keyBuilder_.getMessageOrBuilder();
} else {
return key_ == null ?
com.google.ads.googleads.v21.common.PolicyViolationKey.getDefaultInstance() : key_;
}
}
/**
* <pre>
* Unique identifier for this violation.
* If policy is exemptible, this key may be used to request exemption.
* </pre>
*
* <code>.google.ads.googleads.v21.common.PolicyViolationKey key = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.PolicyViolationKey, com.google.ads.googleads.v21.common.PolicyViolationKey.Builder, com.google.ads.googleads.v21.common.PolicyViolationKeyOrBuilder>
getKeyFieldBuilder() {
if (keyBuilder_ == null) {
keyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.PolicyViolationKey, com.google.ads.googleads.v21.common.PolicyViolationKey.Builder, com.google.ads.googleads.v21.common.PolicyViolationKeyOrBuilder>(
getKey(),
getParentForChildren(),
isClean());
key_ = null;
}
return keyBuilder_;
}
private java.lang.Object externalPolicyName_ = "";
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The externalPolicyName.
*/
public java.lang.String getExternalPolicyName() {
java.lang.Object ref = externalPolicyName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
externalPolicyName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return The bytes for externalPolicyName.
*/
public com.google.protobuf.ByteString
getExternalPolicyNameBytes() {
java.lang.Object ref = externalPolicyName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
externalPolicyName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @param value The externalPolicyName to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
externalPolicyName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @return This builder for chaining.
*/
public Builder clearExternalPolicyName() {
externalPolicyName_ = getDefaultInstance().getExternalPolicyName();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
* <pre>
* Human readable name of the policy.
* </pre>
*
* <code>string external_policy_name = 5;</code>
* @param value The bytes for externalPolicyName to set.
* @return This builder for chaining.
*/
public Builder setExternalPolicyNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
externalPolicyName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private boolean isExemptible_ ;
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return The isExemptible.
*/
@java.lang.Override
public boolean getIsExemptible() {
return isExemptible_;
}
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @param value The isExemptible to set.
* @return This builder for chaining.
*/
public Builder setIsExemptible(boolean value) {
isExemptible_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Whether user can file an exemption request for this violation.
* </pre>
*
* <code>bool is_exemptible = 6;</code>
* @return This builder for chaining.
*/
public Builder clearIsExemptible() {
bitField0_ = (bitField0_ & ~0x00000008);
isExemptible_ = 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.errors.PolicyViolationDetails)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.errors.PolicyViolationDetails)
private static final com.google.ads.googleads.v21.errors.PolicyViolationDetails DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.errors.PolicyViolationDetails();
}
public static com.google.ads.googleads.v21.errors.PolicyViolationDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PolicyViolationDetails>
PARSER = new com.google.protobuf.AbstractParser<PolicyViolationDetails>() {
@java.lang.Override
public PolicyViolationDetails 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<PolicyViolationDetails> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PolicyViolationDetails> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.errors.PolicyViolationDetails getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,405 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListSchedulesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/schedule_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [ScheduleService.ListSchedules][google.cloud.aiplatform.v1beta1.ScheduleService.ListSchedules]
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListSchedulesResponse}
*/
public final class ListSchedulesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListSchedulesResponse)
ListSchedulesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSchedulesResponse.newBuilder() to construct.
private ListSchedulesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSchedulesResponse() {
schedules_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSchedulesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ScheduleServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSchedulesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ScheduleServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSchedulesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.class,
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.Builder.class);
}
public static final int SCHEDULES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Schedule> schedules_;
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Schedule> getSchedulesList() {
return schedules_;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder>
getSchedulesOrBuilderList() {
return schedules_;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
@java.lang.Override
public int getSchedulesCount() {
return schedules_.size();
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Schedule getSchedules(int index) {
return schedules_.get(index);
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder getSchedulesOrBuilder(int index) {
return schedules_.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
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.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
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.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 < schedules_.size(); i++) {
output.writeMessage(1, schedules_.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 < schedules_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, schedules_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse other =
(com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse) obj;
if (!getSchedulesList().equals(other.getSchedulesList())) 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 (getSchedulesCount() > 0) {
hash = (37 * hash) + SCHEDULES_FIELD_NUMBER;
hash = (53 * hash) + getSchedulesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse 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
* [ScheduleService.ListSchedules][google.cloud.aiplatform.v1beta1.ScheduleService.ListSchedules]
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListSchedulesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListSchedulesResponse)
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ScheduleServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSchedulesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ScheduleServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSchedulesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.class,
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (schedulesBuilder_ == null) {
schedules_ = java.util.Collections.emptyList();
} else {
schedules_ = null;
schedulesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.ScheduleServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListSchedulesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse build() {
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse result =
new com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse result) {
if (schedulesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
schedules_ = java.util.Collections.unmodifiableList(schedules_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.schedules_ = schedules_;
} else {
result.schedules_ = schedulesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse.getDefaultInstance())
return this;
if (schedulesBuilder_ == null) {
if (!other.schedules_.isEmpty()) {
if (schedules_.isEmpty()) {
schedules_ = other.schedules_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSchedulesIsMutable();
schedules_.addAll(other.schedules_);
}
onChanged();
}
} else {
if (!other.schedules_.isEmpty()) {
if (schedulesBuilder_.isEmpty()) {
schedulesBuilder_.dispose();
schedulesBuilder_ = null;
schedules_ = other.schedules_;
bitField0_ = (bitField0_ & ~0x00000001);
schedulesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSchedulesFieldBuilder()
: null;
} else {
schedulesBuilder_.addAllMessages(other.schedules_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.Schedule m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.Schedule.parser(), extensionRegistry);
if (schedulesBuilder_ == null) {
ensureSchedulesIsMutable();
schedules_.add(m);
} else {
schedulesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1beta1.Schedule> schedules_ =
java.util.Collections.emptyList();
private void ensureSchedulesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
schedules_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Schedule>(schedules_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Schedule,
com.google.cloud.aiplatform.v1beta1.Schedule.Builder,
com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder>
schedulesBuilder_;
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Schedule> getSchedulesList() {
if (schedulesBuilder_ == null) {
return java.util.Collections.unmodifiableList(schedules_);
} else {
return schedulesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public int getSchedulesCount() {
if (schedulesBuilder_ == null) {
return schedules_.size();
} else {
return schedulesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Schedule getSchedules(int index) {
if (schedulesBuilder_ == null) {
return schedules_.get(index);
} else {
return schedulesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder setSchedules(int index, com.google.cloud.aiplatform.v1beta1.Schedule value) {
if (schedulesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchedulesIsMutable();
schedules_.set(index, value);
onChanged();
} else {
schedulesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder setSchedules(
int index, com.google.cloud.aiplatform.v1beta1.Schedule.Builder builderForValue) {
if (schedulesBuilder_ == null) {
ensureSchedulesIsMutable();
schedules_.set(index, builderForValue.build());
onChanged();
} else {
schedulesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder addSchedules(com.google.cloud.aiplatform.v1beta1.Schedule value) {
if (schedulesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchedulesIsMutable();
schedules_.add(value);
onChanged();
} else {
schedulesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder addSchedules(int index, com.google.cloud.aiplatform.v1beta1.Schedule value) {
if (schedulesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchedulesIsMutable();
schedules_.add(index, value);
onChanged();
} else {
schedulesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder addSchedules(
com.google.cloud.aiplatform.v1beta1.Schedule.Builder builderForValue) {
if (schedulesBuilder_ == null) {
ensureSchedulesIsMutable();
schedules_.add(builderForValue.build());
onChanged();
} else {
schedulesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder addSchedules(
int index, com.google.cloud.aiplatform.v1beta1.Schedule.Builder builderForValue) {
if (schedulesBuilder_ == null) {
ensureSchedulesIsMutable();
schedules_.add(index, builderForValue.build());
onChanged();
} else {
schedulesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder addAllSchedules(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Schedule> values) {
if (schedulesBuilder_ == null) {
ensureSchedulesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, schedules_);
onChanged();
} else {
schedulesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder clearSchedules() {
if (schedulesBuilder_ == null) {
schedules_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
schedulesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public Builder removeSchedules(int index) {
if (schedulesBuilder_ == null) {
ensureSchedulesIsMutable();
schedules_.remove(index);
onChanged();
} else {
schedulesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Schedule.Builder getSchedulesBuilder(int index) {
return getSchedulesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder getSchedulesOrBuilder(int index) {
if (schedulesBuilder_ == null) {
return schedules_.get(index);
} else {
return schedulesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder>
getSchedulesOrBuilderList() {
if (schedulesBuilder_ != null) {
return schedulesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(schedules_);
}
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Schedule.Builder addSchedulesBuilder() {
return getSchedulesFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Schedule.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Schedule.Builder addSchedulesBuilder(int index) {
return getSchedulesFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Schedule.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Schedules in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Schedule schedules = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Schedule.Builder>
getSchedulesBuilderList() {
return getSchedulesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Schedule,
com.google.cloud.aiplatform.v1beta1.Schedule.Builder,
com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder>
getSchedulesFieldBuilder() {
if (schedulesBuilder_ == null) {
schedulesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Schedule,
com.google.cloud.aiplatform.v1beta1.Schedule.Builder,
com.google.cloud.aiplatform.v1beta1.ScheduleOrBuilder>(
schedules_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
schedules_ = null;
}
return schedulesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve the next page of results.
* Pass to
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.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
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.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
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.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
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.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
* [ListSchedulesRequest.page_token][google.cloud.aiplatform.v1beta1.ListSchedulesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ListSchedulesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListSchedulesResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse();
}
public static com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSchedulesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSchedulesResponse>() {
@java.lang.Override
public ListSchedulesResponse 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<ListSchedulesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSchedulesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListSchedulesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,416 | java-securitycenter/proto-google-cloud-securitycenter-v2/src/main/java/com/google/cloud/securitycenter/v2/ListMuteConfigsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v2/securitycenter_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycenter.v2;
/**
*
*
* <pre>
* Response message for listing mute configs.
* </pre>
*
* Protobuf type {@code google.cloud.securitycenter.v2.ListMuteConfigsResponse}
*/
public final class ListMuteConfigsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v2.ListMuteConfigsResponse)
ListMuteConfigsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListMuteConfigsResponse.newBuilder() to construct.
private ListMuteConfigsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListMuteConfigsResponse() {
muteConfigs_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListMuteConfigsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v2.SecuritycenterServiceProto
.internal_static_google_cloud_securitycenter_v2_ListMuteConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v2.SecuritycenterServiceProto
.internal_static_google_cloud_securitycenter_v2_ListMuteConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.class,
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.Builder.class);
}
public static final int MUTE_CONFIGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.securitycenter.v2.MuteConfig> muteConfigs_;
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.securitycenter.v2.MuteConfig> getMuteConfigsList() {
return muteConfigs_;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.securitycenter.v2.MuteConfigOrBuilder>
getMuteConfigsOrBuilderList() {
return muteConfigs_;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public int getMuteConfigsCount() {
return muteConfigs_.size();
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v2.MuteConfig getMuteConfigs(int index) {
return muteConfigs_.get(index);
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v2.MuteConfigOrBuilder getMuteConfigsOrBuilder(int index) {
return muteConfigs_.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 < muteConfigs_.size(); i++) {
output.writeMessage(1, muteConfigs_.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 < muteConfigs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, muteConfigs_.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.securitycenter.v2.ListMuteConfigsResponse)) {
return super.equals(obj);
}
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse other =
(com.google.cloud.securitycenter.v2.ListMuteConfigsResponse) obj;
if (!getMuteConfigsList().equals(other.getMuteConfigsList())) 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 (getMuteConfigsCount() > 0) {
hash = (37 * hash) + MUTE_CONFIGS_FIELD_NUMBER;
hash = (53 * hash) + getMuteConfigsList().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.securitycenter.v2.ListMuteConfigsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse 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 listing mute configs.
* </pre>
*
* Protobuf type {@code google.cloud.securitycenter.v2.ListMuteConfigsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v2.ListMuteConfigsResponse)
com.google.cloud.securitycenter.v2.ListMuteConfigsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v2.SecuritycenterServiceProto
.internal_static_google_cloud_securitycenter_v2_ListMuteConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v2.SecuritycenterServiceProto
.internal_static_google_cloud_securitycenter_v2_ListMuteConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.class,
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.Builder.class);
}
// Construct using com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (muteConfigsBuilder_ == null) {
muteConfigs_ = java.util.Collections.emptyList();
} else {
muteConfigs_ = null;
muteConfigsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycenter.v2.SecuritycenterServiceProto
.internal_static_google_cloud_securitycenter_v2_ListMuteConfigsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycenter.v2.ListMuteConfigsResponse getDefaultInstanceForType() {
return com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycenter.v2.ListMuteConfigsResponse build() {
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycenter.v2.ListMuteConfigsResponse buildPartial() {
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse result =
new com.google.cloud.securitycenter.v2.ListMuteConfigsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.securitycenter.v2.ListMuteConfigsResponse result) {
if (muteConfigsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
muteConfigs_ = java.util.Collections.unmodifiableList(muteConfigs_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.muteConfigs_ = muteConfigs_;
} else {
result.muteConfigs_ = muteConfigsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.securitycenter.v2.ListMuteConfigsResponse 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.securitycenter.v2.ListMuteConfigsResponse) {
return mergeFrom((com.google.cloud.securitycenter.v2.ListMuteConfigsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.securitycenter.v2.ListMuteConfigsResponse other) {
if (other == com.google.cloud.securitycenter.v2.ListMuteConfigsResponse.getDefaultInstance())
return this;
if (muteConfigsBuilder_ == null) {
if (!other.muteConfigs_.isEmpty()) {
if (muteConfigs_.isEmpty()) {
muteConfigs_ = other.muteConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMuteConfigsIsMutable();
muteConfigs_.addAll(other.muteConfigs_);
}
onChanged();
}
} else {
if (!other.muteConfigs_.isEmpty()) {
if (muteConfigsBuilder_.isEmpty()) {
muteConfigsBuilder_.dispose();
muteConfigsBuilder_ = null;
muteConfigs_ = other.muteConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
muteConfigsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMuteConfigsFieldBuilder()
: null;
} else {
muteConfigsBuilder_.addAllMessages(other.muteConfigs_);
}
}
}
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.securitycenter.v2.MuteConfig m =
input.readMessage(
com.google.cloud.securitycenter.v2.MuteConfig.parser(), extensionRegistry);
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.add(m);
} else {
muteConfigsBuilder_.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.securitycenter.v2.MuteConfig> muteConfigs_ =
java.util.Collections.emptyList();
private void ensureMuteConfigsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
muteConfigs_ =
new java.util.ArrayList<com.google.cloud.securitycenter.v2.MuteConfig>(muteConfigs_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v2.MuteConfig,
com.google.cloud.securitycenter.v2.MuteConfig.Builder,
com.google.cloud.securitycenter.v2.MuteConfigOrBuilder>
muteConfigsBuilder_;
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public java.util.List<com.google.cloud.securitycenter.v2.MuteConfig> getMuteConfigsList() {
if (muteConfigsBuilder_ == null) {
return java.util.Collections.unmodifiableList(muteConfigs_);
} else {
return muteConfigsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public int getMuteConfigsCount() {
if (muteConfigsBuilder_ == null) {
return muteConfigs_.size();
} else {
return muteConfigsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v2.MuteConfig getMuteConfigs(int index) {
if (muteConfigsBuilder_ == null) {
return muteConfigs_.get(index);
} else {
return muteConfigsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder setMuteConfigs(int index, com.google.cloud.securitycenter.v2.MuteConfig value) {
if (muteConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMuteConfigsIsMutable();
muteConfigs_.set(index, value);
onChanged();
} else {
muteConfigsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder setMuteConfigs(
int index, com.google.cloud.securitycenter.v2.MuteConfig.Builder builderForValue) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.set(index, builderForValue.build());
onChanged();
} else {
muteConfigsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(com.google.cloud.securitycenter.v2.MuteConfig value) {
if (muteConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMuteConfigsIsMutable();
muteConfigs_.add(value);
onChanged();
} else {
muteConfigsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(int index, com.google.cloud.securitycenter.v2.MuteConfig value) {
if (muteConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMuteConfigsIsMutable();
muteConfigs_.add(index, value);
onChanged();
} else {
muteConfigsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(
com.google.cloud.securitycenter.v2.MuteConfig.Builder builderForValue) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.add(builderForValue.build());
onChanged();
} else {
muteConfigsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder addMuteConfigs(
int index, com.google.cloud.securitycenter.v2.MuteConfig.Builder builderForValue) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.add(index, builderForValue.build());
onChanged();
} else {
muteConfigsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder addAllMuteConfigs(
java.lang.Iterable<? extends com.google.cloud.securitycenter.v2.MuteConfig> values) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, muteConfigs_);
onChanged();
} else {
muteConfigsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder clearMuteConfigs() {
if (muteConfigsBuilder_ == null) {
muteConfigs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
muteConfigsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public Builder removeMuteConfigs(int index) {
if (muteConfigsBuilder_ == null) {
ensureMuteConfigsIsMutable();
muteConfigs_.remove(index);
onChanged();
} else {
muteConfigsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v2.MuteConfig.Builder getMuteConfigsBuilder(int index) {
return getMuteConfigsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v2.MuteConfigOrBuilder getMuteConfigsOrBuilder(
int index) {
if (muteConfigsBuilder_ == null) {
return muteConfigs_.get(index);
} else {
return muteConfigsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.securitycenter.v2.MuteConfigOrBuilder>
getMuteConfigsOrBuilderList() {
if (muteConfigsBuilder_ != null) {
return muteConfigsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(muteConfigs_);
}
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v2.MuteConfig.Builder addMuteConfigsBuilder() {
return getMuteConfigsFieldBuilder()
.addBuilder(com.google.cloud.securitycenter.v2.MuteConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public com.google.cloud.securitycenter.v2.MuteConfig.Builder addMuteConfigsBuilder(int index) {
return getMuteConfigsFieldBuilder()
.addBuilder(index, com.google.cloud.securitycenter.v2.MuteConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The mute configs from the specified parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v2.MuteConfig mute_configs = 1;</code>
*/
public java.util.List<com.google.cloud.securitycenter.v2.MuteConfig.Builder>
getMuteConfigsBuilderList() {
return getMuteConfigsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v2.MuteConfig,
com.google.cloud.securitycenter.v2.MuteConfig.Builder,
com.google.cloud.securitycenter.v2.MuteConfigOrBuilder>
getMuteConfigsFieldBuilder() {
if (muteConfigsBuilder_ == null) {
muteConfigsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v2.MuteConfig,
com.google.cloud.securitycenter.v2.MuteConfig.Builder,
com.google.cloud.securitycenter.v2.MuteConfigOrBuilder>(
muteConfigs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
muteConfigs_ = null;
}
return muteConfigsBuilder_;
}
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.securitycenter.v2.ListMuteConfigsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v2.ListMuteConfigsResponse)
private static final com.google.cloud.securitycenter.v2.ListMuteConfigsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v2.ListMuteConfigsResponse();
}
public static com.google.cloud.securitycenter.v2.ListMuteConfigsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListMuteConfigsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListMuteConfigsResponse>() {
@java.lang.Override
public ListMuteConfigsResponse 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<ListMuteConfigsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListMuteConfigsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycenter.v2.ListMuteConfigsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,505 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteImageRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for Images.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteImageRequest}
*/
public final class DeleteImageRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteImageRequest)
DeleteImageRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteImageRequest.newBuilder() to construct.
private DeleteImageRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteImageRequest() {
image_ = "";
project_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteImageRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteImageRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteImageRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteImageRequest.class,
com.google.cloud.compute.v1.DeleteImageRequest.Builder.class);
}
private int bitField0_;
public static final int IMAGE_FIELD_NUMBER = 100313435;
@SuppressWarnings("serial")
private volatile java.lang.Object image_ = "";
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The image.
*/
@java.lang.Override
public java.lang.String getImage() {
java.lang.Object ref = image_;
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();
image_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for image.
*/
@java.lang.Override
public com.google.protobuf.ByteString getImageBytes() {
java.lang.Object ref = image_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
image_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 37109963;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
@java.lang.Override
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(image_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 100313435, image_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(image_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(100313435, image_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.DeleteImageRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.DeleteImageRequest other =
(com.google.cloud.compute.v1.DeleteImageRequest) obj;
if (!getImage().equals(other.getImage())) return false;
if (!getProject().equals(other.getProject())) return false;
if (hasRequestId() != other.hasRequestId()) return false;
if (hasRequestId()) {
if (!getRequestId().equals(other.getRequestId())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + IMAGE_FIELD_NUMBER;
hash = (53 * hash) + getImage().hashCode();
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
if (hasRequestId()) {
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteImageRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.DeleteImageRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for Images.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteImageRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteImageRequest)
com.google.cloud.compute.v1.DeleteImageRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteImageRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteImageRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteImageRequest.class,
com.google.cloud.compute.v1.DeleteImageRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.DeleteImageRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
image_ = "";
project_ = "";
requestId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteImageRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteImageRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.DeleteImageRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteImageRequest build() {
com.google.cloud.compute.v1.DeleteImageRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteImageRequest buildPartial() {
com.google.cloud.compute.v1.DeleteImageRequest result =
new com.google.cloud.compute.v1.DeleteImageRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.DeleteImageRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.image_ = image_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.requestId_ = requestId_;
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.DeleteImageRequest) {
return mergeFrom((com.google.cloud.compute.v1.DeleteImageRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.DeleteImageRequest other) {
if (other == com.google.cloud.compute.v1.DeleteImageRequest.getDefaultInstance()) return this;
if (!other.getImage().isEmpty()) {
image_ = other.image_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasRequestId()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 296879706:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 296879706
case 802507482:
{
image_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 802507482
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object image_ = "";
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The image.
*/
public java.lang.String getImage() {
java.lang.Object ref = image_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
image_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for image.
*/
public com.google.protobuf.ByteString getImageBytes() {
java.lang.Object ref = image_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
image_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The image to set.
* @return This builder for chaining.
*/
public Builder setImage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
image_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearImage() {
image_ = getDefaultInstance().getImage();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the image resource to delete.
* </pre>
*
* <code>string image = 100313435 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for image to set.
* @return This builder for chaining.
*/
public Builder setImageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
image_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.DeleteImageRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteImageRequest)
private static final com.google.cloud.compute.v1.DeleteImageRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteImageRequest();
}
public static com.google.cloud.compute.v1.DeleteImageRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteImageRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteImageRequest>() {
@java.lang.Override
public DeleteImageRequest 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<DeleteImageRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteImageRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteImageRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,505 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteRouteRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for Routes.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteRouteRequest}
*/
public final class DeleteRouteRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteRouteRequest)
DeleteRouteRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteRouteRequest.newBuilder() to construct.
private DeleteRouteRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteRouteRequest() {
project_ = "";
requestId_ = "";
route_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteRouteRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteRouteRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteRouteRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteRouteRequest.class,
com.google.cloud.compute.v1.DeleteRouteRequest.Builder.class);
}
private int bitField0_;
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 37109963;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
@java.lang.Override
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ROUTE_FIELD_NUMBER = 108704329;
@SuppressWarnings("serial")
private volatile java.lang.Object route_ = "";
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The route.
*/
@java.lang.Override
public java.lang.String getRoute() {
java.lang.Object ref = route_;
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();
route_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for route.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRouteBytes() {
java.lang.Object ref = route_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
route_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(route_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 108704329, route_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(route_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(108704329, route_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.DeleteRouteRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.DeleteRouteRequest other =
(com.google.cloud.compute.v1.DeleteRouteRequest) obj;
if (!getProject().equals(other.getProject())) return false;
if (hasRequestId() != other.hasRequestId()) return false;
if (hasRequestId()) {
if (!getRequestId().equals(other.getRequestId())) return false;
}
if (!getRoute().equals(other.getRoute())) 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) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
if (hasRequestId()) {
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
}
hash = (37 * hash) + ROUTE_FIELD_NUMBER;
hash = (53 * hash) + getRoute().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteRouteRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.DeleteRouteRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for Routes.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteRouteRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteRouteRequest)
com.google.cloud.compute.v1.DeleteRouteRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteRouteRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteRouteRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteRouteRequest.class,
com.google.cloud.compute.v1.DeleteRouteRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.DeleteRouteRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
project_ = "";
requestId_ = "";
route_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteRouteRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteRouteRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.DeleteRouteRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteRouteRequest build() {
com.google.cloud.compute.v1.DeleteRouteRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteRouteRequest buildPartial() {
com.google.cloud.compute.v1.DeleteRouteRequest result =
new com.google.cloud.compute.v1.DeleteRouteRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.DeleteRouteRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.project_ = project_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.requestId_ = requestId_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.route_ = route_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.DeleteRouteRequest) {
return mergeFrom((com.google.cloud.compute.v1.DeleteRouteRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.DeleteRouteRequest other) {
if (other == com.google.cloud.compute.v1.DeleteRouteRequest.getDefaultInstance()) return this;
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasRequestId()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getRoute().isEmpty()) {
route_ = other.route_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 296879706:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 296879706
case 869634634:
{
route_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 869634634
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 1820481738
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object route_ = "";
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The route.
*/
public java.lang.String getRoute() {
java.lang.Object ref = route_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
route_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for route.
*/
public com.google.protobuf.ByteString getRouteBytes() {
java.lang.Object ref = route_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
route_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The route to set.
* @return This builder for chaining.
*/
public Builder setRoute(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
route_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearRoute() {
route_ = getDefaultInstance().getRoute();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the Route resource to delete.
* </pre>
*
* <code>string route = 108704329 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for route to set.
* @return This builder for chaining.
*/
public Builder setRouteBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
route_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.DeleteRouteRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteRouteRequest)
private static final com.google.cloud.compute.v1.DeleteRouteRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteRouteRequest();
}
public static com.google.cloud.compute.v1.DeleteRouteRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteRouteRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteRouteRequest>() {
@java.lang.Override
public DeleteRouteRequest 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<DeleteRouteRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteRouteRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteRouteRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,423 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition/AutoMlTables.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/schema/trainingjob/definition/automl_tables.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition;
/**
*
*
* <pre>
* A TrainingJob that trains and uploads an AutoML Tables Model.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables}
*/
public final class AutoMlTables extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables)
AutoMlTablesOrBuilder {
private static final long serialVersionUID = 0L;
// Use AutoMlTables.newBuilder() to construct.
private AutoMlTables(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AutoMlTables() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new AutoMlTables();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1beta1_schema_trainingjob_definition_AutoMlTables_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1beta1_schema_trainingjob_definition_AutoMlTables_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables.class,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables.Builder
.class);
}
private int bitField0_;
public static final int INPUTS_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
inputs_;
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return Whether the inputs field is set.
*/
@java.lang.Override
public boolean hasInputs() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return The inputs.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
getInputs() {
return inputs_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder
getInputsOrBuilder() {
return inputs_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
}
public static final int METADATA_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
metadata_;
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return Whether the metadata field is set.
*/
@java.lang.Override
public boolean hasMetadata() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return The metadata.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
getMetadata() {
return metadata_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder
getMetadataOrBuilder() {
return metadata_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
}
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, getInputs());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getMetadata());
}
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, getInputs());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getMetadata());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables other =
(com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables) obj;
if (hasInputs() != other.hasInputs()) return false;
if (hasInputs()) {
if (!getInputs().equals(other.getInputs())) return false;
}
if (hasMetadata() != other.hasMetadata()) return false;
if (hasMetadata()) {
if (!getMetadata().equals(other.getMetadata())) 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 (hasInputs()) {
hash = (37 * hash) + INPUTS_FIELD_NUMBER;
hash = (53 * hash) + getInputs().hashCode();
}
if (hasMetadata()) {
hash = (37 * hash) + METADATA_FIELD_NUMBER;
hash = (53 * hash) + getMetadata().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables 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 TrainingJob that trains and uploads an AutoML Tables Model.
* </pre>
*
* Protobuf type {@code
* google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables)
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1beta1_schema_trainingjob_definition_AutoMlTables_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1beta1_schema_trainingjob_definition_AutoMlTables_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables.class,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables.Builder
.class);
}
// Construct using
// com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getInputsFieldBuilder();
getMetadataFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
inputs_ = null;
if (inputsBuilder_ != null) {
inputsBuilder_.dispose();
inputsBuilder_ = null;
}
metadata_ = null;
if (metadataBuilder_ != null) {
metadataBuilder_.dispose();
metadataBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1beta1_schema_trainingjob_definition_AutoMlTables_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables build() {
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
buildPartial() {
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables result =
new com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.inputs_ = inputsBuilder_ == null ? inputs_ : inputsBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.metadata_ = metadataBuilder_ == null ? metadata_ : metadataBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables) {
return mergeFrom(
(com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables other) {
if (other
== com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
.getDefaultInstance()) return this;
if (other.hasInputs()) {
mergeInputs(other.getInputs());
}
if (other.hasMetadata()) {
mergeMetadata(other.getMetadata());
}
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(getInputsFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getMetadataFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
inputs_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.Builder,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder>
inputsBuilder_;
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return Whether the inputs field is set.
*/
public boolean hasInputs() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return The inputs.
*/
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
getInputs() {
if (inputsBuilder_ == null) {
return inputs_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
} else {
return inputsBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder setInputs(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
value) {
if (inputsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
inputs_ = value;
} else {
inputsBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder setInputs(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs.Builder
builderForValue) {
if (inputsBuilder_ == null) {
inputs_ = builderForValue.build();
} else {
inputsBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder mergeInputs(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
value) {
if (inputsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& inputs_ != null
&& inputs_
!= com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputs.getDefaultInstance()) {
getInputsBuilder().mergeFrom(value);
} else {
inputs_ = value;
}
} else {
inputsBuilder_.mergeFrom(value);
}
if (inputs_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder clearInputs() {
bitField0_ = (bitField0_ & ~0x00000001);
inputs_ = null;
if (inputsBuilder_ != null) {
inputsBuilder_.dispose();
inputsBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.Builder
getInputsBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getInputsFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder
getInputsOrBuilder() {
if (inputsBuilder_ != null) {
return inputsBuilder_.getMessageOrBuilder();
} else {
return inputs_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
}
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.Builder,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder>
getInputsFieldBuilder() {
if (inputsBuilder_ == null) {
inputsBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputs,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesInputs
.Builder,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder>(getInputs(), getParentForChildren(), isClean());
inputs_ = null;
}
return inputsBuilder_;
}
private com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
metadata_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder>
metadataBuilder_;
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return Whether the metadata field is set.
*/
public boolean hasMetadata() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return The metadata.
*/
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
getMetadata() {
if (metadataBuilder_ == null) {
return metadata_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
} else {
return metadataBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder setMetadata(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
value) {
if (metadataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
metadata_ = value;
} else {
metadataBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder setMetadata(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder
builderForValue) {
if (metadataBuilder_ == null) {
metadata_ = builderForValue.build();
} else {
metadataBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder mergeMetadata(
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
value) {
if (metadataBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& metadata_ != null
&& metadata_
!= com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadata.getDefaultInstance()) {
getMetadataBuilder().mergeFrom(value);
} else {
metadata_ = value;
}
} else {
metadataBuilder_.mergeFrom(value);
}
if (metadata_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder clearMetadata() {
bitField0_ = (bitField0_ & ~0x00000002);
metadata_ = null;
if (metadataBuilder_ != null) {
metadataBuilder_.dispose();
metadataBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder
getMetadataBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getMetadataFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder
getMetadataOrBuilder() {
if (metadataBuilder_ != null) {
return metadataBuilder_.getMessageOrBuilder();
} else {
return metadata_ == null
? com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
}
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder>
getMetadataFieldBuilder() {
if (metadataBuilder_ == null) {
metadataBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadata,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadata.Builder,
com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder>(
getMetadata(), getParentForChildren(), isClean());
metadata_ = null;
}
return metadataBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables)
private static final com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition
.AutoMlTables
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables();
}
public static com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AutoMlTables> PARSER =
new com.google.protobuf.AbstractParser<AutoMlTables>() {
@java.lang.Override
public AutoMlTables 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<AutoMlTables> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AutoMlTables> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.schema.trainingjob.definition.AutoMlTables
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hadoop | 37,380 | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/yarn/server/federation/policies/amrmproxy/TestLocalityMulticastAMRMProxyPolicy.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.federation.policies.amrmproxy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.nio.ByteBuffer;
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.Random;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.records.EnhancedHeadroom;
import org.apache.hadoop.yarn.api.records.NMToken;
import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.federation.policies.BaseFederationPoliciesTest;
import org.apache.hadoop.yarn.server.federation.policies.FederationPolicyInitializationContext;
import org.apache.hadoop.yarn.server.federation.policies.dao.WeightedPolicyInfo;
import org.apache.hadoop.yarn.server.federation.policies.exceptions.FederationPolicyInitializationException;
import org.apache.hadoop.yarn.server.federation.resolver.DefaultSubClusterResolverImpl;
import org.apache.hadoop.yarn.server.federation.resolver.SubClusterResolver;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterId;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterIdInfo;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterInfo;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterPolicyConfiguration;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterState;
import org.apache.hadoop.yarn.server.federation.utils.FederationPoliciesTestUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple test class for the {@link LocalityMulticastAMRMProxyPolicy}.
*/
public class TestLocalityMulticastAMRMProxyPolicy
extends BaseFederationPoliciesTest {
public static final Logger LOG =
LoggerFactory.getLogger(TestLocalityMulticastAMRMProxyPolicy.class);
@BeforeEach
public void setUp() throws Exception {
setPolicy(new TestableLocalityMulticastAMRMProxyPolicy());
setPolicyInfo(new WeightedPolicyInfo());
Map<SubClusterIdInfo, Float> routerWeights = new HashMap<>();
Map<SubClusterIdInfo, Float> amrmWeights = new HashMap<>();
// Six sub-clusters with one inactive and one disabled
for (int i = 0; i < 6; i++) {
SubClusterIdInfo sc = new SubClusterIdInfo("subcluster" + i);
// sub-cluster 3 is not active
if (i != 3) {
SubClusterInfo sci = SubClusterInfo.newInstance(
sc.toId(), "dns1:80", "dns1:81", "dns1:82", "dns1:83", SubClusterState.SC_RUNNING,
System.currentTimeMillis(), "something");
getActiveSubclusters().put(sc.toId(), sci);
}
float weight = 1 / 10f;
routerWeights.put(sc, weight);
amrmWeights.put(sc, weight);
// sub-cluster 4 is "disabled" in the weights
if (i == 4) {
routerWeights.put(sc, 0f);
amrmWeights.put(sc, 0f);
}
}
getPolicyInfo().setRouterPolicyWeights(routerWeights);
getPolicyInfo().setAMRMPolicyWeights(amrmWeights);
getPolicyInfo().setHeadroomAlpha(0.5f);
setHomeSubCluster(SubClusterId.newInstance("homesubcluster"));
}
@Test
public void testReinitilialize() throws YarnException {
initializePolicy();
}
private void initializePolicy() throws YarnException {
initializePolicy(new YarnConfiguration());
}
private void initializePolicy(Configuration conf) throws YarnException {
setFederationPolicyContext(new FederationPolicyInitializationContext());
SubClusterResolver resolver = FederationPoliciesTestUtil.initResolver();
getFederationPolicyContext().setFederationSubclusterResolver(resolver);
ByteBuffer buf = getPolicyInfo().toByteBuffer();
getFederationPolicyContext().setSubClusterPolicyConfiguration(
SubClusterPolicyConfiguration.newInstance("queue1",
getPolicy().getClass().getCanonicalName(), buf));
getFederationPolicyContext().setHomeSubcluster(getHomeSubCluster());
FederationPoliciesTestUtil.initializePolicyContext(
getFederationPolicyContext(), getPolicy(), getPolicyInfo(),
getActiveSubclusters(), conf);
}
@Test
public void testNullWeights() throws Exception {
assertThrows(FederationPolicyInitializationException.class, () -> {
getPolicyInfo().setAMRMPolicyWeights(null);
initializePolicy();
fail();
});
}
@Test
public void testEmptyWeights() throws Exception {
assertThrows(FederationPolicyInitializationException.class, () -> {
getPolicyInfo()
.setAMRMPolicyWeights(new HashMap<SubClusterIdInfo, Float>());
initializePolicy();
fail();
});
}
@Test
public void testSplitBasedOnHeadroom() throws Exception {
// Tests how the headroom info are used to split based on the capacity
// each RM claims to give us.
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(1.0f);
initializePolicy();
List<ResourceRequest> resourceRequests = createSimpleRequest();
prepPolicyWithHeadroom(true);
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy()).splitResourceRequests(
resourceRequests, new HashSet<SubClusterId>());
// pretty print requests
LOG.info("Initial headroom");
prettyPrintRequests(response);
validateSplit(response, resourceRequests);
/*
* based on headroom, we expect 75 containers to got to subcluster0 (60) and
* subcluster2 (15) according to the advertised headroom (40 and 10), no
* containers for sublcuster1 as it advertise zero headroom, and 25 to
* subcluster5 which has unknown headroom, and so it gets 1/4th of the load
*/
checkExpectedAllocation(response, "subcluster0", 1, 60);
checkExpectedAllocation(response, "subcluster1", 1, -1);
checkExpectedAllocation(response, "subcluster2", 1, 15);
checkExpectedAllocation(response, "subcluster5", 1, 25);
checkTotalContainerAllocation(response, 100);
// notify a change in headroom and try again
AllocateResponse ar = getAllocateResponseWithTargetHeadroom(40);
((FederationAMRMProxyPolicy) getPolicy())
.notifyOfResponse(SubClusterId.newInstance("subcluster2"), ar);
response = ((FederationAMRMProxyPolicy) getPolicy())
.splitResourceRequests(resourceRequests, new HashSet<SubClusterId>());
LOG.info("After headroom update");
prettyPrintRequests(response);
validateSplit(response, resourceRequests);
/*
* we simulated a change in headroom for subcluster2, which will now have
* the same headroom of subcluster0, so each 37.5, note that the odd one
* will be assigned to either one of the two subclusters
*/
checkExpectedAllocation(response, "subcluster0", 1, 37);
checkExpectedAllocation(response, "subcluster1", 1, -1);
checkExpectedAllocation(response, "subcluster2", 1, 37);
checkExpectedAllocation(response, "subcluster5", 1, 25);
checkTotalContainerAllocation(response, 100);
}
@Test
@Timeout(value = 16)
public void testStressPolicy() throws Exception {
// Tests how the headroom info are used to split based on the capacity
// each RM claims to give us.
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(1.0f);
initializePolicy();
addHomeSubClusterAsActive();
int numRR = 1000;
List<ResourceRequest> resourceRequests = createLargeRandomList(numRR);
prepPolicyWithHeadroom(true);
int numIterations = 1000;
long tstart = System.currentTimeMillis();
for (int i = 0; i < numIterations; i++) {
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy()).splitResourceRequests(
resourceRequests, new HashSet<SubClusterId>());
validateSplit(response, resourceRequests);
}
long tend = System.currentTimeMillis();
LOG.info("Performed " + numIterations + " policy invocations (and "
+ "validations) in " + (tend - tstart) + "ms");
}
@Test
public void testFWDAllZeroANY() throws Exception {
// Tests how the headroom info are used to split based on the capacity
// each RM claims to give us.
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(0.5f);
initializePolicy();
List<ResourceRequest> resourceRequests = createZeroSizedANYRequest();
// this receives responses from sc0,sc1,sc2
prepPolicyWithHeadroom(true);
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy()).splitResourceRequests(
resourceRequests, new HashSet<SubClusterId>());
// we expect all three to appear for a zero-sized ANY
// pretty print requests
prettyPrintRequests(response);
validateSplit(response, resourceRequests);
// we expect the zero size request to be sent to the first 3 rm (due to
// the fact that we received responses only from these 3 sublcusters)
checkExpectedAllocation(response, "subcluster0", 1, 0);
checkExpectedAllocation(response, "subcluster1", 1, 0);
checkExpectedAllocation(response, "subcluster2", 1, 0);
checkExpectedAllocation(response, "subcluster3", -1, -1);
checkExpectedAllocation(response, "subcluster4", -1, -1);
checkExpectedAllocation(response, "subcluster5", -1, -1);
checkTotalContainerAllocation(response, 0);
}
@Test
public void testSplitBasedOnHeadroomAndWeights() throws Exception {
// Tests how the headroom info are used to split based on the capacity
// each RM claims to give us.
// Configure policy to be 50% headroom based and 50% weight based
getPolicyInfo().setHeadroomAlpha(0.5f);
initializePolicy();
List<ResourceRequest> resourceRequests = createSimpleRequest();
prepPolicyWithHeadroom(true);
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy()).splitResourceRequests(
resourceRequests, new HashSet<SubClusterId>());
// pretty print requests
prettyPrintRequests(response);
validateSplit(response, resourceRequests);
// in this case the headroom allocates 50 containers, while weights allocate
// the rest. due to weights we have 12.5 containers for each
// sublcuster, the rest is due to headroom.
checkExpectedAllocation(response, "subcluster0", 1, 42); // 30 + 12.5
checkExpectedAllocation(response, "subcluster1", 1, 12); // 0 + 12.5
checkExpectedAllocation(response, "subcluster2", 1, 20); // 7.5 + 12.5
checkExpectedAllocation(response, "subcluster3", -1, -1);
checkExpectedAllocation(response, "subcluster4", -1, -1);
checkExpectedAllocation(response, "subcluster5", 1, 25); // 12.5 + 12.5
checkTotalContainerAllocation(response, 100);
}
private void prepPolicyWithHeadroom(boolean setSubCluster0)
throws YarnException {
AllocateResponse ar = getAllocateResponseWithTargetHeadroom(40);
if (setSubCluster0) {
((FederationAMRMProxyPolicy) getPolicy())
.notifyOfResponse(SubClusterId.newInstance("subcluster0"), ar);
}
ar = getAllocateResponseWithTargetHeadroom(0);
((FederationAMRMProxyPolicy) getPolicy())
.notifyOfResponse(SubClusterId.newInstance("subcluster1"), ar);
ar = getAllocateResponseWithTargetHeadroom(10);
((FederationAMRMProxyPolicy) getPolicy())
.notifyOfResponse(SubClusterId.newInstance("subcluster2"), ar);
}
private AllocateResponse getAllocateResponseWithTargetHeadroom(
int numContainers) {
return AllocateResponse.newInstance(0, null, null,
Collections.<NodeReport> emptyList(),
Resource.newInstance(numContainers * 1024, numContainers), null, 10,
null, Collections.<NMToken> emptyList());
}
/**
* modify default initialization to include a "homesubcluster" which we will
* use as the default for when nodes or racks are unknown.
*/
private void addHomeSubClusterAsActive() {
SubClusterId homeSubCluster = getHomeSubCluster();
SubClusterInfo sci = SubClusterInfo.newInstance(
homeSubCluster, "dns1:80", "dns1:81", "dns1:82", "dns1:83", SubClusterState.SC_RUNNING,
System.currentTimeMillis(), "something");
getActiveSubclusters().put(homeSubCluster, sci);
SubClusterIdInfo sc = new SubClusterIdInfo(homeSubCluster.getId());
getPolicyInfo().getRouterPolicyWeights().put(sc, 0.1f);
getPolicyInfo().getAMRMPolicyWeights().put(sc, 0.1f);
}
@Test
public void testSplitAllocateRequest() throws Exception {
// Test a complex List<ResourceRequest> is split correctly
initializePolicy();
addHomeSubClusterAsActive();
FederationPoliciesTestUtil.initializePolicyContext(
getFederationPolicyContext(), getPolicy(), getPolicyInfo(),
getActiveSubclusters(), new Configuration());
List<ResourceRequest> resourceRequests = createComplexRequest();
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy()).splitResourceRequests(
resourceRequests, new HashSet<SubClusterId>());
validateSplit(response, resourceRequests);
prettyPrintRequests(response);
// we expect 7 entries for home subcluster (2 for request-id 4, 3 for
// request-id 5, and a part of the broadcast of request-id 2
checkExpectedAllocation(response, getHomeSubCluster().getId(), 7, 29);
// for subcluster0 we expect 10 entries, 3 from request-id 0, and 3 from
// request-id 3, 3 entries from request-id 5, as well as part of the
// request-id 2 broadast
checkExpectedAllocation(response, "subcluster0", 10, 32);
// we expect 5 entries for subcluster1 (4 from request-id 1, and part
// of the broadcast of request-id 2
checkExpectedAllocation(response, "subcluster1", 5, 26);
// sub-cluster 2 should contain 3 entries from request-id 1 and 1 from the
// broadcast of request-id 2, and no request-id 0
checkExpectedAllocation(response, "subcluster2", 4, 23);
// subcluster id 3, 4 should not appear (due to weights or active/inactive)
checkExpectedAllocation(response, "subcluster3", -1, -1);
checkExpectedAllocation(response, "subcluster4", -1, -1);
// subcluster5 should get only part of the request-id 2 broadcast
checkExpectedAllocation(response, "subcluster5", 1, 20);
// Check the total number of container asks in all RR
checkTotalContainerAllocation(response, 130);
// check that the allocations that show up are what expected
for (ResourceRequest rr : response.get(getHomeSubCluster())) {
assertTrue(rr.getAllocationRequestId() == 2L || rr.getAllocationRequestId() == 4L
|| rr.getAllocationRequestId() == 5L);
}
List<ResourceRequest> rrs =
response.get(SubClusterId.newInstance("subcluster0"));
for (ResourceRequest rr : rrs) {
assertTrue(rr.getAllocationRequestId() != 1L);
assertTrue(rr.getAllocationRequestId() != 4L);
}
for (ResourceRequest rr : response
.get(SubClusterId.newInstance("subcluster1"))) {
assertTrue(rr.getAllocationRequestId() == 1L
|| rr.getAllocationRequestId() == 2L);
}
for (ResourceRequest rr : response
.get(SubClusterId.newInstance("subcluster2"))) {
assertTrue(rr.getAllocationRequestId() == 1L
|| rr.getAllocationRequestId() == 2L);
}
for (ResourceRequest rr : response
.get(SubClusterId.newInstance("subcluster5"))) {
assertTrue(rr.getAllocationRequestId() == 2);
assertTrue(rr.getRelaxLocality());
}
}
// check that the number of containers in the first ResourceRequest in
// response for this sub-cluster matches expectations. -1 indicate the
// response should be null
private void checkExpectedAllocation(
Map<SubClusterId, List<ResourceRequest>> response, String subCluster,
long totResourceRequests, long minimumTotalContainers) {
if (minimumTotalContainers == -1) {
assertNull(response.get(SubClusterId.newInstance(subCluster)));
} else {
SubClusterId sc = SubClusterId.newInstance(subCluster);
assertEquals(totResourceRequests, response.get(sc).size());
long actualContCount = 0;
for (ResourceRequest rr : response.get(sc)) {
actualContCount += rr.getNumContainers();
}
assertTrue(minimumTotalContainers <= actualContCount,
"Actual count " + actualContCount + " should be at least "
+ minimumTotalContainers);
}
}
private void checkTotalContainerAllocation(
Map<SubClusterId, List<ResourceRequest>> response, long totalContainers) {
long actualContCount = 0;
for (Map.Entry<SubClusterId, List<ResourceRequest>> entry : response
.entrySet()) {
for (ResourceRequest rr : entry.getValue()) {
actualContCount += rr.getNumContainers();
}
}
assertEquals(totalContainers, actualContCount);
}
private void validateSplit(Map<SubClusterId, List<ResourceRequest>> split,
List<ResourceRequest> original) throws YarnException {
SubClusterResolver resolver =
getFederationPolicyContext().getFederationSubclusterResolver();
// Apply general validation rules
int numUsedSubclusters = split.size();
Set<Long> originalIds = new HashSet<>();
Set<Long> splitIds = new HashSet<>();
int originalContainers = 0;
for (ResourceRequest rr : original) {
originalContainers += rr.getNumContainers();
originalIds.add(rr.getAllocationRequestId());
}
int splitContainers = 0;
for (Map.Entry<SubClusterId, List<ResourceRequest>> rrs : split
.entrySet()) {
for (ResourceRequest rr : rrs.getValue()) {
splitContainers += rr.getNumContainers();
splitIds.add(rr.getAllocationRequestId());
// check node-local asks are sent to right RM (only)
SubClusterId fid = null;
try {
fid = resolver.getSubClusterForNode(rr.getResourceName());
} catch (YarnException e) {
// ignore code will handle
}
if (!rrs.getKey().equals(getHomeSubCluster()) && fid != null
&& !fid.equals(rrs.getKey())) {
fail("A node-local (or resolvable rack-local) RR should not "
+ "be send to an RM other than what it resolves to.");
}
}
}
// check we are not inventing Allocation Ids
assertEquals(originalIds, splitIds);
// check we are not exceedingly replicating the container asks among
// RMs (a little is allowed due to rounding of fractional splits)
assertTrue(originalContainers + numUsedSubclusters >= splitContainers,
" Containers requested (" + splitContainers + ") should "
+ "not exceed the original count of containers ("
+ originalContainers + ") by more than the number of subclusters ("
+ numUsedSubclusters + ")");
// Test target Ids
for (SubClusterId targetId : split.keySet()) {
assertTrue(getActiveSubclusters().containsKey(targetId),
"Target subcluster " + targetId + " should be in the active set");
assertTrue(getPolicyInfo().getRouterPolicyWeights()
.get(new SubClusterIdInfo(targetId)) > 0,
"Target subclusters (" + targetId + ") should have weight >0 in the policy ");
}
}
private void prettyPrintRequests(
Map<SubClusterId, List<ResourceRequest>> response) {
for (Map.Entry<SubClusterId, List<ResourceRequest>> entry : response
.entrySet()) {
String str = "";
for (ResourceRequest rr : entry.getValue()) {
str += " [id:" + rr.getAllocationRequestId() + " loc:"
+ rr.getResourceName() + " numCont:" + rr.getNumContainers()
+ "], ";
}
LOG.info(entry.getKey() + " --> " + str);
}
}
private List<ResourceRequest> createLargeRandomList(int numRR)
throws Exception {
List<ResourceRequest> out = new ArrayList<>();
Random rand = new Random(1);
DefaultSubClusterResolverImpl resolver =
(DefaultSubClusterResolverImpl) getFederationPolicyContext()
.getFederationSubclusterResolver();
List<String> nodes =
new ArrayList<>(resolver.getNodeToSubCluster().keySet());
for (int i = 0; i < numRR; i++) {
String nodeName = nodes.get(rand.nextInt(nodes.size()));
long allocationId = (long) rand.nextInt(20);
// create a single container request in sc0
out.add(FederationPoliciesTestUtil.createResourceRequest(allocationId,
nodeName, 1024, 1, 1, rand.nextInt(100), null, rand.nextBoolean()));
}
return out;
}
private List<ResourceRequest> createSimpleRequest() throws Exception {
List<ResourceRequest> out = new ArrayList<>();
// create a single container request in sc0
out.add(FederationPoliciesTestUtil.createResourceRequest(0L,
ResourceRequest.ANY, 1024, 1, 1, 100, null, true));
return out;
}
private List<ResourceRequest> createZeroSizedANYRequest() throws Exception {
List<ResourceRequest> out = new ArrayList<>();
// create a single container request in sc0
out.add(FederationPoliciesTestUtil.createResourceRequest(0L,
ResourceRequest.ANY, 1024, 1, 1, 0, null, true));
return out;
}
private List<ResourceRequest> createComplexRequest() throws Exception {
List<ResourceRequest> out = new ArrayList<>();
// create a single container request in sc0
out.add(FederationPoliciesTestUtil.createResourceRequest(0L,
"subcluster0-rack0-host0", 1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(0L,
"subcluster0-rack0", 1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(0L,
ResourceRequest.ANY, 1024, 1, 1, 1, null, false));
// create a single container request with 3 alternative hosts across sc1,sc2
// where we want 2 containers in sc1 and 1 in sc2
out.add(FederationPoliciesTestUtil.createResourceRequest(1L,
"subcluster1-rack1-host1", 1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(1L,
"subcluster1-rack1-host2", 1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(1L,
"subcluster2-rack3-host3", 1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(1L,
"subcluster1-rack1", 1024, 1, 1, 2, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(1L,
"subcluster2-rack3", 1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(1L,
ResourceRequest.ANY, 1024, 1, 1, 3, null, false));
// create a non-local ANY request that can span anything
out.add(FederationPoliciesTestUtil.createResourceRequest(2L,
ResourceRequest.ANY, 1024, 1, 1, 100, null, true));
// create a single container request in sc0 with relaxed locality
out.add(FederationPoliciesTestUtil.createResourceRequest(3L,
"subcluster0-rack0-host0", 1024, 1, 1, 1, null, true));
out.add(FederationPoliciesTestUtil.createResourceRequest(3L,
"subcluster0-rack0", 1024, 1, 1, 1, null, true));
out.add(FederationPoliciesTestUtil.createResourceRequest(3L,
ResourceRequest.ANY, 1024, 1, 1, 1, null, true));
// create a request of an unknown node/rack and expect this to show up
// in homesubcluster
out.add(FederationPoliciesTestUtil.createResourceRequest(4L, "unknownNode",
1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(4L, "unknownRack",
1024, 1, 1, 1, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(4L,
ResourceRequest.ANY, 1024, 1, 1, 1, null, false));
// create a request of two hosts, an unknown node and a known node, both in
// a known rack, and expect the unknown node to show up in homesubcluster
out.add(FederationPoliciesTestUtil.createResourceRequest(5L,
"subcluster0-rack0-host0", 1024, 1, 1, 2, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(5L,
"subcluster0-rack0", 1024, 1, 1, 2, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(5L, "node4", 1024,
1, 1, 2, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(5L, "rack2", 1024,
1, 1, 2, null, false));
out.add(FederationPoliciesTestUtil.createResourceRequest(5L,
ResourceRequest.ANY, 1024, 1, 1, 4, null, false));
return out;
}
public String printList(ArrayList<Integer> list) {
StringBuilder sb = new StringBuilder();
for (Integer entry : list) {
sb.append(entry + ", ");
}
return sb.toString();
}
@Test
public void testIntegerAssignment() throws YarnException {
float[] weights =
new float[] {0, 0.1f, 0.2f, 0.2f, -0.1f, 0.1f, 0.2f, 0.1f, 0.1f};
int[] expectedMin = new int[] {0, 1, 3, 3, 0, 1, 3, 1, 1};
ArrayList<Float> weightsList = new ArrayList<>();
for (float weight : weights) {
weightsList.add(weight);
}
LocalityMulticastAMRMProxyPolicy policy =
(LocalityMulticastAMRMProxyPolicy) getPolicy();
for (int i = 0; i < 500000; i++) {
ArrayList<Integer> allocations =
policy.computeIntegerAssignment(19, weightsList);
int sum = 0;
for (int j = 0; j < weights.length; j++) {
sum += allocations.get(j);
if (allocations.get(j) < expectedMin[j]) {
fail(allocations.get(j) + " at index " + j
+ " should be at least " + expectedMin[j] + ". Allocation array: "
+ printList(allocations));
}
}
assertEquals(19, sum,
"Expect sum to be 19 in array: " + printList(allocations));
}
}
@Test
public void testCancelWithLocalizedResource() throws YarnException {
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(1.0f);
initializePolicy();
List<ResourceRequest> resourceRequests = new ArrayList<>();
// Initialize the headroom map
prepPolicyWithHeadroom(true);
// Cancel at ANY level only
resourceRequests.add(FederationPoliciesTestUtil.createResourceRequest(0L,
"subcluster0-rack0-host0", 1024, 1, 1, 1, null, false));
resourceRequests.add(FederationPoliciesTestUtil.createResourceRequest(0L,
"subcluster0-rack0", 1024, 1, 1, 1, null, false));
resourceRequests.add(FederationPoliciesTestUtil.createResourceRequest(0L,
ResourceRequest.ANY, 1024, 1, 1, 0, null, false));
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy()).splitResourceRequests(
resourceRequests, new HashSet<SubClusterId>());
checkExpectedAllocation(response, "subcluster0", 3, 1);
checkExpectedAllocation(response, "subcluster1", 1, 0);
checkExpectedAllocation(response, "subcluster2", 1, 0);
checkExpectedAllocation(response, "subcluster3", -1, -1);
checkExpectedAllocation(response, "subcluster4", -1, -1);
checkExpectedAllocation(response, "subcluster5", -1, -1);
resourceRequests.clear();
// Cancel at node level only
resourceRequests.add(FederationPoliciesTestUtil.createResourceRequest(0L,
"subcluster0-rack0-host0", 1024, 1, 1, 0, null, false));
resourceRequests.add(FederationPoliciesTestUtil.createResourceRequest(0L,
"subcluster0-rack0", 1024, 1, 1, 0, null, false));
resourceRequests.add(FederationPoliciesTestUtil.createResourceRequest(0L,
ResourceRequest.ANY, 1024, 1, 1, 100, null, false));
response = ((FederationAMRMProxyPolicy) getPolicy())
.splitResourceRequests(resourceRequests, new HashSet<SubClusterId>());
/*
* Since node request is a cancel, it should not be considered associated
* with localized requests. Based on headroom, we expect 75 containers to
* got to subcluster0 (60) and subcluster2 (15) according to the advertised
* headroom (40 and 10), no containers for sublcuster1 as it advertise zero
* headroom, and 25 to subcluster5 which has unknown headroom, and so it
* gets 1/4th of the load
*/
checkExpectedAllocation(response, "subcluster0", 3, 60);
checkExpectedAllocation(response, "subcluster1", 1, -1);
checkExpectedAllocation(response, "subcluster2", 1, 15);
checkExpectedAllocation(response, "subcluster5", 1, 25);
checkTotalContainerAllocation(response, 100);
}
@Test
public void testSubClusterExpiry() throws Exception {
// Tests how the headroom info are used to split based on the capacity
// each RM claims to give us.
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(1.0f);
YarnConfiguration conf = new YarnConfiguration();
// Set expiry to 500ms
conf.setLong(YarnConfiguration.FEDERATION_AMRMPROXY_SUBCLUSTER_TIMEOUT,
500);
initializePolicy(conf);
List<ResourceRequest> resourceRequests = createSimpleRequest();
prepPolicyWithHeadroom(true);
// For first time, no sub-cluster expired
Set<SubClusterId> expiredSCList = new HashSet<>();
Map<SubClusterId, List<ResourceRequest>> response =
((FederationAMRMProxyPolicy) getPolicy())
.splitResourceRequests(resourceRequests, expiredSCList);
// pretty print requests
prettyPrintRequests(response);
validateSplit(response, resourceRequests);
/*
* based on headroom, we expect 75 containers to got to subcluster0 (60) and
* subcluster2 (15) according to the advertised headroom (40 and 10), no
* containers for sublcuster1 as it advertise zero headroom, and 25 to
* subcluster5 which has unknown headroom, and so it gets 1/4th of the load
*/
checkExpectedAllocation(response, "subcluster0", 1, 60);
checkExpectedAllocation(response, "subcluster1", 1, -1);
checkExpectedAllocation(response, "subcluster2", 1, 15);
checkExpectedAllocation(response, "subcluster5", 1, 25);
checkTotalContainerAllocation(response, 100);
Thread.sleep(800);
// For the second time, sc0 and sc5 expired
expiredSCList.add(SubClusterId.newInstance("subcluster0"));
expiredSCList.add(SubClusterId.newInstance("subcluster5"));
response = ((FederationAMRMProxyPolicy) getPolicy())
.splitResourceRequests(resourceRequests, expiredSCList);
// pretty print requests
prettyPrintRequests(response);
validateSplit(response, resourceRequests);
checkExpectedAllocation(response, "subcluster0", 1, -1);
checkExpectedAllocation(response, "subcluster1", 1, -1);
checkExpectedAllocation(response, "subcluster2", 1, 100);
checkExpectedAllocation(response, "subcluster5", 1, -1);
checkTotalContainerAllocation(response, 100);
}
/**
* A testable version of LocalityMulticastAMRMProxyPolicy that
* deterministically falls back to home sub-cluster for unresolved requests.
*/
private class TestableLocalityMulticastAMRMProxyPolicy
extends LocalityMulticastAMRMProxyPolicy {
@Override
protected SubClusterId getSubClusterForUnResolvedRequest(
AllocationBookkeeper bookkeeper, long allocationId) {
SubClusterId originalResult =
super.getSubClusterForUnResolvedRequest(bookkeeper, allocationId);
Map<SubClusterId, SubClusterInfo> activeClusters = null;
try {
activeClusters = getActiveSubclusters();
} catch (YarnException e) {
throw new RuntimeException(e);
}
// The randomly selected sub-cluster should at least be active
assertTrue(activeClusters.containsKey(originalResult));
// Always use home sub-cluster so that unit test is deterministic
return getHomeSubCluster();
}
}
/**
* Test the rerouting behavior when some subclusters are loaded. Make sure
* that the AMRMProxy rerouting decisions attempt to redirect requests
* to the least loaded subcluster when load thresholds are exceeded
*/
@Test
public void testLoadBasedSubClusterReroute() throws YarnException {
int pendingThreshold = 1000;
LocalityMulticastAMRMProxyPolicy policy = (LocalityMulticastAMRMProxyPolicy) getPolicy();
initializePolicy();
SubClusterId sc0 = SubClusterId.newInstance("0");
SubClusterId sc1 = SubClusterId.newInstance("1");
SubClusterId sc2 = SubClusterId.newInstance("2");
SubClusterId sc3 = SubClusterId.newInstance("3");
SubClusterId sc4 = SubClusterId.newInstance("4");
Set<SubClusterId> scList = new HashSet<>();
scList.add(sc0);
scList.add(sc1);
scList.add(sc2);
scList.add(sc3);
scList.add(sc4);
// This cluster is the most overloaded - 4 times the threshold.
policy.notifyOfResponse(sc0,
getAllocateResponseWithEnhancedHeadroom(4 * pendingThreshold, 0));
// This cluster is the most overloaded - 4 times the threshold.
policy.notifyOfResponse(sc1,
getAllocateResponseWithEnhancedHeadroom(4 * pendingThreshold, 0));
// This cluster is 2 times the threshold, but not the most loaded.
policy.notifyOfResponse(sc2,
getAllocateResponseWithEnhancedHeadroom(2 * pendingThreshold, 0));
// This cluster is at the threshold, but not the most loaded.
policy.notifyOfResponse(sc3,
getAllocateResponseWithEnhancedHeadroom(pendingThreshold, 0));
// This cluster has zero pending.
policy.notifyOfResponse(sc4, getAllocateResponseWithEnhancedHeadroom(0, 0));
// sc2, sc3 and sc4 should just return the original subcluster.
assertEquals(
policy.routeNodeRequestIfNeeded(sc2, pendingThreshold, scList), sc2);
assertEquals(
policy.routeNodeRequestIfNeeded(sc3, pendingThreshold, scList), sc3);
assertEquals(
policy.routeNodeRequestIfNeeded(sc4, pendingThreshold, scList), sc4);
// sc0 and sc1 must select from sc0/sc1/sc2/sc3/sc4 according to weights
// 1/4, 1/4, 1/2, 1, 2. Let's run tons of random of samples, and verify that
// the proportion approximately holds.
Map<SubClusterId, Integer> counts = new HashMap<>();
counts.put(sc0, 0);
counts.put(sc1, 0);
counts.put(sc2, 0);
counts.put(sc3, 0);
counts.put(sc4, 0);
int n = 100000;
for (int i = 0; i < n; i++) {
SubClusterId selectedId = policy.routeNodeRequestIfNeeded(sc0, pendingThreshold, scList);
counts.put(selectedId, counts.get(selectedId) + 1);
selectedId = policy.routeNodeRequestIfNeeded(sc1, pendingThreshold, scList);
counts.put(selectedId, counts.get(selectedId) + 1);
// Also try a new SCId that's not active and enabled. Should be rerouted
// to sc0-4 with the same distribution as above
selectedId = policy.routeNodeRequestIfNeeded(SubClusterId.newInstance("10"),
pendingThreshold, scList);
counts.put(selectedId, counts.get(selectedId) + 1);
}
// The probability should be 1/16, 1/16, 1/8, 1/4, 1/2R
assertEquals((double) counts.get(sc0) / n / 3, 1 / 16.0, 0.01);
assertEquals((double) counts.get(sc1) / n / 3, 1 / 16.0, 0.01);
assertEquals((double) counts.get(sc2) / n / 3, 1 / 8.0, 0.01);
assertEquals((double) counts.get(sc3) / n / 3, 1 / 4.0, 0.01);
assertEquals((double) counts.get(sc4) / n / 3, 1 / 2.0, 0.01);
// Everything should be routed to these five active and enabled SCs
assertEquals(5, counts.size());
}
private AllocateResponse getAllocateResponseWithEnhancedHeadroom(int pending, int activeCores) {
return AllocateResponse.newInstance(0, null, null,
Collections.emptyList(), Resource.newInstance(0, 0), null, 10, null,
Collections.emptyList(), null, null, null,
EnhancedHeadroom.newInstance(pending, activeCores));
}
} |
googleads/google-ads-java | 37,558 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/AssetSetAsset.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/resources/asset_set_asset.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.resources;
/**
* <pre>
* AssetSetAsset is the link between an asset and an asset set.
* Adding an AssetSetAsset links an asset with an asset set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.resources.AssetSetAsset}
*/
public final class AssetSetAsset extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.resources.AssetSetAsset)
AssetSetAssetOrBuilder {
private static final long serialVersionUID = 0L;
// Use AssetSetAsset.newBuilder() to construct.
private AssetSetAsset(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AssetSetAsset() {
resourceName_ = "";
assetSet_ = "";
asset_ = "";
status_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new AssetSetAsset();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v19_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v19_resources_AssetSetAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.resources.AssetSetAsset.class, com.google.ads.googleads.v19.resources.AssetSetAsset.Builder.class);
}
public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object resourceName_ = "";
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ASSET_SET_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object assetSet_ = "";
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The assetSet.
*/
@java.lang.Override
public java.lang.String getAssetSet() {
java.lang.Object ref = assetSet_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
assetSet_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for assetSet.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getAssetSetBytes() {
java.lang.Object ref = assetSet_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
assetSet_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ASSET_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object asset_ = "";
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The asset.
*/
@java.lang.Override
public java.lang.String getAsset() {
java.lang.Object ref = asset_;
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();
asset_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for asset.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getAssetBytes() {
java.lang.Object ref = asset_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
asset_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int STATUS_FIELD_NUMBER = 4;
private int status_ = 0;
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
@java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus getStatus() {
com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus result = com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.forNumber(status_);
return result == null ? com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, assetSet_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(asset_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, asset_);
}
if (status_ != com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNSPECIFIED.getNumber()) {
output.writeEnum(4, status_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, assetSet_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(asset_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, asset_);
}
if (status_ != com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(4, status_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.resources.AssetSetAsset)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.resources.AssetSetAsset other = (com.google.ads.googleads.v19.resources.AssetSetAsset) obj;
if (!getResourceName()
.equals(other.getResourceName())) return false;
if (!getAssetSet()
.equals(other.getAssetSet())) return false;
if (!getAsset()
.equals(other.getAsset())) return false;
if (status_ != other.status_) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
hash = (37 * hash) + ASSET_SET_FIELD_NUMBER;
hash = (53 * hash) + getAssetSet().hashCode();
hash = (37 * hash) + ASSET_FIELD_NUMBER;
hash = (53 * hash) + getAsset().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v19.resources.AssetSetAsset 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>
* AssetSetAsset is the link between an asset and an asset set.
* Adding an AssetSetAsset links an asset with an asset set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.resources.AssetSetAsset}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.resources.AssetSetAsset)
com.google.ads.googleads.v19.resources.AssetSetAssetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v19_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v19_resources_AssetSetAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.resources.AssetSetAsset.class, com.google.ads.googleads.v19.resources.AssetSetAsset.Builder.class);
}
// Construct using com.google.ads.googleads.v19.resources.AssetSetAsset.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
resourceName_ = "";
assetSet_ = "";
asset_ = "";
status_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v19_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.AssetSetAsset getDefaultInstanceForType() {
return com.google.ads.googleads.v19.resources.AssetSetAsset.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.AssetSetAsset build() {
com.google.ads.googleads.v19.resources.AssetSetAsset result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.AssetSetAsset buildPartial() {
com.google.ads.googleads.v19.resources.AssetSetAsset result = new com.google.ads.googleads.v19.resources.AssetSetAsset(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.resources.AssetSetAsset result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.resourceName_ = resourceName_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.assetSet_ = assetSet_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.asset_ = asset_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.status_ = status_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v19.resources.AssetSetAsset) {
return mergeFrom((com.google.ads.googleads.v19.resources.AssetSetAsset)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.resources.AssetSetAsset other) {
if (other == com.google.ads.googleads.v19.resources.AssetSetAsset.getDefaultInstance()) return this;
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getAssetSet().isEmpty()) {
assetSet_ = other.assetSet_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getAsset().isEmpty()) {
asset_ = other.asset_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
resourceName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
assetSet_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26: {
asset_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 32: {
status_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 32
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object resourceName_ = "";
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object assetSet_ = "";
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The assetSet.
*/
public java.lang.String getAssetSet() {
java.lang.Object ref = assetSet_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
assetSet_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for assetSet.
*/
public com.google.protobuf.ByteString
getAssetSetBytes() {
java.lang.Object ref = assetSet_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
assetSet_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The assetSet to set.
* @return This builder for chaining.
*/
public Builder setAssetSet(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
assetSet_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearAssetSet() {
assetSet_ = getDefaultInstance().getAssetSet();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for assetSet to set.
* @return This builder for chaining.
*/
public Builder setAssetSetBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
assetSet_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object asset_ = "";
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The asset.
*/
public java.lang.String getAsset() {
java.lang.Object ref = asset_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
asset_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for asset.
*/
public com.google.protobuf.ByteString
getAssetBytes() {
java.lang.Object ref = asset_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
asset_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The asset to set.
* @return This builder for chaining.
*/
public Builder setAsset(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
asset_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearAsset() {
asset_ = getDefaultInstance().getAsset();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for asset to set.
* @return This builder for chaining.
*/
public Builder setAssetBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
asset_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private int status_ = 0;
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The enum numeric value on the wire for status to set.
* @return This builder for chaining.
*/
public Builder setStatusValue(int value) {
status_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
@java.lang.Override
public com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus getStatus() {
com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus result = com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.forNumber(status_);
return result == null ? com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNRECOGNIZED : result;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The status to set.
* @return This builder for chaining.
*/
public Builder setStatus(com.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
status_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearStatus() {
bitField0_ = (bitField0_ & ~0x00000008);
status_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.resources.AssetSetAsset)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.resources.AssetSetAsset)
private static final com.google.ads.googleads.v19.resources.AssetSetAsset DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.resources.AssetSetAsset();
}
public static com.google.ads.googleads.v19.resources.AssetSetAsset getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AssetSetAsset>
PARSER = new com.google.protobuf.AbstractParser<AssetSetAsset>() {
@java.lang.Override
public AssetSetAsset 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<AssetSetAsset> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AssetSetAsset> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.resources.AssetSetAsset getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 37,558 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/AssetSetAsset.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/resources/asset_set_asset.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.resources;
/**
* <pre>
* AssetSetAsset is the link between an asset and an asset set.
* Adding an AssetSetAsset links an asset with an asset set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.resources.AssetSetAsset}
*/
public final class AssetSetAsset extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.resources.AssetSetAsset)
AssetSetAssetOrBuilder {
private static final long serialVersionUID = 0L;
// Use AssetSetAsset.newBuilder() to construct.
private AssetSetAsset(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AssetSetAsset() {
resourceName_ = "";
assetSet_ = "";
asset_ = "";
status_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new AssetSetAsset();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v20_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v20_resources_AssetSetAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.resources.AssetSetAsset.class, com.google.ads.googleads.v20.resources.AssetSetAsset.Builder.class);
}
public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object resourceName_ = "";
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ASSET_SET_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object assetSet_ = "";
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The assetSet.
*/
@java.lang.Override
public java.lang.String getAssetSet() {
java.lang.Object ref = assetSet_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
assetSet_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for assetSet.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getAssetSetBytes() {
java.lang.Object ref = assetSet_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
assetSet_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ASSET_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object asset_ = "";
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The asset.
*/
@java.lang.Override
public java.lang.String getAsset() {
java.lang.Object ref = asset_;
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();
asset_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for asset.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getAssetBytes() {
java.lang.Object ref = asset_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
asset_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int STATUS_FIELD_NUMBER = 4;
private int status_ = 0;
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
@java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus getStatus() {
com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus result = com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.forNumber(status_);
return result == null ? com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, assetSet_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(asset_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, asset_);
}
if (status_ != com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNSPECIFIED.getNumber()) {
output.writeEnum(4, status_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, assetSet_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(asset_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, asset_);
}
if (status_ != com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(4, status_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.resources.AssetSetAsset)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.resources.AssetSetAsset other = (com.google.ads.googleads.v20.resources.AssetSetAsset) obj;
if (!getResourceName()
.equals(other.getResourceName())) return false;
if (!getAssetSet()
.equals(other.getAssetSet())) return false;
if (!getAsset()
.equals(other.getAsset())) return false;
if (status_ != other.status_) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
hash = (37 * hash) + ASSET_SET_FIELD_NUMBER;
hash = (53 * hash) + getAssetSet().hashCode();
hash = (37 * hash) + ASSET_FIELD_NUMBER;
hash = (53 * hash) + getAsset().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v20.resources.AssetSetAsset 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>
* AssetSetAsset is the link between an asset and an asset set.
* Adding an AssetSetAsset links an asset with an asset set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.resources.AssetSetAsset}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.resources.AssetSetAsset)
com.google.ads.googleads.v20.resources.AssetSetAssetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v20_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v20_resources_AssetSetAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.resources.AssetSetAsset.class, com.google.ads.googleads.v20.resources.AssetSetAsset.Builder.class);
}
// Construct using com.google.ads.googleads.v20.resources.AssetSetAsset.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
resourceName_ = "";
assetSet_ = "";
asset_ = "";
status_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v20_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.AssetSetAsset getDefaultInstanceForType() {
return com.google.ads.googleads.v20.resources.AssetSetAsset.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.AssetSetAsset build() {
com.google.ads.googleads.v20.resources.AssetSetAsset result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.AssetSetAsset buildPartial() {
com.google.ads.googleads.v20.resources.AssetSetAsset result = new com.google.ads.googleads.v20.resources.AssetSetAsset(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.resources.AssetSetAsset result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.resourceName_ = resourceName_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.assetSet_ = assetSet_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.asset_ = asset_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.status_ = status_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v20.resources.AssetSetAsset) {
return mergeFrom((com.google.ads.googleads.v20.resources.AssetSetAsset)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.resources.AssetSetAsset other) {
if (other == com.google.ads.googleads.v20.resources.AssetSetAsset.getDefaultInstance()) return this;
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getAssetSet().isEmpty()) {
assetSet_ = other.assetSet_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getAsset().isEmpty()) {
asset_ = other.asset_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
resourceName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
assetSet_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26: {
asset_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 32: {
status_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 32
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object resourceName_ = "";
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object assetSet_ = "";
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The assetSet.
*/
public java.lang.String getAssetSet() {
java.lang.Object ref = assetSet_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
assetSet_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for assetSet.
*/
public com.google.protobuf.ByteString
getAssetSetBytes() {
java.lang.Object ref = assetSet_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
assetSet_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The assetSet to set.
* @return This builder for chaining.
*/
public Builder setAssetSet(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
assetSet_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearAssetSet() {
assetSet_ = getDefaultInstance().getAssetSet();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for assetSet to set.
* @return This builder for chaining.
*/
public Builder setAssetSetBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
assetSet_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object asset_ = "";
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The asset.
*/
public java.lang.String getAsset() {
java.lang.Object ref = asset_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
asset_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for asset.
*/
public com.google.protobuf.ByteString
getAssetBytes() {
java.lang.Object ref = asset_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
asset_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The asset to set.
* @return This builder for chaining.
*/
public Builder setAsset(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
asset_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearAsset() {
asset_ = getDefaultInstance().getAsset();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for asset to set.
* @return This builder for chaining.
*/
public Builder setAssetBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
asset_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private int status_ = 0;
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The enum numeric value on the wire for status to set.
* @return This builder for chaining.
*/
public Builder setStatusValue(int value) {
status_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
@java.lang.Override
public com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus getStatus() {
com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus result = com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.forNumber(status_);
return result == null ? com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNRECOGNIZED : result;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The status to set.
* @return This builder for chaining.
*/
public Builder setStatus(com.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
status_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearStatus() {
bitField0_ = (bitField0_ & ~0x00000008);
status_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.resources.AssetSetAsset)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.resources.AssetSetAsset)
private static final com.google.ads.googleads.v20.resources.AssetSetAsset DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.resources.AssetSetAsset();
}
public static com.google.ads.googleads.v20.resources.AssetSetAsset getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AssetSetAsset>
PARSER = new com.google.protobuf.AbstractParser<AssetSetAsset>() {
@java.lang.Override
public AssetSetAsset 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<AssetSetAsset> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AssetSetAsset> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.resources.AssetSetAsset getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 37,558 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/AssetSetAsset.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/resources/asset_set_asset.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.resources;
/**
* <pre>
* AssetSetAsset is the link between an asset and an asset set.
* Adding an AssetSetAsset links an asset with an asset set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.resources.AssetSetAsset}
*/
public final class AssetSetAsset extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.AssetSetAsset)
AssetSetAssetOrBuilder {
private static final long serialVersionUID = 0L;
// Use AssetSetAsset.newBuilder() to construct.
private AssetSetAsset(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AssetSetAsset() {
resourceName_ = "";
assetSet_ = "";
asset_ = "";
status_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new AssetSetAsset();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v21_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v21_resources_AssetSetAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.resources.AssetSetAsset.class, com.google.ads.googleads.v21.resources.AssetSetAsset.Builder.class);
}
public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object resourceName_ = "";
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ASSET_SET_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object assetSet_ = "";
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The assetSet.
*/
@java.lang.Override
public java.lang.String getAssetSet() {
java.lang.Object ref = assetSet_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
assetSet_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for assetSet.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getAssetSetBytes() {
java.lang.Object ref = assetSet_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
assetSet_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ASSET_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object asset_ = "";
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The asset.
*/
@java.lang.Override
public java.lang.String getAsset() {
java.lang.Object ref = asset_;
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();
asset_ = s;
return s;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for asset.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getAssetBytes() {
java.lang.Object ref = asset_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
asset_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int STATUS_FIELD_NUMBER = 4;
private int status_ = 0;
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
@java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus getStatus() {
com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus result = com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.forNumber(status_);
return result == null ? com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, assetSet_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(asset_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, asset_);
}
if (status_ != com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNSPECIFIED.getNumber()) {
output.writeEnum(4, status_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, assetSet_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(asset_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, asset_);
}
if (status_ != com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(4, status_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.resources.AssetSetAsset)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.resources.AssetSetAsset other = (com.google.ads.googleads.v21.resources.AssetSetAsset) obj;
if (!getResourceName()
.equals(other.getResourceName())) return false;
if (!getAssetSet()
.equals(other.getAssetSet())) return false;
if (!getAsset()
.equals(other.getAsset())) return false;
if (status_ != other.status_) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
hash = (37 * hash) + ASSET_SET_FIELD_NUMBER;
hash = (53 * hash) + getAssetSet().hashCode();
hash = (37 * hash) + ASSET_FIELD_NUMBER;
hash = (53 * hash) + getAsset().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v21.resources.AssetSetAsset 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>
* AssetSetAsset is the link between an asset and an asset set.
* Adding an AssetSetAsset links an asset with an asset set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.resources.AssetSetAsset}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.AssetSetAsset)
com.google.ads.googleads.v21.resources.AssetSetAssetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v21_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v21_resources_AssetSetAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.resources.AssetSetAsset.class, com.google.ads.googleads.v21.resources.AssetSetAsset.Builder.class);
}
// Construct using com.google.ads.googleads.v21.resources.AssetSetAsset.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
resourceName_ = "";
assetSet_ = "";
asset_ = "";
status_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.resources.AssetSetAssetProto.internal_static_google_ads_googleads_v21_resources_AssetSetAsset_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.AssetSetAsset getDefaultInstanceForType() {
return com.google.ads.googleads.v21.resources.AssetSetAsset.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.AssetSetAsset build() {
com.google.ads.googleads.v21.resources.AssetSetAsset result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.AssetSetAsset buildPartial() {
com.google.ads.googleads.v21.resources.AssetSetAsset result = new com.google.ads.googleads.v21.resources.AssetSetAsset(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.resources.AssetSetAsset result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.resourceName_ = resourceName_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.assetSet_ = assetSet_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.asset_ = asset_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.status_ = status_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v21.resources.AssetSetAsset) {
return mergeFrom((com.google.ads.googleads.v21.resources.AssetSetAsset)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.resources.AssetSetAsset other) {
if (other == com.google.ads.googleads.v21.resources.AssetSetAsset.getDefaultInstance()) return this;
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getAssetSet().isEmpty()) {
assetSet_ = other.assetSet_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getAsset().isEmpty()) {
asset_ = other.asset_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
resourceName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
assetSet_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26: {
asset_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 32: {
status_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 32
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object resourceName_ = "";
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The resource name of the asset set asset.
* Asset set asset resource names have the form:
*
* `customers/{customer_id}/assetSetAssets/{asset_set_id}~{asset_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object assetSet_ = "";
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The assetSet.
*/
public java.lang.String getAssetSet() {
java.lang.Object ref = assetSet_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
assetSet_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for assetSet.
*/
public com.google.protobuf.ByteString
getAssetSetBytes() {
java.lang.Object ref = assetSet_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
assetSet_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The assetSet to set.
* @return This builder for chaining.
*/
public Builder setAssetSet(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
assetSet_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearAssetSet() {
assetSet_ = getDefaultInstance().getAssetSet();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset set which this asset set asset is linking to.
* </pre>
*
* <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for assetSet to set.
* @return This builder for chaining.
*/
public Builder setAssetSetBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
assetSet_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object asset_ = "";
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The asset.
*/
public java.lang.String getAsset() {
java.lang.Object ref = asset_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
asset_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for asset.
*/
public com.google.protobuf.ByteString
getAssetBytes() {
java.lang.Object ref = asset_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
asset_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The asset to set.
* @return This builder for chaining.
*/
public Builder setAsset(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
asset_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearAsset() {
asset_ = getDefaultInstance().getAsset();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
* <pre>
* Immutable. The asset which this asset set asset is linking to.
* </pre>
*
* <code>string asset = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for asset to set.
* @return This builder for chaining.
*/
public Builder setAssetBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
asset_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private int status_ = 0;
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
@java.lang.Override public int getStatusValue() {
return status_;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The enum numeric value on the wire for status to set.
* @return This builder for chaining.
*/
public Builder setStatusValue(int value) {
status_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
@java.lang.Override
public com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus getStatus() {
com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus result = com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.forNumber(status_);
return result == null ? com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus.UNRECOGNIZED : result;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The status to set.
* @return This builder for chaining.
*/
public Builder setStatus(com.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
status_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Output only. The status of the asset set asset. Read-only.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearStatus() {
bitField0_ = (bitField0_ & ~0x00000008);
status_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.resources.AssetSetAsset)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.AssetSetAsset)
private static final com.google.ads.googleads.v21.resources.AssetSetAsset DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.AssetSetAsset();
}
public static com.google.ads.googleads.v21.resources.AssetSetAsset getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AssetSetAsset>
PARSER = new com.google.protobuf.AbstractParser<AssetSetAsset>() {
@java.lang.Override
public AssetSetAsset 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<AssetSetAsset> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AssetSetAsset> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.AssetSetAsset getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,407 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/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/aiplatform/v1beta1/endpoint_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [EndpointService.ListEndpoints][google.cloud.aiplatform.v1beta1.EndpointService.ListEndpoints].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListEndpointsResponse}
*/
public final class ListEndpointsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.EndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListEndpointsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListEndpointsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse.Builder.class);
}
public static final int ENDPOINTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Endpoint> endpoints_;
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Endpoint> getEndpointsList() {
return endpoints_;
}
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.EndpointOrBuilder>
getEndpointsOrBuilderList() {
return endpoints_;
}
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Endpoint getEndpoints(int index) {
return endpoints_.get(index);
}
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.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.v1beta1.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.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse other =
(com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.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.v1beta1.EndpointService.ListEndpoints].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListEndpointsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListEndpointsResponse)
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListEndpointsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListEndpointsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.EndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListEndpointsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse build() {
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse result =
new com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint> endpoints_ =
java.util.Collections.emptyList();
private void ensureEndpointsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
endpoints_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Endpoint>(endpoints_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Endpoint,
com.google.cloud.aiplatform.v1beta1.Endpoint.Builder,
com.google.cloud.aiplatform.v1beta1.EndpointOrBuilder>
endpointsBuilder_;
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder setEndpoints(int index, com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder setEndpoints(
int index, com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder addEndpoints(com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder addEndpoints(int index, com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder addEndpoints(
com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder addEndpoints(
int index, com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public Builder addAllEndpoints(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.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.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Endpoint.Builder getEndpointsBuilder(int index) {
return getEndpointsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Endpoint.Builder addEndpointsBuilder() {
return getEndpointsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Endpoint.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Endpoint.Builder addEndpointsBuilder(int index) {
return getEndpointsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Endpoint.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Endpoints in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Endpoint endpoints = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Endpoint.Builder>
getEndpointsBuilderList() {
return getEndpointsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Endpoint,
com.google.cloud.aiplatform.v1beta1.Endpoint.Builder,
com.google.cloud.aiplatform.v1beta1.EndpointOrBuilder>
getEndpointsFieldBuilder() {
if (endpointsBuilder_ == null) {
endpointsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Endpoint,
com.google.cloud.aiplatform.v1beta1.Endpoint.Builder,
com.google.cloud.aiplatform.v1beta1.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.v1beta1.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.v1beta1.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.v1beta1.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.v1beta1.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.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListEndpointsResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse();
}
public static com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.ListEndpointsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/graalpython | 37,607 | graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/io/BytesIOBuiltins.java | /*
* Copyright (c) 2021, 2025, 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.graal.python.builtins.modules.io;
import static com.oracle.graal.python.builtins.PythonBuiltinClassType.OverflowError;
import static com.oracle.graal.python.builtins.modules.io.BufferedIOUtil.SEEK_CUR;
import static com.oracle.graal.python.builtins.modules.io.BufferedIOUtil.SEEK_END;
import static com.oracle.graal.python.builtins.modules.io.BufferedIOUtil.SEEK_SET;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_CLOSE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_CLOSED;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_FLUSH;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_GETBUFFER;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_GETVALUE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_ISATTY;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_READ;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_READ1;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_READABLE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_READINTO;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_READLINE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_READLINES;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_SEEK;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_SEEKABLE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_TELL;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_TRUNCATE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_WRITABLE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_WRITE;
import static com.oracle.graal.python.builtins.modules.io.IONodes.J_WRITELINES;
import static com.oracle.graal.python.nodes.ErrorMessages.INVALID_WHENCE_D_SHOULD_BE_0_1_OR_2;
import static com.oracle.graal.python.nodes.ErrorMessages.IO_CLOSED;
import static com.oracle.graal.python.nodes.ErrorMessages.NEGATIVE_SEEK_VALUE_D;
import static com.oracle.graal.python.nodes.ErrorMessages.NEGATIVE_SIZE_VALUE_D;
import static com.oracle.graal.python.nodes.ErrorMessages.NEW_POSITION_TOO_LARGE;
import static com.oracle.graal.python.nodes.ErrorMessages.POSITION_VALUE_CANNOT_BE_NEGATIVE;
import static com.oracle.graal.python.nodes.ErrorMessages.P_SETSTATE_ARGUMENT_SHOULD_BE_D_TUPLE_GOT_P;
import static com.oracle.graal.python.nodes.ErrorMessages.SECOND_ITEM_OF_STATE_MUST_BE_AN_INTEGER_NOT_P;
import static com.oracle.graal.python.nodes.ErrorMessages.THIRD_ITEM_OF_STATE_SHOULD_BE_A_DICT_GOT_A_P;
import static com.oracle.graal.python.nodes.SpecialMethodNames.J___GETSTATE__;
import static com.oracle.graal.python.nodes.SpecialMethodNames.J___SETSTATE__;
import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError;
import static com.oracle.graal.python.runtime.exception.PythonErrorType.ValueError;
import java.util.List;
import com.oracle.graal.python.PythonLanguage;
import com.oracle.graal.python.annotations.ArgumentClinic;
import com.oracle.graal.python.annotations.Slot;
import com.oracle.graal.python.annotations.Slot.SlotKind;
import com.oracle.graal.python.annotations.Slot.SlotSignature;
import com.oracle.graal.python.annotations.Builtin;
import com.oracle.graal.python.builtins.CoreFunctions;
import com.oracle.graal.python.builtins.PythonBuiltinClassType;
import com.oracle.graal.python.builtins.PythonBuiltins;
import com.oracle.graal.python.builtins.objects.PNone;
import com.oracle.graal.python.builtins.objects.buffer.PythonBufferAccessLibrary;
import com.oracle.graal.python.builtins.objects.buffer.PythonBufferAcquireLibrary;
import com.oracle.graal.python.builtins.objects.bytes.PByteArray;
import com.oracle.graal.python.builtins.objects.bytes.PBytes;
import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageAddAllToOther;
import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes;
import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes.GetInternalObjectArrayNode;
import com.oracle.graal.python.builtins.objects.dict.PDict;
import com.oracle.graal.python.builtins.objects.tuple.PTuple;
import com.oracle.graal.python.builtins.objects.type.TpSlots;
import com.oracle.graal.python.builtins.objects.type.TypeNodes;
import com.oracle.graal.python.builtins.objects.type.slots.TpSlotIterNext.TpIterNextBuiltin;
import com.oracle.graal.python.lib.IteratorExhausted;
import com.oracle.graal.python.lib.PyIndexCheckNode;
import com.oracle.graal.python.lib.PyIterNextNode;
import com.oracle.graal.python.lib.PyMemoryViewFromObject;
import com.oracle.graal.python.lib.PyNumberAsSizeNode;
import com.oracle.graal.python.lib.PyObjectGetIter;
import com.oracle.graal.python.nodes.PGuards;
import com.oracle.graal.python.nodes.PRaiseNode;
import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode;
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonTernaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.clinic.ArgumentClinicProvider;
import com.oracle.graal.python.nodes.object.GetOrCreateDictNode;
import com.oracle.graal.python.runtime.IndirectCallData;
import com.oracle.graal.python.runtime.object.PFactory;
import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage;
import com.oracle.graal.python.util.ArrayBuilder;
import com.oracle.graal.python.util.PythonUtils;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.dsl.Bind;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Cached.Exclusive;
import com.oracle.truffle.api.dsl.Cached.Shared;
import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.NodeFactory;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.library.CachedLibrary;
import com.oracle.truffle.api.nodes.Node;
@CoreFunctions(extendClasses = PythonBuiltinClassType.PBytesIO)
public final class BytesIOBuiltins extends PythonBuiltins {
public static final TpSlots SLOTS = BytesIOBuiltinsSlotsGen.SLOTS;
@Override
protected List<? extends NodeFactory<? extends PythonBuiltinBaseNode>> getNodeFactories() {
return BytesIOBuiltinsFactory.getFactories();
}
abstract static class ClosedCheckPythonUnaryBuiltinNode extends PythonUnaryBuiltinNode {
@Specialization(guards = "!self.hasBuf()")
@SuppressWarnings("unused")
static Object closedError(PBytesIO self,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, ValueError, IO_CLOSED);
}
}
abstract static class ClosedCheckPythonBinaryBuiltinNode extends PythonBinaryBuiltinNode {
@Specialization(guards = "!self.hasBuf()")
@SuppressWarnings("unused")
static Object closedError(PBytesIO self, Object arg,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, ValueError, IO_CLOSED);
}
}
abstract static class ClosedCheckPythonBinaryClinicBuiltinNode extends PythonBinaryClinicBuiltinNode {
@Override
protected ArgumentClinicProvider getArgumentClinic() {
throw CompilerDirectives.shouldNotReachHere();
}
@Specialization(guards = "!self.hasBuf()")
@SuppressWarnings("unused")
static Object closedError(PBytesIO self, Object arg,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, ValueError, IO_CLOSED);
}
}
protected static final byte[] EMPTY_BYTE_ARRAY = PythonUtils.EMPTY_BYTE_ARRAY;
@Slot(value = SlotKind.tp_new, isComplex = true)
@SlotSignature(name = "BytesIO", minNumOfPositionalArgs = 1, takesVarArgs = true, takesVarKeywordArgs = true)
@GenerateNodeFactory
public abstract static class BytesIONode extends PythonBuiltinNode {
@Specialization
static PBytesIO doNew(Object cls, @SuppressWarnings("unused") Object arg,
@Bind PythonLanguage language,
@Cached TypeNodes.GetInstanceShape getInstanceShape) {
// data filled in subsequent __init__ call - see BytesIONodeBuiltins.InitNode
PBytesIO bytesIO = PFactory.createBytesIO(language, cls, getInstanceShape.execute(cls));
bytesIO.setBuf(PFactory.createByteArray(language, PythonUtils.EMPTY_BYTE_ARRAY));
return bytesIO;
}
}
@Slot(value = SlotKind.tp_init, isComplex = true)
@SlotSignature(name = "BytesIO", minNumOfPositionalArgs = 1, parameterNames = {"$self", "initial_bytes"})
@GenerateNodeFactory
public abstract static class InitNode extends PythonBinaryBuiltinNode {
@Specialization
@SuppressWarnings("unused")
static PNone init(PBytesIO self, PNone initvalue,
@Bind Node inliningTarget,
@Shared @Cached PRaiseNode raiseNode) {
self.checkExports(inliningTarget, raiseNode);
self.setPos(0);
return PNone.NONE;
}
@Specialization(guards = "!isPNone(initvalue)")
static PNone init(VirtualFrame frame, PBytesIO self, Object initvalue,
@Bind Node inliningTarget,
@Cached WriteNode writeNode,
@Shared @Cached PRaiseNode raiseNode) {
/* In case, __init__ is called multiple times. */
self.setStringSize(0);
self.setPos(0);
self.checkExports(inliningTarget, raiseNode);
writeNode.execute(frame, self, initvalue);
self.setPos(0);
return PNone.NONE;
}
}
static PBytes readBytes(PBytesIO self, int size,
PythonBufferAccessLibrary bufferLib,
PythonLanguage language) {
if (size == 0) {
return PFactory.createEmptyBytes(language);
}
assert (size <= self.getStringSize());
PByteArray buffer = self.getBuf();
if (self.getPos() == 0 && bufferLib.hasInternalByteArray(buffer) && self.getExports() == 0 && size > bufferLib.getBufferLength(buffer) / 2) {
self.incPos(size);
self.markEscaped();
return PFactory.createBytes(language, bufferLib.getInternalByteArray(buffer), size);
}
PBytes output = PFactory.createBytes(language, bufferLib.getCopyOfRange(buffer, self.getPos(), self.getPos() + size));
self.incPos(size);
return output;
}
@Builtin(name = J_READ, minNumOfPositionalArgs = 1, parameterNames = {"$self", "size"})
@ArgumentClinic(name = "size", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "-1", useDefaultForNone = true)
@GenerateNodeFactory
abstract static class ReadNode extends ClosedCheckPythonBinaryClinicBuiltinNode {
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return BytesIOBuiltinsClinicProviders.ReadNodeClinicProviderGen.INSTANCE;
}
@Specialization(guards = "self.hasBuf()")
static Object read(PBytesIO self, int len,
@Bind PythonLanguage language,
@CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib) {
int size = len;
/* adjust invalid sizes */
int n = self.getStringSize() - self.getPos();
if (size < 0 || size > n) {
size = n;
if (size < 0) {
size = 0;
}
}
return readBytes(self, size, bufferLib, language);
}
}
@Builtin(name = J_READ1, minNumOfPositionalArgs = 1, parameterNames = {"$self", "size"})
@ArgumentClinic(name = "size", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "-1", useDefaultForNone = true)
@GenerateNodeFactory
abstract static class Read1Node extends ReadNode {
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return BytesIOBuiltinsClinicProviders.Read1NodeClinicProviderGen.INSTANCE;
}
}
static int scanEOL(PBytesIO self, int l,
PythonBufferAccessLibrary bufferLib) {
PByteArray buffer = self.getBuf();
byte[] buf = bufferLib.getInternalOrCopiedByteArray(buffer);
return scanEOL(self, l, buf);
}
private static int scanEOL(PBytesIO self, int l, byte[] buf) {
assert (self.getPos() >= 0);
if (self.getPos() >= self.getStringSize()) {
return 0;
}
/* Move to the end of the line, up to the end of the string, s. */
int maxlen = self.getStringSize() - self.getPos();
int len = l;
if (len < 0 || len > maxlen) {
len = maxlen;
}
if (len > 0) {
int n = -1;
for (int i = self.getPos(); i < (self.getPos() + len); i++) {
if (buf[i] == '\n') {
n = i;
break;
}
}
if (n != -1) {
/* Get the length from the current position to the end of the line. */
len = n - self.getPos() + 1;
}
}
assert (len >= 0);
assert (self.getPos() < Integer.MAX_VALUE - len);
return len;
}
@Builtin(name = J_READLINE, minNumOfPositionalArgs = 1, parameterNames = {"$self", "size"})
@ArgumentClinic(name = "size", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "-1", useDefaultForNone = true)
@GenerateNodeFactory
abstract static class ReadlineNode extends ClosedCheckPythonBinaryClinicBuiltinNode {
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return BytesIOBuiltinsClinicProviders.ReadlineNodeClinicProviderGen.INSTANCE;
}
@Specialization(guards = "self.hasBuf()")
Object readline(PBytesIO self, int size,
@Bind PythonLanguage language,
@CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib) {
int n = scanEOL(self, size, bufferLib);
return readBytes(self, n, bufferLib, language);
}
}
@Builtin(name = J_READLINES, minNumOfPositionalArgs = 1, parameterNames = {"$self", "size"})
@ArgumentClinic(name = "size", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "-1", useDefaultForNone = true)
@GenerateNodeFactory
abstract static class ReadlinesNode extends ClosedCheckPythonBinaryClinicBuiltinNode {
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return BytesIOBuiltinsClinicProviders.ReadlinesNodeClinicProviderGen.INSTANCE;
}
@Specialization(guards = "self.hasBuf()")
static Object readlines(PBytesIO self, int maxsize,
@Bind PythonLanguage language,
@CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib) {
ArrayBuilder<Object> result = new ArrayBuilder<>();
int n;
PByteArray buffer = self.getBuf();
byte[] buf = bufferLib.getInternalOrCopiedByteArray(buffer);
int cur = self.getPos();
int size = 0;
while ((n = scanEOL(self, -1, buf)) != 0) {
self.incPos(n);
PBytes line = PFactory.createBytes(language, PythonUtils.arrayCopyOfRange(buf, cur, cur + n));
result.add(line);
size += n;
if (maxsize > 0 && size >= maxsize) {
break;
}
cur += n;
}
return PFactory.createList(language, result.toArray(new Object[0]));
}
}
@Builtin(name = J_READINTO, minNumOfPositionalArgs = 2, numOfPositionalOnlyArgs = 2, parameterNames = {"$self", "buffer"})
@ArgumentClinic(name = "buffer", conversion = ArgumentClinic.ClinicConversion.WritableBuffer)
@GenerateNodeFactory
abstract static class ReadIntoNode extends ClosedCheckPythonBinaryClinicBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object readinto(VirtualFrame frame, PBytesIO self, Object buffer,
@Cached("createFor($node)") IndirectCallData indirectCallData,
@CachedLibrary(limit = "3") PythonBufferAccessLibrary bufferLib) {
try {
/* adjust invalid sizes */
int len = bufferLib.getBufferLength(buffer);
int n = self.getStringSize() - self.getPos();
if (len > n) {
len = n;
if (len < 0) {
return 0;
}
}
bufferLib.readIntoBuffer(self.getBuf(), self.getPos(), buffer, 0, len, bufferLib);
assert (self.getPos() + len < Integer.MAX_VALUE);
assert (len >= 0);
self.incPos(len);
return len;
} finally {
bufferLib.release(buffer, frame, indirectCallData);
}
}
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return BytesIOBuiltinsClinicProviders.ReadIntoNodeClinicProviderGen.INSTANCE;
}
}
@Builtin(name = J_TRUNCATE, minNumOfPositionalArgs = 1, parameterNames = {"$self", "size"})
@GenerateNodeFactory
abstract static class TruncateNode extends ClosedCheckPythonBinaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object truncate(PBytesIO self, int size,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Shared("lib") @CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib,
@Shared @Cached PRaiseNode raiseNode) {
self.checkExports(inliningTarget, raiseNode);
if (size < 0) {
throw raiseNode.raise(inliningTarget, ValueError, NEGATIVE_SIZE_VALUE_D, size);
}
if (size < self.getStringSize()) {
self.unshareAndResize(bufferLib, language, size, true);
self.setStringSize(size);
}
return size;
}
@Specialization(guards = "self.hasBuf()")
static Object truncate(PBytesIO self, @SuppressWarnings("unused") PNone size,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Shared("lib") @CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib,
@Shared @Cached PRaiseNode raiseNode) {
return truncate(self, self.getPos(), inliningTarget, language, bufferLib, raiseNode);
}
@Specialization(guards = {"self.hasBuf()", "!isPNone(size)"})
static Object truncate(VirtualFrame frame, PBytesIO self, Object size,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached PyNumberAsSizeNode asSizeNode,
@Shared("lib") @CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib,
@Exclusive @Cached PRaiseNode raiseNode) {
return truncate(self, asSizeNode.executeExact(frame, inliningTarget, size), inliningTarget, language, bufferLib, raiseNode);
}
}
@Builtin(name = J_WRITE, minNumOfPositionalArgs = 2)
@GenerateNodeFactory
abstract static class WriteNode extends ClosedCheckPythonBinaryBuiltinNode {
@Specialization(guards = "self.hasBuf()", limit = "3")
static Object doWrite(VirtualFrame frame, PBytesIO self, Object b,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached("createFor($node)") IndirectCallData indirectCallData,
@CachedLibrary("b") PythonBufferAcquireLibrary acquireLib,
@CachedLibrary(limit = "2") PythonBufferAccessLibrary bufferLib,
@Cached PRaiseNode raiseNode) {
self.checkExports(inliningTarget, raiseNode);
Object buffer = acquireLib.acquireReadonly(b, frame, indirectCallData);
try {
int len = bufferLib.getBufferLength(buffer);
if (len == 0) {
return 0;
}
int pos = self.getPos();
int endpos = pos + len;
self.unshareAndResize(bufferLib, language, endpos, false);
bufferLib.readIntoBuffer(buffer, 0, self.getBuf(), pos, len, bufferLib);
self.setPos(endpos);
if (endpos > self.getStringSize()) {
self.setStringSize(endpos);
}
return len;
} finally {
bufferLib.release(buffer, frame, indirectCallData);
}
}
}
@Builtin(name = J_WRITELINES, minNumOfPositionalArgs = 2, parameterNames = {"$self", "lines"})
@GenerateNodeFactory
abstract static class WriteLinesNode extends ClosedCheckPythonBinaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object writeLines(VirtualFrame frame, PBytesIO self, Object lines,
@Bind Node inliningTarget,
@Cached WriteNode writeNode,
@Cached PyObjectGetIter getIter,
@Cached PyIterNextNode nextNode,
@Cached PRaiseNode raiseNode) {
self.checkExports(inliningTarget, raiseNode);
Object iter = getIter.execute(frame, inliningTarget, lines);
while (true) {
Object line;
try {
line = nextNode.execute(frame, inliningTarget, iter);
} catch (IteratorExhausted e) {
break;
}
writeNode.execute(frame, self, line);
}
return PNone.NONE;
}
}
@Builtin(name = J_ISATTY, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class IsAttyNode extends ClosedCheckPythonUnaryBuiltinNode {
@SuppressWarnings("unused")
@Specialization(guards = "self.hasBuf()")
static boolean atty(PBytesIO self) {
return false;
}
}
@Builtin(name = J_TELL, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class TellNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object tell(PBytesIO self) {
return self.getPos();
}
}
@Builtin(name = J_SEEK, minNumOfPositionalArgs = 2, parameterNames = {"$self", "pos", "whence"})
@ArgumentClinic(name = "pos", conversion = ArgumentClinic.ClinicConversion.Index)
@ArgumentClinic(name = "whence", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "BufferedIOUtil.SEEK_SET", useDefaultForNone = true)
@GenerateNodeFactory
abstract static class SeekNode extends PythonTernaryClinicBuiltinNode {
@Override
protected ArgumentClinicProvider getArgumentClinic() {
return BytesIOBuiltinsClinicProviders.SeekNodeClinicProviderGen.INSTANCE;
}
protected static boolean isSupportedWhence(int whence) {
return whence == SEEK_SET || whence == SEEK_CUR || whence == SEEK_END;
}
protected static boolean isLargePos(int pos, int to) {
return pos > Integer.MAX_VALUE - to;
}
protected static boolean validPos(PBytesIO self, int pos, int whence) {
return !(pos < 0 && whence == 0) &&
!(isLargePos(pos, self.getStringSize()) && whence == 2) &&
!(isLargePos(pos, self.getPos()) && whence == 1);
}
@Specialization(guards = {"self.hasBuf()", "isSupportedWhence(whence)", "validPos(self, pos, whence)"})
static Object seek(PBytesIO self, int pos, int whence) {
/*-
* whence = 0: offset relative to beginning of the string.
* whence = 1: offset relative to current position.
* whence = 2: offset relative the end of the string.
*/
int p = pos;
if (whence == 1) {
p += self.getPos();
} else if (whence == 2) {
p += self.getStringSize();
}
if (p < 0) {
p = 0;
}
self.setPos(p);
return p;
}
@Specialization(guards = {"self.hasBuf()", "!isSupportedWhence(whence)"})
static Object whenceError(@SuppressWarnings("unused") PBytesIO self, @SuppressWarnings("unused") int pos, int whence,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, ValueError, INVALID_WHENCE_D_SHOULD_BE_0_1_OR_2, whence);
}
@SuppressWarnings("unused")
@Specialization(guards = {"self.hasBuf()", "isLargePos(pos, self.getPos())", "whence == 1"})
static Object largePos1(PBytesIO self, int pos, int whence,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, OverflowError, NEW_POSITION_TOO_LARGE);
}
@SuppressWarnings("unused")
@Specialization(guards = {"self.hasBuf()", "isLargePos(pos, self.getStringSize())", "whence == 2"})
static Object largePos2(PBytesIO self, int pos, int whence,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, OverflowError, NEW_POSITION_TOO_LARGE);
}
@Specialization(guards = {"self.hasBuf()", "pos < 0", "whence == 0"})
static Object negPos(@SuppressWarnings("unused") PBytesIO self, int pos, @SuppressWarnings("unused") int whence,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, ValueError, NEGATIVE_SEEK_VALUE_D, pos);
}
@SuppressWarnings("unused")
@Specialization(guards = "!self.hasBuf()")
static Object closedError(PBytesIO self, int pos, int whence,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, ValueError, IO_CLOSED);
}
}
@Builtin(name = J_GETBUFFER, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class GetBufferNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization
static Object doit(VirtualFrame frame, PBytesIO self,
@CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached PyMemoryViewFromObject memoryViewNode,
@Cached SequenceStorageNodes.SetLenNode setLenNode) {
self.unshareIfNecessary(bufferLib, language);
setLenNode.execute(inliningTarget, self.getBuf().getSequenceStorage(), self.getStringSize());
PBytesIOBuffer buf = PFactory.createBytesIOBuf(language, self);
return memoryViewNode.execute(frame, buf);
}
}
@Builtin(name = J_GETVALUE, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class GetValueNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object doCopy(PBytesIO self,
@Bind PythonLanguage language,
@CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib) {
if (bufferLib.hasInternalByteArray(self.getBuf()) && self.getExports() == 0) {
self.markEscaped();
}
return PFactory.createBytes(language, bufferLib.getInternalOrCopiedByteArray(self.getBuf()), self.getStringSize());
}
}
@Builtin(name = J___GETSTATE__, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class GetStateNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object doit(VirtualFrame frame, PBytesIO self,
@Bind Node inliningTarget,
@Bind PythonLanguage language,
@Cached GetValueNode getValueNode,
@Cached GetOrCreateDictNode getDict) {
Object initValue = getValueNode.execute(frame, self);
Object[] state = new Object[]{initValue, self.getPos(), getDict.execute(inliningTarget, self)};
return PFactory.createTuple(language, state);
}
}
@Builtin(name = J___SETSTATE__, minNumOfPositionalArgs = 2)
@GenerateNodeFactory
abstract static class SetStateNode extends PythonBinaryBuiltinNode {
@Specialization
static Object doit(VirtualFrame frame, PBytesIO self, PTuple state,
@Bind Node inliningTarget,
@Cached GetInternalObjectArrayNode getArray,
@Cached WriteNode writeNode,
@Cached PyIndexCheckNode indexCheckNode,
@Cached PyNumberAsSizeNode asSizeNode,
@Cached GetOrCreateDictNode getDict,
@Cached HashingStorageAddAllToOther addAllToOtherNode,
@Cached PRaiseNode raiseNode) {
self.checkExports(inliningTarget, raiseNode);
SequenceStorage storage = state.getSequenceStorage();
Object[] array = getArray.execute(inliningTarget, storage);
if (storage.length() < 3) {
return notTuple(self, state, raiseNode);
}
/*
* Reset the object to its default state. This is only needed to handle the case of
* repeated calls to __setstate__.
*/
self.setStringSize(0);
self.setPos(0);
/*
* Set the value of the internal buffer. If state[0] does not support the buffer
* protocol, bytesio_write will raise the appropriate TypeError.
*/
writeNode.execute(frame, self, array[0]);
/*
* Set carefully the position value. Alternatively, we could use the seek method instead
* of modifying self.getPos() directly to better protect the object internal state
* against erroneous (or malicious) inputs.
*/
if (!indexCheckNode.execute(inliningTarget, array[1])) {
throw raiseNode.raise(inliningTarget, TypeError, SECOND_ITEM_OF_STATE_MUST_BE_AN_INTEGER_NOT_P, array[1]);
}
int pos = asSizeNode.executeExact(frame, inliningTarget, array[1]);
if (pos < 0) {
throw raiseNode.raise(inliningTarget, ValueError, POSITION_VALUE_CANNOT_BE_NEGATIVE);
}
self.setPos(pos);
/* Set the dictionary of the instance variables. */
if (!PGuards.isNone(array[2])) {
if (!PGuards.isDict(array[2])) {
throw raiseNode.raise(inliningTarget, TypeError, THIRD_ITEM_OF_STATE_SHOULD_BE_A_DICT_GOT_A_P, array[2]);
}
/*
* Alternatively, we could replace the internal dictionary completely. However, it
* seems more practical to just update it.
*/
PDict dict = getDict.execute(inliningTarget, self);
addAllToOtherNode.execute(frame, inliningTarget, ((PDict) array[2]).getDictStorage(), dict);
}
return PNone.NONE;
}
@Specialization(guards = "!isPTuple(state)")
static Object notTuple(PBytesIO self, Object state,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, TypeError, P_SETSTATE_ARGUMENT_SHOULD_BE_D_TUPLE_GOT_P, self, 3, state);
}
}
@Builtin(name = J_FLUSH, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class FlushNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object doit(@SuppressWarnings("unused") PBytesIO self) {
return PNone.NONE;
}
}
@Builtin(name = J_SEEKABLE, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class SeekableNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static boolean seekable(@SuppressWarnings("unused") PBytesIO self) {
return true;
}
}
@Builtin(name = J_READABLE, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class ReadableNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static boolean readable(@SuppressWarnings("unused") PBytesIO self) {
return true;
}
}
@Builtin(name = J_WRITABLE, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class WritableNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static boolean writable(@SuppressWarnings("unused") PBytesIO self) {
return true;
}
}
@Builtin(name = J_CLOSED, minNumOfPositionalArgs = 1, isGetter = true)
@GenerateNodeFactory
abstract static class ClosedNode extends PythonUnaryBuiltinNode {
@Specialization
static boolean closed(PBytesIO self) {
return !self.hasBuf();
}
}
@Builtin(name = J_CLOSE, minNumOfPositionalArgs = 1)
@GenerateNodeFactory
abstract static class CloseNode extends PythonUnaryBuiltinNode {
@Specialization
static Object close(PBytesIO self,
@Bind Node inliningTarget,
@Cached PRaiseNode raiseNode) {
self.checkExports(inliningTarget, raiseNode);
self.setBuf(null);
return PNone.NONE;
}
}
@Slot(value = SlotKind.tp_iternext, isComplex = true)
@GenerateNodeFactory
abstract static class IternextNode extends ClosedCheckPythonUnaryBuiltinNode {
@Specialization(guards = "self.hasBuf()")
static Object doit(PBytesIO self,
@Bind PythonLanguage language,
@CachedLibrary(limit = "1") PythonBufferAccessLibrary bufferLib) {
int n = scanEOL(self, -1, bufferLib);
if (n == 0) {
throw TpIterNextBuiltin.iteratorExhausted();
}
return readBytes(self, n, bufferLib, language);
}
}
}
|
apache/dubbo | 37,468 | dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.extension;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.convert.Converter;
import org.apache.dubbo.common.convert.StringToBooleanConverter;
import org.apache.dubbo.common.convert.StringToDoubleConverter;
import org.apache.dubbo.common.convert.StringToIntegerConverter;
import org.apache.dubbo.common.extension.activate.ActivateExt1;
import org.apache.dubbo.common.extension.activate.impl.ActivateExt1Impl1;
import org.apache.dubbo.common.extension.activate.impl.GroupActivateExtImpl;
import org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl1;
import org.apache.dubbo.common.extension.activate.impl.OrderActivateExtImpl2;
import org.apache.dubbo.common.extension.activate.impl.ValueActivateExtImpl;
import org.apache.dubbo.common.extension.convert.String2BooleanConverter;
import org.apache.dubbo.common.extension.convert.String2DoubleConverter;
import org.apache.dubbo.common.extension.convert.String2IntegerConverter;
import org.apache.dubbo.common.extension.duplicated.DuplicatedOverriddenExt;
import org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt;
import org.apache.dubbo.common.extension.ext1.SimpleExt;
import org.apache.dubbo.common.extension.ext1.impl.SimpleExtImpl1;
import org.apache.dubbo.common.extension.ext1.impl.SimpleExtImpl2;
import org.apache.dubbo.common.extension.ext10_multi_names.Ext10MultiNames;
import org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExt;
import org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExtImpl;
import org.apache.dubbo.common.extension.ext2.Ext2;
import org.apache.dubbo.common.extension.ext6_wrap.WrappedExt;
import org.apache.dubbo.common.extension.ext6_wrap.WrappedExtWrapper;
import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Impl1;
import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Impl3;
import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper1;
import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper2;
import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper3;
import org.apache.dubbo.common.extension.ext6_wrap.impl.Ext6Wrapper4;
import org.apache.dubbo.common.extension.ext7.InitErrorExt;
import org.apache.dubbo.common.extension.ext8_add.AddExt1;
import org.apache.dubbo.common.extension.ext8_add.AddExt2;
import org.apache.dubbo.common.extension.ext8_add.AddExt3;
import org.apache.dubbo.common.extension.ext8_add.AddExt4;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1Impl1;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1_ManualAdaptive;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1_ManualAdd1;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt1_ManualAdd2;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt2_ManualAdaptive;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt3_ManualAdaptive;
import org.apache.dubbo.common.extension.ext8_add.impl.AddExt4_ManualAdaptive;
import org.apache.dubbo.common.extension.ext9_empty.Ext9Empty;
import org.apache.dubbo.common.extension.ext9_empty.impl.Ext9EmptyImpl;
import org.apache.dubbo.common.extension.injection.InjectExt;
import org.apache.dubbo.common.extension.injection.impl.InjectExtImpl;
import org.apache.dubbo.common.extension.wrapper.Demo;
import org.apache.dubbo.common.extension.wrapper.impl.DemoImpl;
import org.apache.dubbo.common.extension.wrapper.impl.DemoWrapper;
import org.apache.dubbo.common.extension.wrapper.impl.DemoWrapper2;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.extension.ExtensionLoader.getLoadingStrategies;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
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.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class ExtensionLoaderTest {
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
return ApplicationModel.defaultModel().getExtensionDirector().getExtensionLoader(type);
}
@Test
void test_getExtensionLoader_Null() {
try {
getExtensionLoader(null);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension type == null"));
}
}
@Test
void test_getExtensionLoader_NotInterface() {
try {
getExtensionLoader(ExtensionLoaderTest.class);
fail();
} catch (IllegalArgumentException expected) {
assertThat(
expected.getMessage(),
containsString(
"Extension type (class org.apache.dubbo.common.extension.ExtensionLoaderTest) is not an interface"));
}
}
@Test
void test_getExtensionLoader_NotSpiAnnotation() {
try {
getExtensionLoader(NoSpiExt.class);
fail();
} catch (IllegalArgumentException expected) {
assertThat(
expected.getMessage(),
allOf(
containsString("org.apache.dubbo.common.extension.NoSpiExt"),
containsString("is not an extension"),
containsString("NOT annotated with @SPI")));
}
}
@Test
void test_getDefaultExtension() {
SimpleExt ext = getExtensionLoader(SimpleExt.class).getDefaultExtension();
assertThat(ext, instanceOf(SimpleExtImpl1.class));
String name = getExtensionLoader(SimpleExt.class).getDefaultExtensionName();
assertEquals("impl1", name);
}
@Test
void test_getDefaultExtension_NULL() {
Ext2 ext = getExtensionLoader(Ext2.class).getDefaultExtension();
assertNull(ext);
String name = getExtensionLoader(Ext2.class).getDefaultExtensionName();
assertNull(name);
}
@Test
void test_getExtension() {
assertTrue(getExtensionLoader(SimpleExt.class).getExtension("impl1") instanceof SimpleExtImpl1);
assertTrue(getExtensionLoader(SimpleExt.class).getExtension("impl2") instanceof SimpleExtImpl2);
}
@Test
void test_getExtension_WithWrapper() {
WrappedExt impl1 = getExtensionLoader(WrappedExt.class).getExtension("impl1");
assertThat(impl1, anyOf(instanceOf(Ext6Wrapper1.class), instanceOf(Ext6Wrapper2.class)));
assertThat(impl1, instanceOf(WrappedExtWrapper.class));
// get origin instance from wrapper
WrappedExt originImpl1 = impl1;
while (originImpl1 instanceof WrappedExtWrapper) {
originImpl1 = ((WrappedExtWrapper) originImpl1).getOrigin();
}
// test unwrapped instance
WrappedExt unwrappedImpl1 = getExtensionLoader(WrappedExt.class).getExtension("impl1", false);
assertThat(unwrappedImpl1, instanceOf(Ext6Impl1.class));
assertNotSame(unwrappedImpl1, impl1);
assertSame(unwrappedImpl1, originImpl1);
WrappedExt impl2 = getExtensionLoader(WrappedExt.class).getExtension("impl2");
assertThat(impl2, anyOf(instanceOf(Ext6Wrapper1.class), instanceOf(Ext6Wrapper2.class)));
URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1");
int echoCount1 = Ext6Wrapper1.echoCount.get();
int echoCount2 = Ext6Wrapper2.echoCount.get();
assertEquals("Ext6Impl1-echo", impl1.echo(url, "ha"));
assertEquals(echoCount1 + 1, Ext6Wrapper1.echoCount.get());
assertEquals(echoCount2 + 1, Ext6Wrapper2.echoCount.get());
}
@Test
void test_getExtension_withWrapperAnnotation() {
WrappedExt impl3 = getExtensionLoader(WrappedExt.class).getExtension("impl3");
assertThat(impl3, instanceOf(Ext6Wrapper3.class));
WrappedExt originImpl3 = impl3;
while (originImpl3 instanceof WrappedExtWrapper) {
originImpl3 = ((WrappedExtWrapper) originImpl3).getOrigin();
}
// test unwrapped instance
WrappedExt unwrappedImpl3 = getExtensionLoader(WrappedExt.class).getExtension("impl3", false);
assertThat(unwrappedImpl3, instanceOf(Ext6Impl3.class));
assertNotSame(unwrappedImpl3, impl3);
assertSame(unwrappedImpl3, originImpl3);
WrappedExt impl4 = getExtensionLoader(WrappedExt.class).getExtension("impl4");
assertThat(impl4, instanceOf(Ext6Wrapper4.class));
URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1");
int echoCount3 = Ext6Wrapper3.echoCount.get();
int echoCount4 = Ext6Wrapper4.echoCount.get();
assertEquals("Ext6Impl4-echo", impl4.echo(url, "haha"));
assertEquals(echoCount3, Ext6Wrapper3.echoCount.get());
assertEquals(echoCount4 + 1, Ext6Wrapper4.echoCount.get());
}
@Test
void test_getActivateExtension_WithWrapper1() {
URL url = URL.valueOf("test://localhost/test");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order");
assertEquals(2, list.size());
}
@Test
void test_getExtension_ExceptionNoExtension() {
try {
getExtensionLoader(SimpleExt.class).getExtension("XXX");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString("No such extension org.apache.dubbo.common.extension.ext1.SimpleExt by name XXX"));
}
}
@Test
void test_getExtension_ExceptionNoExtension_WrapperNotAffactName() {
try {
getExtensionLoader(WrappedExt.class).getExtension("XXX");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"No such extension org.apache.dubbo.common.extension.ext6_wrap.WrappedExt by name XXX"));
}
}
@Test
void test_getExtension_ExceptionNullArg() {
try {
getExtensionLoader(SimpleExt.class).getExtension(null);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void test_hasExtension() {
assertTrue(getExtensionLoader(SimpleExt.class).hasExtension("impl1"));
assertFalse(getExtensionLoader(SimpleExt.class).hasExtension("impl1,impl2"));
assertFalse(getExtensionLoader(SimpleExt.class).hasExtension("xxx"));
try {
getExtensionLoader(SimpleExt.class).hasExtension(null);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void test_hasExtension_wrapperIsNotExt() {
assertTrue(getExtensionLoader(WrappedExt.class).hasExtension("impl1"));
assertFalse(getExtensionLoader(WrappedExt.class).hasExtension("impl1,impl2"));
assertFalse(getExtensionLoader(WrappedExt.class).hasExtension("xxx"));
assertFalse(getExtensionLoader(WrappedExt.class).hasExtension("wrapper1"));
try {
getExtensionLoader(WrappedExt.class).hasExtension(null);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void test_getSupportedExtensions() {
Set<String> exts = getExtensionLoader(SimpleExt.class).getSupportedExtensions();
Set<String> expected = new HashSet<>();
expected.add("impl1");
expected.add("impl2");
expected.add("impl3");
assertEquals(expected, exts);
}
@Test
void test_getSupportedExtensions_wrapperIsNotExt() {
Set<String> exts = getExtensionLoader(WrappedExt.class).getSupportedExtensions();
Set<String> expected = new HashSet<>();
expected.add("impl1");
expected.add("impl2");
expected.add("impl3");
expected.add("impl4");
assertEquals(expected, exts);
}
@Test
void test_AddExtension() {
try {
getExtensionLoader(AddExt1.class).getExtension("Manual1");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual"));
}
getExtensionLoader(AddExt1.class).addExtension("Manual1", AddExt1_ManualAdd1.class);
AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("Manual1");
assertThat(ext, instanceOf(AddExt1_ManualAdd1.class));
assertEquals("Manual1", getExtensionLoader(AddExt1.class).getExtensionName(AddExt1_ManualAdd1.class));
}
@Test
void test_AddExtension_NoExtend() {
getExtensionLoader(Ext9Empty.class).addExtension("ext9", Ext9EmptyImpl.class);
Ext9Empty ext = getExtensionLoader(Ext9Empty.class).getExtension("ext9");
assertThat(ext, instanceOf(Ext9Empty.class));
assertEquals("ext9", getExtensionLoader(Ext9Empty.class).getExtensionName(Ext9EmptyImpl.class));
}
@Test
void test_AddExtension_ExceptionWhenExistedExtension() {
SimpleExt ext = getExtensionLoader(SimpleExt.class).getExtension("impl1");
try {
getExtensionLoader(AddExt1.class).addExtension("impl1", AddExt1_ManualAdd1.class);
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Extension name impl1 already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!"));
}
}
@Test
void test_AddExtension_Adaptive() {
ExtensionLoader<AddExt2> loader = getExtensionLoader(AddExt2.class);
loader.addExtension(null, AddExt2_ManualAdaptive.class);
AddExt2 adaptive = loader.getAdaptiveExtension();
assertTrue(adaptive instanceof AddExt2_ManualAdaptive);
}
@Test
void test_AddExtension_Adaptive_ExceptionWhenExistedAdaptive() {
ExtensionLoader<AddExt1> loader = getExtensionLoader(AddExt1.class);
loader.getAdaptiveExtension();
try {
loader.addExtension(null, AddExt1_ManualAdaptive.class);
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Adaptive Extension already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!"));
}
}
@Test
void test_addExtension_with_error_class() {
try {
getExtensionLoader(SimpleExt.class).addExtension("impl1", ExtensionLoaderTest.class);
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest "
+ "doesn't implement the Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt"));
}
}
@Test
void test_addExtension_with_interface() {
try {
getExtensionLoader(SimpleExt.class).addExtension("impl1", SimpleExt.class);
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt "
+ "can't be interface!"));
}
}
@Test
void test_addExtension_without_adaptive_annotation() {
try {
getExtensionLoader(NoAdaptiveExt.class).addExtension(null, NoAdaptiveExtImpl.class);
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Extension name is blank "
+ "(Extension interface org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExt)!"));
}
}
@Test
void test_getLoadedExtension_name_with_null() {
try {
getExtensionLoader(SimpleExt.class).getLoadedExtension(null);
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void test_getLoadedExtension_null() {
SimpleExt impl1 = getExtensionLoader(SimpleExt.class).getLoadedExtension("XXX");
assertNull(impl1);
}
@Test
void test_getLoadedExtension() {
SimpleExt simpleExt = getExtensionLoader(SimpleExt.class).getExtension("impl1");
assertThat(simpleExt, instanceOf(SimpleExtImpl1.class));
SimpleExt simpleExt1 = getExtensionLoader(SimpleExt.class).getLoadedExtension("impl1");
assertThat(simpleExt1, instanceOf(SimpleExtImpl1.class));
}
@Test
void test_getLoadedExtensions() {
SimpleExt simpleExt1 = getExtensionLoader(SimpleExt.class).getExtension("impl1");
assertThat(simpleExt1, instanceOf(SimpleExtImpl1.class));
SimpleExt simpleExt2 = getExtensionLoader(SimpleExt.class).getExtension("impl2");
assertThat(simpleExt2, instanceOf(SimpleExtImpl2.class));
Set<String> loadedExtensions = getExtensionLoader(SimpleExt.class).getLoadedExtensions();
Assertions.assertNotNull(loadedExtensions);
}
@Test
void test_getLoadedExtensionInstances() {
SimpleExt simpleExt1 = getExtensionLoader(SimpleExt.class).getExtension("impl1");
assertThat(simpleExt1, instanceOf(SimpleExtImpl1.class));
SimpleExt simpleExt2 = getExtensionLoader(SimpleExt.class).getExtension("impl2");
assertThat(simpleExt2, instanceOf(SimpleExtImpl2.class));
List<SimpleExt> loadedExtensionInstances =
getExtensionLoader(SimpleExt.class).getLoadedExtensionInstances();
Assertions.assertNotNull(loadedExtensionInstances);
}
@Test
void test_replaceExtension_with_error_class() {
try {
getExtensionLoader(SimpleExt.class).replaceExtension("impl1", ExtensionLoaderTest.class);
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest "
+ "doesn't implement Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt"));
}
}
@Test
void test_replaceExtension_with_interface() {
try {
getExtensionLoader(SimpleExt.class).replaceExtension("impl1", SimpleExt.class);
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt "
+ "can't be interface!"));
}
}
@Test
void test_replaceExtension() {
try {
getExtensionLoader(AddExt1.class).getExtension("Manual2");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual"));
}
{
AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("impl1");
assertThat(ext, instanceOf(AddExt1Impl1.class));
assertEquals("impl1", getExtensionLoader(AddExt1.class).getExtensionName(AddExt1Impl1.class));
}
{
getExtensionLoader(AddExt1.class).replaceExtension("impl1", AddExt1_ManualAdd2.class);
AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("impl1");
assertThat(ext, instanceOf(AddExt1_ManualAdd2.class));
assertEquals("impl1", getExtensionLoader(AddExt1.class).getExtensionName(AddExt1_ManualAdd2.class));
}
}
@Test
void test_replaceExtension_Adaptive() {
ExtensionLoader<AddExt3> loader = getExtensionLoader(AddExt3.class);
AddExt3 adaptive = loader.getAdaptiveExtension();
assertFalse(adaptive instanceof AddExt3_ManualAdaptive);
loader.replaceExtension(null, AddExt3_ManualAdaptive.class);
adaptive = loader.getAdaptiveExtension();
assertTrue(adaptive instanceof AddExt3_ManualAdaptive);
}
@Test
void test_replaceExtension_ExceptionWhenNotExistedExtension() {
AddExt1 ext = getExtensionLoader(AddExt1.class).getExtension("impl1");
try {
getExtensionLoader(AddExt1.class).replaceExtension("NotExistedExtension", AddExt1_ManualAdd1.class);
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Extension name NotExistedExtension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)"));
}
}
@Test
void test_replaceExtension_Adaptive_ExceptionWhenNotExistedExtension() {
ExtensionLoader<AddExt4> loader = getExtensionLoader(AddExt4.class);
try {
loader.replaceExtension(null, AddExt4_ManualAdaptive.class);
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Adaptive Extension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt4)"));
}
}
@Test
void test_InitError() {
ExtensionLoader<InitErrorExt> loader = getExtensionLoader(InitErrorExt.class);
loader.getExtension("ok");
try {
loader.getExtension("error");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Failed to load extension class (interface: interface org.apache.dubbo.common.extension.ext7.InitErrorExt"));
assertThat(expected.getMessage(), containsString("java.lang.ExceptionInInitializerError"));
}
}
@Test
void testLoadActivateExtension() {
// test default
URL url = URL.valueOf("test://localhost/test");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "default_group");
Assertions.assertEquals(1, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
// test group
url = url.addParameter(GROUP_KEY, "group1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "group1");
Assertions.assertEquals(1, list.size());
assertSame(list.get(0).getClass(), GroupActivateExtImpl.class);
// test value
url = url.removeParameter(GROUP_KEY);
url = url.addParameter(GROUP_KEY, "value");
url = url.addParameter("value", "value");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "value");
Assertions.assertEquals(1, list.size());
assertSame(list.get(0).getClass(), ValueActivateExtImpl.class);
// test order
url = URL.valueOf("test://localhost/test");
url = url.addParameter(GROUP_KEY, "order");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl2.class);
}
@Test
void testLoadDefaultActivateExtension1() {
// test default
URL url = URL.valueOf("test://localhost/test?ext=order1,default");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class);
assertSame(list.get(1).getClass(), ActivateExt1Impl1.class);
url = URL.valueOf("test://localhost/test?ext=default,order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
url = URL.valueOf("test://localhost/test?ext=order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
}
@Test
void testLoadDefaultActivateExtension2() {
// test default
URL url = URL.valueOf("test://localhost/test?ext=order1 , default");
List<ActivateExt1> list =
getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class);
assertSame(list.get(1).getClass(), ActivateExt1Impl1.class);
url = URL.valueOf("test://localhost/test?ext=default, order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
url = URL.valueOf("test://localhost/test?ext=order1");
list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group");
Assertions.assertEquals(2, list.size());
assertSame(list.get(0).getClass(), ActivateExt1Impl1.class);
assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class);
}
@Test
void testInjectExtension() {
// register bean for test ScopeBeanExtensionInjector
DemoImpl demoBean = new DemoImpl();
ApplicationModel.defaultModel().getBeanFactory().registerBean(demoBean);
// test default
InjectExt injectExt = getExtensionLoader(InjectExt.class).getExtension("injection");
InjectExtImpl injectExtImpl = (InjectExtImpl) injectExt;
Assertions.assertNotNull(injectExtImpl.getSimpleExt());
Assertions.assertNull(injectExtImpl.getSimpleExt1());
Assertions.assertNull(injectExtImpl.getGenericType());
Assertions.assertSame(demoBean, injectExtImpl.getDemo());
}
@Test
void testMultiNames() {
Ext10MultiNames ext10MultiNames =
getExtensionLoader(Ext10MultiNames.class).getExtension("impl");
Assertions.assertNotNull(ext10MultiNames);
ext10MultiNames = getExtensionLoader(Ext10MultiNames.class).getExtension("implMultiName");
Assertions.assertNotNull(ext10MultiNames);
Assertions.assertThrows(IllegalStateException.class, () -> getExtensionLoader(Ext10MultiNames.class)
.getExtension("impl,implMultiName"));
}
@Test
void testGetOrDefaultExtension() {
ExtensionLoader<InjectExt> loader = getExtensionLoader(InjectExt.class);
InjectExt injectExt = loader.getOrDefaultExtension("non-exists");
assertEquals(InjectExtImpl.class, injectExt.getClass());
assertEquals(
InjectExtImpl.class, loader.getOrDefaultExtension("injection").getClass());
}
@Test
void testGetSupported() {
ExtensionLoader<InjectExt> loader = getExtensionLoader(InjectExt.class);
assertEquals(1, loader.getSupportedExtensions().size());
assertEquals(Collections.singleton("injection"), loader.getSupportedExtensions());
}
/**
* @since 2.7.7
*/
@Test
void testOverridden() {
ExtensionLoader<Converter> loader = getExtensionLoader(Converter.class);
Converter converter = loader.getExtension("string-to-boolean");
assertEquals(String2BooleanConverter.class, converter.getClass());
converter = loader.getExtension("string-to-double");
assertEquals(String2DoubleConverter.class, converter.getClass());
converter = loader.getExtension("string-to-integer");
assertEquals(String2IntegerConverter.class, converter.getClass());
assertEquals("string-to-boolean", loader.getExtensionName(String2BooleanConverter.class));
assertEquals("string-to-boolean", loader.getExtensionName(StringToBooleanConverter.class));
assertEquals("string-to-double", loader.getExtensionName(String2DoubleConverter.class));
assertEquals("string-to-double", loader.getExtensionName(StringToDoubleConverter.class));
assertEquals("string-to-integer", loader.getExtensionName(String2IntegerConverter.class));
assertEquals("string-to-integer", loader.getExtensionName(StringToIntegerConverter.class));
}
/**
* @since 2.7.7
*/
@Test
void testGetLoadingStrategies() {
List<LoadingStrategy> strategies = getLoadingStrategies();
assertEquals(4, strategies.size());
int i = 0;
LoadingStrategy loadingStrategy = strategies.get(i++);
assertEquals(DubboInternalLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.MAX_PRIORITY, loadingStrategy.getPriority());
loadingStrategy = strategies.get(i++);
assertEquals(DubboExternalLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.MAX_PRIORITY + 1, loadingStrategy.getPriority());
loadingStrategy = strategies.get(i++);
assertEquals(DubboLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.NORMAL_PRIORITY, loadingStrategy.getPriority());
loadingStrategy = strategies.get(i++);
assertEquals(ServicesLoadingStrategy.class, loadingStrategy.getClass());
assertEquals(Prioritized.MIN_PRIORITY, loadingStrategy.getPriority());
}
@Test
void testDuplicatedImplWithoutOverriddenStrategy() {
List<LoadingStrategy> loadingStrategies = ExtensionLoader.getLoadingStrategies();
ExtensionLoader.setLoadingStrategies(
new DubboExternalLoadingStrategyTest(false), new DubboInternalLoadingStrategyTest(false));
ExtensionLoader<DuplicatedWithoutOverriddenExt> extensionLoader =
getExtensionLoader(DuplicatedWithoutOverriddenExt.class);
try {
extensionLoader.getExtension("duplicated");
fail();
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Failed to load extension class (interface: interface org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt"));
assertThat(
expected.getMessage(),
containsString(
"cause: Duplicate extension org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt name duplicated"));
} finally {
// recover the loading strategies
ExtensionLoader.setLoadingStrategies(
loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()]));
}
}
@Test
void testDuplicatedImplWithOverriddenStrategy() {
List<LoadingStrategy> loadingStrategies = ExtensionLoader.getLoadingStrategies();
ExtensionLoader.setLoadingStrategies(
new DubboExternalLoadingStrategyTest(true), new DubboInternalLoadingStrategyTest(true));
ExtensionLoader<DuplicatedOverriddenExt> extensionLoader = getExtensionLoader(DuplicatedOverriddenExt.class);
DuplicatedOverriddenExt duplicatedOverriddenExt = extensionLoader.getExtension("duplicated");
assertEquals("DuplicatedOverriddenExt1", duplicatedOverriddenExt.echo());
// recover the loading strategies
ExtensionLoader.setLoadingStrategies(loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()]));
}
@Test
void testLoadByDubboInternalSPI() {
ExtensionLoader<SPI1> extensionLoader = getExtensionLoader(SPI1.class);
SPI1 spi1 = extensionLoader.getExtension("1", true);
assertNotNull(spi1);
ExtensionLoader<SPI2> extensionLoader2 = getExtensionLoader(SPI2.class);
SPI2 spi2 = extensionLoader2.getExtension("2", true);
assertNotNull(spi2);
try {
ExtensionLoader<SPI3> extensionLoader3 = getExtensionLoader(SPI3.class);
SPI3 spi3 = extensionLoader3.getExtension("3", true);
assertNotNull(spi3);
} catch (IllegalStateException illegalStateException) {
if (!illegalStateException.getMessage().contains("No such extension")) {
fail();
}
}
ExtensionLoader<SPI4> extensionLoader4 = getExtensionLoader(SPI4.class);
SPI4 spi4 = extensionLoader4.getExtension("4", true);
assertNotNull(spi4);
}
@Test
void isWrapperClass() {
assertFalse(getExtensionLoader(Demo.class).isWrapperClass(DemoImpl.class));
assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper.class));
assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper2.class));
}
/**
* The external {@link LoadingStrategy}, which can set if it supports overriding.
*/
private static class DubboExternalLoadingStrategyTest implements LoadingStrategy {
public DubboExternalLoadingStrategyTest(boolean overridden) {
this.overridden = overridden;
}
private boolean overridden;
@Override
public String directory() {
return "META-INF/dubbo/external/";
}
@Override
public boolean overridden() {
return this.overridden;
}
@Override
public int getPriority() {
return MAX_PRIORITY + 1;
}
}
/**
* The internal {@link LoadingStrategy}, which can set if it support overridden
*/
private static class DubboInternalLoadingStrategyTest implements LoadingStrategy {
public DubboInternalLoadingStrategyTest(boolean overridden) {
this.overridden = overridden;
}
private boolean overridden;
@Override
public String directory() {
return "META-INF/dubbo/internal/";
}
@Override
public boolean overridden() {
return this.overridden;
}
@Override
public int getPriority() {
return MAX_PRIORITY;
}
}
}
|
apache/harmony | 37,561 | classlib/modules/beans/src/main/java/java/beans/beancontext/BeanContextServicesSupport.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.beans.beancontext;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.TooManyListenersException;
import java.util.Map.Entry;
import org.apache.harmony.beans.internal.nls.Messages;
/**
* This support class implements <code>BeanContextServices</code> interface.
* This class can be used directly, or be a super class of your class, or be a
* delegate of your implementation that needs to support
* <code>BeanContextServices</code> interface.
*
*/
public class BeanContextServicesSupport extends BeanContextSupport implements
BeanContextServices, Serializable {
private static class ServiceRecord {
BeanContextServiceProvider provider;
BeanContextChild child;
Object requestor;
Class serviceClass;
BeanContextServiceRevokedListener revokedListener;
Object service;
boolean isDelegate;
ServiceRecord(BeanContextServiceProvider provider,
BeanContextChild child, Object requestor, Class serviceClass,
BeanContextServiceRevokedListener revokedListener,
Object service, boolean isDelegate) {
this.provider = provider;
this.child = child;
this.requestor = requestor;
this.serviceClass = serviceClass;
this.revokedListener = revokedListener;
this.service = service;
this.isDelegate = isDelegate;
}
}
/**
* Every child of context is companied with a <code>BCSSChild</code>
* instance. It can hold implementation specific information about each
* child.
* <p>
* This class keeps records of all services requests submitted by this
* child.
* </p>
*
*/
protected class BCSSChild extends BeanContextSupport.BCSChild {
private static final long serialVersionUID = -3263851306889194873L;
transient ArrayList<ServiceRecord> serviceRecords;
BCSSChild(Object child, Object proxyPeer) {
super(child, proxyPeer);
}
}
/**
* This class implements the <code>BeanContextServiceProvider</code>
* interface by wrapping a <code>BeanContextServices</code>. All services
* registered in the <code>BeanContextServices</code> are accessible via
* this wrapper service provider.
* <p>
* This class is used by <code>BeanContextServicesSupport</code> to access
* services provided by its parent context (if there is one).
* </p>
*
*/
protected class BCSSProxyServiceProvider implements
BeanContextServiceProvider, BeanContextServiceRevokedListener {
private BeanContextServices backBCS;
BCSSProxyServiceProvider(BeanContextServices backBCS) {
this.backBCS = backBCS;
}
/**
* Throws <code>UnsupportedOperationException</code>.
*/
public Iterator getCurrentServiceSelectors(BeanContextServices bcs,
Class serviceClass) {
throw new UnsupportedOperationException();
}
/**
* Throws <code>UnsupportedOperationException</code>.
*/
public Object getService(BeanContextServices bcs, Object requestor,
Class serviceClass, Object serviceSelector) {
throw new UnsupportedOperationException();
}
/**
* Delegate to the wrapped <code>BeanContextServices</code>.
*/
Object getService(BeanContextServices bcs, Object requestor,
Class serviceClass, Object serviceSelector,
BeanContextServiceRevokedListener listener)
throws TooManyListenersException {
return backBCS.getService(BeanContextServicesSupport.this
.getBeanContextServicesPeer(), requestor, serviceClass,
serviceSelector, new ServiceRevokedListenerDelegator(
listener));
}
/**
* Delegate to the wrapped <code>BeanContextServices</code>.
*/
public void releaseService(BeanContextServices bcs, Object requestor,
Object service) {
backBCS.releaseService(BeanContextServicesSupport.this
.getBeanContextServicesPeer(), requestor, service);
}
/**
* Throws <code>UnsupportedOperationException</code>.
*/
public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) {
throw new UnsupportedOperationException();
}
}
private class ServiceRevokedListenerDelegator implements
BeanContextServiceRevokedListener {
private BeanContextServiceRevokedListener backListener;
public ServiceRevokedListenerDelegator(
BeanContextServiceRevokedListener backListener) {
this.backListener = backListener;
}
public void serviceRevoked(BeanContextServiceRevokedEvent event) {
backListener.serviceRevoked(new BeanContextServiceRevokedEvent(
BeanContextServicesSupport.this
.getBeanContextServicesPeer(), event
.getServiceClass(), event
.isCurrentServiceInvalidNow()));
}
}
/**
* Every servie registered in this context is companied with a
* <code>BCSSServiceProvider</code> instance. It can hold implementation
* specific information about each registered service.
* <p>
* This class holds a reference to the service provider of the service.
* </p>
*
*/
protected static class BCSSServiceProvider implements Serializable {
private static final long serialVersionUID = 861278251667444782L;
/**
* The service provider of the related service.
*/
protected BeanContextServiceProvider serviceProvider;
BCSSServiceProvider(BeanContextServiceProvider provider) {
this.serviceProvider = provider;
}
/**
* Returns the service provider of the related service.
*
* @return the service provider of the related service
*/
protected BeanContextServiceProvider getServiceProvider() {
return serviceProvider;
}
}
private static final long serialVersionUID = -8494482757288719206L;
/**
* A map of all registered services - key is service class, value is
* <code>BCSSServiceProvider</code> object. All access to this object
* should be synchronized on itself.
*/
@SuppressWarnings("unchecked")
protected transient HashMap services;
/**
* The number of serializable service providers currently registered.
*/
protected transient int serializable;
/**
* A proxy service provider that delegates service requests to the parent
* context.
*/
protected transient BCSSProxyServiceProvider proxy;
/**
* A list of registered <code>BeanContextServicesListener</code>s. All
* access to this object should be synchronized on itself.
*/
@SuppressWarnings("unchecked")
protected transient ArrayList bcsListeners;
/**
* Constructs a standard <code>BeanContextServicesSupport</code>.
*/
public BeanContextServicesSupport() {
super();
}
/**
* Constructs a <code>BeanContextServicesSupport</code> which is a
* delegate of the given peer.
*
* @param peer
* the peer of this context
*/
public BeanContextServicesSupport(BeanContextServices peer) {
super(peer);
}
/**
* Constructs a <code>BeanContextServicesSupport</code> which is a
* delegate of the given peer.
*
* @param peer
* the peer of this context
* @param locale
* the locale of this context
*/
public BeanContextServicesSupport(BeanContextServices peer, Locale locale) {
super(peer, locale);
}
/**
* Constructs a <code>BeanContextServicesSupport</code> which is a
* delegate of the given peer.
*
* @param peer
* the peer of this context
* @param locale
* the locale of this context
* @param designTime
* whether in design mode or not
*/
public BeanContextServicesSupport(BeanContextServices peer, Locale locale,
boolean designTime) {
super(peer, locale, designTime);
}
/**
* Constructs a <code>BeanContextServicesSupport</code> which is a
* delegate of the given peer.
*
* @param peer
* the peer of this context
* @param locale
* the locale of this context
* @param designTime
* whether in design mode or not
* @param okToUseGui
* whether GUI is usable or not
*/
public BeanContextServicesSupport(BeanContextServices peer, Locale locale,
boolean designTime, boolean okToUseGui) {
super(peer, locale, designTime, okToUseGui);
}
/*
* (non-Javadoc)
*
* @see java.beans.beancontext.BeanContextServices#addBeanContextServicesListener(java.beans.beancontext.BeanContextServicesListener)
*/
public void addBeanContextServicesListener(
BeanContextServicesListener listener) {
if (listener == null) {
throw new NullPointerException();
}
synchronized (bcsListeners) {
bcsListeners.add(listener);
}
}
/**
* Add a service to this context.
* <p>
* Delegate to <code>addService(serviceClass, provider, true)</code>.
* </p>
*
* @see java.beans.beancontext.BeanContextServices#addService(java.lang.Class,
* java.beans.beancontext.BeanContextServiceProvider)
*/
public boolean addService(Class serviceClass,
BeanContextServiceProvider provider) {
return addService(serviceClass, provider, true);
}
/**
* Add a service to this context.
* <p>
* If the service already exists in the context, simply return false.
* Otherwise, the service is added and event is fired if required.
* </p>
*
* @param serviceClass
* the service class
* @param provider
* the provider of the service
* @param fireEvent
* the flag indicating to fire event or not
* @return true if the service is added; or false if the context already has
* this service
*/
protected boolean addService(Class serviceClass,
BeanContextServiceProvider provider, boolean fireEvent) {
if (serviceClass == null || provider == null) {
throw new NullPointerException();
}
synchronized (globalHierarchyLock) {
synchronized (services) {
if (services.containsKey(serviceClass)) {
return false;
}
// add to services
services.put(serviceClass, createBCSSServiceProvider(
serviceClass, provider));
// count Serializable
if (provider instanceof Serializable) {
serializable++;
}
}
}
if (fireEvent) {
// notify all listeners and BeanContextServices children
notifyServiceAvailable(new BeanContextServiceAvailableEvent(this,
serviceClass));
}
return true;
}
private void notifyServiceAvailable(BeanContextServiceAvailableEvent event) {
fireServiceAdded(event);
Object childs[] = copyChildren();
for (int i = 0; i < childs.length; i++) {
if (childs[i] instanceof BeanContextServices) {
((BeanContextServices) childs[i]).serviceAvailable(event);
}
}
}
/**
* Deserializes all serializable services and their providers before the
* children of this context is deserialized.
* <p>
* First a <code>int</code> is read, indicating the number of services to
* read. Then pairs of service class and service provider are read one by
* one.
* </p>
*
* @see java.beans.beancontext.BeanContextSupport#bcsPreDeserializationHook(java.io.ObjectInputStream)
*/
protected void bcsPreDeserializationHook(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
super.bcsPreDeserializationHook(ois);
// deserialize services
synchronized (services) {
serializable = ois.readInt();
for (int i = 0; i < serializable; i++) {
Object serviceClass = ois.readObject();
Object bcssProvider = ois.readObject();
services.put((Class) serviceClass,
(BCSSServiceProvider) bcssProvider);
}
}
}
/**
* Serializes all serializable services and their providers before the
* children of this context is serialized.
* <p>
* First a <code>int</code> is writtern, indicating the number of
* serializable services. Then pairs of service class and service provider
* are writtern one by one.
* </p>
*
* @see java.beans.beancontext.BeanContextSupport#bcsPreSerializationHook(java.io.ObjectOutputStream)
*/
protected void bcsPreSerializationHook(ObjectOutputStream oos)
throws IOException {
super.bcsPreSerializationHook(oos);
// serialize services
synchronized (services) {
oos.writeInt(serializable);
for (Iterator iter = services.entrySet().iterator(); iter.hasNext();) {
Entry entry = (Entry) iter.next();
if (((BCSSServiceProvider) entry.getValue())
.getServiceProvider() instanceof Serializable) {
oos.writeObject(entry.getKey());
oos.writeObject(entry.getValue());
}
}
}
}
/**
* This method is called everytime a child is removed from this context.
* <p>
* The implementation releases all services requested by the child.
* </p>
*
* @see java.beans.beancontext.BeanContextSupport#childJustRemovedHook(java.lang.Object,
* java.beans.beancontext.BeanContextSupport.BCSChild)
*/
protected void childJustRemovedHook(Object child, BCSChild bcsChild) {
if (bcsChild instanceof BCSSChild) {
releaseServicesForChild((BCSSChild) bcsChild, false);
}
}
/**
* Release all services requested by the given child.
*
* @param bcssChild
* a child
* @param delegatedServices
* only release services that are delegated to parent context
*/
private void releaseServicesForChild(BCSSChild bcssChild,
boolean delegatedServices) {
if (bcssChild.serviceRecords == null
|| bcssChild.serviceRecords.isEmpty()) {
return;
}
synchronized (bcssChild.child) {
Object records[] = bcssChild.serviceRecords.toArray();
for (int i = 0; i < records.length; i++) {
ServiceRecord rec = (ServiceRecord) records[i];
if (delegatedServices) {
if (rec.isDelegate) {
releaseServiceWithoutCheck(rec.child, bcssChild,
rec.requestor, rec.service, true);
}
} else {
releaseServiceWithoutCheck(rec.child, bcssChild,
rec.requestor, rec.service, false);
}
}
}
}
/**
* Creates a <code>BCSSChild</code> object to company the given child.
*
* @see java.beans.beancontext.BeanContextSupport#createBCSChild(java.lang.Object,
* java.lang.Object)
*/
protected BCSChild createBCSChild(Object child, Object proxyPeer) {
return new BCSSChild(child, proxyPeer);
}
/**
* Creates a <code>BCSSServiceProvider</code> to company the given
* service.
*
* @param serviceClass
* the service class
* @param provider
* the service provider
* @return a <code>BCSSServiceProvider</code> to company the given service
*/
protected BCSSServiceProvider createBCSSServiceProvider(Class serviceClass,
BeanContextServiceProvider provider) {
return new BCSSServiceProvider(provider);
}
/**
* Fires a <code>BeanContextServiceAvailableEvent</code> to registered
* <code>BeanContextServicesListener</code>s.
*
* @param serviceClass
* the service that has been added
*/
protected final void fireServiceAdded(Class serviceClass) {
fireServiceAdded(new BeanContextServiceAvailableEvent(this,
serviceClass));
}
/**
* Fires a <code>BeanContextServiceAvailableEvent</code> to registered
* <code>BeanContextServicesListener</code>s.
*
* @param event
* the event
*/
protected final void fireServiceAdded(BeanContextServiceAvailableEvent event) {
Object listeners[];
synchronized (bcsListeners) {
listeners = bcsListeners.toArray();
}
for (int i = 0; i < listeners.length; i++) {
BeanContextServicesListener l = (BeanContextServicesListener) listeners[i];
l.serviceAvailable(event);
}
}
/**
* Fires a <code>BeanContextServiceRevokedEvent</code> to registered
* <code>BeanContextServicesListener</code>s.
*
* @param serviceClass
* the service that has been revoked
* @param revokeNow
* whether to terminate service immediately
*/
protected final void fireServiceRevoked(Class serviceClass,
boolean revokeNow) {
fireServiceRevoked(new BeanContextServiceRevokedEvent(this,
serviceClass, revokeNow));
}
/**
* Fires a <code>BeanContextServiceRevokedEvent</code> to registered
* <code>BeanContextServicesListener</code>s.
*
* @param event
* the event
*/
protected final void fireServiceRevoked(BeanContextServiceRevokedEvent event) {
Object listeners[];
synchronized (bcsListeners) {
listeners = bcsListeners.toArray();
}
for (int i = 0; i < listeners.length; i++) {
BeanContextServicesListener l = (BeanContextServicesListener) listeners[i];
l.serviceRevoked(event);
}
}
/**
* Returns the peer of this context casted as
* <code>BeanContextServices</code>.
*
* @return the peer of this context casted as
* <code>BeanContextServices</code>
*/
public BeanContextServices getBeanContextServicesPeer() {
return (BeanContextServices) beanContextChildPeer;
}
/**
* Returns the given child casted to
* <code>BeanContextServicesListener</code>, or null if it does not
* implements the interface.
*
* @param child
* a child
* @return the given child casted to
* <code>BeanContextServicesListener</code>, or null if it does
* not implements the interface
*/
protected static final BeanContextServicesListener getChildBeanContextServicesListener(
Object child) {
if (child instanceof BeanContextServicesListener) {
return (BeanContextServicesListener) child;
}
return null;
}
/**
* Returns an iterator of all registered service classes, with
* <code>removed()</code> disabled.
*
* @return an iterator of all registered service classes
* @see java.beans.beancontext.BeanContextServices#getCurrentServiceClasses()
*/
public Iterator getCurrentServiceClasses() {
synchronized (services) {
return new BCSIterator(services.keySet().iterator());
}
}
/**
* Returns the service selectors of the specified service. The iterator's
* <code>remove()</code> operation is disabled.
*
* @see java.beans.beancontext.BeanContextServices#getCurrentServiceSelectors(java.lang.Class)
*/
public Iterator getCurrentServiceSelectors(Class serviceClass) {
BeanContextServiceProvider provider = getLocalServiceProvider(serviceClass);
return provider == null ? null : new BCSIterator(provider
.getCurrentServiceSelectors(getBeanContextServicesPeer(),
serviceClass));
}
private BeanContextServiceProvider getLocalServiceProvider(
Class serviceClass) {
synchronized (services) {
BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services
.get(serviceClass);
if (bcssProvider != null) {
return bcssProvider.getServiceProvider();
}
return null;
}
}
/**
* Get a service instance on behalf of the specified child of this context,
* by calling the registered service provider, or by delegating to the
* parent context.
*
* @param child
* the child that request service
* @param requestor
* the requestor object
* @param serviceClass
* the service class
* @param serviceSelector
* the service selectors
* @param bcsrl
* the <code>BeanContextServiceRevokedListener</code>
* @return a service instance on behalf of the specified child of this
* context
* @throws IllegalArgumentException
* if <code>child</code> is not a child of this context
* @throws TooManyListenersException
* @see java.beans.beancontext.BeanContextServices#getService(java.beans.beancontext.BeanContextChild,
* java.lang.Object, java.lang.Class, java.lang.Object,
* java.beans.beancontext.BeanContextServiceRevokedListener)
*/
public Object getService(BeanContextChild child, Object requestor,
Class serviceClass, Object serviceSelector,
BeanContextServiceRevokedListener bcsrl)
throws TooManyListenersException {
if (child == null || requestor == null || serviceClass == null
|| bcsrl == null) {
throw new NullPointerException();
}
BCSSChild bcssChild = null;
BeanContextServiceProvider provider = null;
Object service = null;
boolean isDelegate = false;
synchronized (globalHierarchyLock) {
// check child
synchronized (children) {
bcssChild = (BCSSChild) children.get(child);
}
if (bcssChild == null) {
throw new IllegalArgumentException(
Messages.getString("beans.65"));
}
// try local service
provider = getLocalServiceProvider(serviceClass);
if (provider != null) {
service = provider.getService(getBeanContextServicesPeer(),
requestor, serviceClass, serviceSelector);
}
// no local service, try delegate
if (service == null && proxy != null) {
provider = proxy;
service = proxy.getService(getBeanContextServicesPeer(),
requestor, serviceClass, serviceSelector, bcsrl);
isDelegate = true;
}
}
if (service != null) {
// save record
synchronized (child) {
if (bcssChild.serviceRecords == null) {
bcssChild.serviceRecords = new ArrayList<ServiceRecord>();
}
bcssChild.serviceRecords.add(new ServiceRecord(provider, child,
requestor, serviceClass, bcsrl, service, isDelegate));
}
}
return service;
}
/**
* Checks whether a service is registed in this context or the parent
* context.
*
* @param serviceClass
* the service class
* @return true if the service is registered
* @see java.beans.beancontext.BeanContextServices#hasService(java.lang.Class)
*/
public boolean hasService(Class serviceClass) {
if (serviceClass == null) {
throw new NullPointerException();
}
boolean has;
synchronized (services) {
has = services.containsKey(serviceClass);
}
if (!has && getBeanContext() instanceof BeanContextServices) {
has = ((BeanContextServices) getBeanContext())
.hasService(serviceClass);
}
return has;
}
/*
* (non-Javadoc)
*
* @see java.beans.beancontext.BeanContextSupport#initialize()
*/
public void initialize() {
super.initialize();
services = new HashMap<Class, BCSSServiceProvider>();
serializable = 0;
proxy = null;
bcsListeners = new ArrayList<BeanContextServicesListener>();
}
/**
* Called after the parent context is updated. The implementation checks if
* the parent context is a <code>BeanContextServices</code>. If it is,
* then a <code>BCSSProxyServiceProvider</code> is created to delegate
* service requests to the parent context.
*
* @see java.beans.beancontext.BeanContextChildSupport#initializeBeanContextResources()
*/
protected void initializeBeanContextResources() {
super.initializeBeanContextResources();
BeanContext context = getBeanContext();
if (context instanceof BeanContextServices) {
proxy = new BCSSProxyServiceProvider((BeanContextServices) context);
} else {
proxy = null;
}
}
/**
* Called before the parent context is updated. The implementation releases
* any service that is currently provided by the parent context.
*
* @see java.beans.beancontext.BeanContextChildSupport#releaseBeanContextResources()
*/
protected void releaseBeanContextResources() {
super.releaseBeanContextResources();
releaseAllDelegatedServices();
proxy = null;
}
private void releaseAllDelegatedServices() {
synchronized (children) {
for (Iterator iter = bcsChildren(); iter.hasNext();) {
releaseServicesForChild((BCSSChild) iter.next(), true);
}
}
}
/**
* Release a service which has been requested previously.
*
* @param child
* the child that request the service
* @param requestor
* the requestor object
* @param service
* the service instance
* @throws IllegalArgumentException
* if <code>child</code> is not a child of this context
*/
public void releaseService(BeanContextChild child, Object requestor,
Object service) {
if (child == null || requestor == null || service == null) {
throw new NullPointerException();
}
synchronized (globalHierarchyLock) {
BCSSChild bcssChild;
synchronized (children) {
bcssChild = (BCSSChild) children.get(child);
}
if (bcssChild == null) {
throw new IllegalArgumentException(
Messages.getString("beans.65"));
}
releaseServiceWithoutCheck(child, bcssChild, requestor, service,
false);
}
}
/**
* Releases a service without checking the membership of the child.
*/
private void releaseServiceWithoutCheck(BeanContextChild child,
BCSSChild bcssChild, Object requestor, Object service,
boolean callRevokedListener) {
if (bcssChild.serviceRecords == null
|| bcssChild.serviceRecords.isEmpty()) {
return;
}
synchronized (child) {
// scan record
for (Iterator iter = bcssChild.serviceRecords.iterator(); iter
.hasNext();) {
ServiceRecord rec = (ServiceRecord) iter.next();
if (rec.requestor == requestor && rec.service == service) {
// release service
rec.provider.releaseService(getBeanContextServicesPeer(),
requestor, service);
// call service revoked listener
if (callRevokedListener && rec.revokedListener != null) {
rec.revokedListener
.serviceRevoked(new BeanContextServiceRevokedEvent(
getBeanContextServicesPeer(),
rec.serviceClass, true));
}
// remove record
iter.remove();
break;
}
}
}
}
/*
* (non-Javadoc)
*
* @see java.beans.beancontext.BeanContextServices#removeBeanContextServicesListener(java.beans.beancontext.BeanContextServicesListener)
*/
public void removeBeanContextServicesListener(
BeanContextServicesListener listener) {
if (listener == null) {
throw new NullPointerException();
}
synchronized (bcsListeners) {
bcsListeners.remove(listener);
}
}
/**
* Revokes a service in this bean context.
* <p>
* The given service provider is unregistered and a
* <code>BeanContextServiceRevokedEvent</code> is fired. All registered
* service listeners and current service users get notified.
* </p>
*
* @param serviceClass
* the service class
* @param serviceProvider
* the service provider
* @param revokeCurrentServicesNow
* true if service should be terminated immediantly
* @see java.beans.beancontext.BeanContextServices#revokeService(java.lang.Class,
* java.beans.beancontext.BeanContextServiceProvider, boolean)
*/
public void revokeService(Class serviceClass,
BeanContextServiceProvider serviceProvider,
boolean revokeCurrentServicesNow) {
if (serviceClass == null || serviceProvider == null) {
throw new NullPointerException();
}
synchronized (globalHierarchyLock) {
synchronized (services) {
BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services
.get(serviceClass);
if (bcssProvider == null) { // non-exist service
return;
}
if (bcssProvider.getServiceProvider() != serviceProvider) {
throw new IllegalArgumentException(
Messages.getString("beans.66"));
}
services.remove(serviceClass);
if (serviceProvider instanceof Serializable) {
serializable--;
}
}
}
// notify listeners
fireServiceRevoked(serviceClass, revokeCurrentServicesNow);
// notify service users
notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider,
revokeCurrentServicesNow);
}
/**
* Notify all children that a service has been revoked.
*/
private void notifyServiceRevokedToServiceUsers(Class serviceClass,
BeanContextServiceProvider serviceProvider,
boolean revokeCurrentServicesNow) {
synchronized (children) {
for (Iterator iter = bcsChildren(); iter.hasNext();) {
BCSSChild bcssChild = (BCSSChild) iter.next();
notifyServiceRevokedToServiceUsers(serviceClass,
serviceProvider, revokeCurrentServicesNow, bcssChild);
}
}
}
/**
* Notify the given child that a service has been revoked.
*/
private void notifyServiceRevokedToServiceUsers(Class serviceClass,
BeanContextServiceProvider serviceProvider,
boolean revokeCurrentServicesNow, BCSSChild bcssChild) {
if (bcssChild.serviceRecords == null
|| bcssChild.serviceRecords.isEmpty()) {
return;
}
synchronized (bcssChild.child) {
for (Iterator it = bcssChild.serviceRecords.iterator(); it
.hasNext();) {
ServiceRecord rec = (ServiceRecord) it.next();
if (rec.serviceClass == serviceClass
&& rec.provider == serviceProvider
&& rec.revokedListener != null && !rec.isDelegate) {
rec.revokedListener
.serviceRevoked(new BeanContextServiceRevokedEvent(
getBeanContextServicesPeer(), serviceClass,
revokeCurrentServicesNow));
// prevent duplicate notification
rec.revokedListener = null;
}
}
}
}
/**
* Notify all listeners and children that implements
* <code>BeanContextServices</code> of the event.
*
* @see java.beans.beancontext.BeanContextServicesListener#serviceAvailable(java.beans.beancontext.BeanContextServiceAvailableEvent)
*/
public void serviceAvailable(BeanContextServiceAvailableEvent event) {
if (null == event) {
throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$
}
if (services.containsKey(event.serviceClass)) {
return;
}
fireServiceAdded(event);
Object childs[] = copyChildren();
for (int i = 0; i < childs.length; i++) {
if (childs[i] instanceof BeanContextServices) {
((BeanContextServices) childs[i]).serviceAvailable(event);
}
}
}
/**
* Notify all listeners and children that implements
* <code>BeanContextServices</code> of the event.
*
* @see java.beans.beancontext.BeanContextServiceRevokedListener#serviceRevoked(java.beans.beancontext.BeanContextServiceRevokedEvent)
*/
public void serviceRevoked(BeanContextServiceRevokedEvent event) {
if (null == event) {
throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$
}
if (services.containsKey(event.serviceClass)) {
return;
}
fireServiceRevoked(event);
Object childs[] = copyChildren();
for (int i = 0; i < childs.length; i++) {
if (childs[i] instanceof BeanContextServices) {
((BeanContextServices) childs[i]).serviceRevoked(event);
}
}
}
/**
* The implementation goes through following steps:
* <p>
* <ol>
* <li>Calls <code>defaultWriteObject()</code>.</li>
* <li>Writes out serializable service listeners.</li>
* </ol>
* </p>
*
* @param oos
* the object output stream
* @throws IOException
* if I/O exception occurs
*/
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
synchronized (bcsListeners) {
serialize(oos, bcsListeners);
}
}
/**
* The implementation goes through following steps:
* <p>
* <ol>
* <li>Calls <code>defaultReadObject()</code>.</li>
* <li>Reads serializable service listeners.</li>
* </ol>
* </p>
*
* @param ois
* the object input stream
* @throws IOException
* if I/O error occurs
* @throws ClassNotFoundException
* if class of read object is not found
*/
private void readObject(ObjectInputStream ois) throws IOException,
ClassNotFoundException {
ois.defaultReadObject();
deserialize(ois, bcsListeners);
}
}
|
googleapis/google-cloud-java | 37,658 | java-saasservicemgmt/google-cloud-saasservicemgmt/src/main/java/com/google/cloud/saasplatform/saasservicemgmt/v1beta1/stub/SaasRolloutsStubSettings.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.saasplatform.saasservicemgmt.v1beta1.stub;
import static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.SaasRolloutsClient.ListLocationsPagedResponse;
import static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.SaasRolloutsClient.ListRolloutKindsPagedResponse;
import static com.google.cloud.saasplatform.saasservicemgmt.v1beta1.SaasRolloutsClient.ListRolloutsPagedResponse;
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.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
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.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.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CreateRolloutKindRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.CreateRolloutRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.DeleteRolloutKindRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.DeleteRolloutRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.GetRolloutKindRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.GetRolloutRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.ListRolloutKindsRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.ListRolloutKindsResponse;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.ListRolloutsRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.ListRolloutsResponse;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.Rollout;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.RolloutKind;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UpdateRolloutKindRequest;
import com.google.cloud.saasplatform.saasservicemgmt.v1beta1.UpdateRolloutRequest;
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.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 SaasRolloutsStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (saasservicemgmt.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 getRollout:
*
* <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
* SaasRolloutsStubSettings.Builder saasRolloutsSettingsBuilder =
* SaasRolloutsStubSettings.newBuilder();
* saasRolloutsSettingsBuilder
* .getRolloutSettings()
* .setRetrySettings(
* saasRolloutsSettingsBuilder
* .getRolloutSettings()
* .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());
* SaasRolloutsStubSettings saasRolloutsSettings = saasRolloutsSettingsBuilder.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.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class SaasRolloutsStubSettings extends StubSettings<SaasRolloutsStubSettings> {
/** 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").build();
private final PagedCallSettings<
ListRolloutsRequest, ListRolloutsResponse, ListRolloutsPagedResponse>
listRolloutsSettings;
private final UnaryCallSettings<GetRolloutRequest, Rollout> getRolloutSettings;
private final UnaryCallSettings<CreateRolloutRequest, Rollout> createRolloutSettings;
private final UnaryCallSettings<UpdateRolloutRequest, Rollout> updateRolloutSettings;
private final UnaryCallSettings<DeleteRolloutRequest, Empty> deleteRolloutSettings;
private final PagedCallSettings<
ListRolloutKindsRequest, ListRolloutKindsResponse, ListRolloutKindsPagedResponse>
listRolloutKindsSettings;
private final UnaryCallSettings<GetRolloutKindRequest, RolloutKind> getRolloutKindSettings;
private final UnaryCallSettings<CreateRolloutKindRequest, RolloutKind> createRolloutKindSettings;
private final UnaryCallSettings<UpdateRolloutKindRequest, RolloutKind> updateRolloutKindSettings;
private final UnaryCallSettings<DeleteRolloutKindRequest, Empty> deleteRolloutKindSettings;
private final PagedCallSettings<
ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings;
private final UnaryCallSettings<GetLocationRequest, Location> getLocationSettings;
private static final PagedListDescriptor<ListRolloutsRequest, ListRolloutsResponse, Rollout>
LIST_ROLLOUTS_PAGE_STR_DESC =
new PagedListDescriptor<ListRolloutsRequest, ListRolloutsResponse, Rollout>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListRolloutsRequest injectToken(ListRolloutsRequest payload, String token) {
return ListRolloutsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListRolloutsRequest injectPageSize(ListRolloutsRequest payload, int pageSize) {
return ListRolloutsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListRolloutsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListRolloutsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Rollout> extractResources(ListRolloutsResponse payload) {
return payload.getRolloutsList();
}
};
private static final PagedListDescriptor<
ListRolloutKindsRequest, ListRolloutKindsResponse, RolloutKind>
LIST_ROLLOUT_KINDS_PAGE_STR_DESC =
new PagedListDescriptor<
ListRolloutKindsRequest, ListRolloutKindsResponse, RolloutKind>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListRolloutKindsRequest injectToken(
ListRolloutKindsRequest payload, String token) {
return ListRolloutKindsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListRolloutKindsRequest injectPageSize(
ListRolloutKindsRequest payload, int pageSize) {
return ListRolloutKindsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListRolloutKindsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListRolloutKindsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<RolloutKind> extractResources(ListRolloutKindsResponse payload) {
return payload.getRolloutKindsList();
}
};
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<
ListRolloutsRequest, ListRolloutsResponse, ListRolloutsPagedResponse>
LIST_ROLLOUTS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListRolloutsRequest, ListRolloutsResponse, ListRolloutsPagedResponse>() {
@Override
public ApiFuture<ListRolloutsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListRolloutsRequest, ListRolloutsResponse> callable,
ListRolloutsRequest request,
ApiCallContext context,
ApiFuture<ListRolloutsResponse> futureResponse) {
PageContext<ListRolloutsRequest, ListRolloutsResponse, Rollout> pageContext =
PageContext.create(callable, LIST_ROLLOUTS_PAGE_STR_DESC, request, context);
return ListRolloutsPagedResponse.createAsync(pageContext, futureResponse);
}
};
private static final PagedListResponseFactory<
ListRolloutKindsRequest, ListRolloutKindsResponse, ListRolloutKindsPagedResponse>
LIST_ROLLOUT_KINDS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListRolloutKindsRequest, ListRolloutKindsResponse, ListRolloutKindsPagedResponse>() {
@Override
public ApiFuture<ListRolloutKindsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListRolloutKindsRequest, ListRolloutKindsResponse> callable,
ListRolloutKindsRequest request,
ApiCallContext context,
ApiFuture<ListRolloutKindsResponse> futureResponse) {
PageContext<ListRolloutKindsRequest, ListRolloutKindsResponse, RolloutKind>
pageContext =
PageContext.create(
callable, LIST_ROLLOUT_KINDS_PAGE_STR_DESC, request, context);
return ListRolloutKindsPagedResponse.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 listRollouts. */
public PagedCallSettings<ListRolloutsRequest, ListRolloutsResponse, ListRolloutsPagedResponse>
listRolloutsSettings() {
return listRolloutsSettings;
}
/** Returns the object with the settings used for calls to getRollout. */
public UnaryCallSettings<GetRolloutRequest, Rollout> getRolloutSettings() {
return getRolloutSettings;
}
/** Returns the object with the settings used for calls to createRollout. */
public UnaryCallSettings<CreateRolloutRequest, Rollout> createRolloutSettings() {
return createRolloutSettings;
}
/** Returns the object with the settings used for calls to updateRollout. */
public UnaryCallSettings<UpdateRolloutRequest, Rollout> updateRolloutSettings() {
return updateRolloutSettings;
}
/** Returns the object with the settings used for calls to deleteRollout. */
public UnaryCallSettings<DeleteRolloutRequest, Empty> deleteRolloutSettings() {
return deleteRolloutSettings;
}
/** Returns the object with the settings used for calls to listRolloutKinds. */
public PagedCallSettings<
ListRolloutKindsRequest, ListRolloutKindsResponse, ListRolloutKindsPagedResponse>
listRolloutKindsSettings() {
return listRolloutKindsSettings;
}
/** Returns the object with the settings used for calls to getRolloutKind. */
public UnaryCallSettings<GetRolloutKindRequest, RolloutKind> getRolloutKindSettings() {
return getRolloutKindSettings;
}
/** Returns the object with the settings used for calls to createRolloutKind. */
public UnaryCallSettings<CreateRolloutKindRequest, RolloutKind> createRolloutKindSettings() {
return createRolloutKindSettings;
}
/** Returns the object with the settings used for calls to updateRolloutKind. */
public UnaryCallSettings<UpdateRolloutKindRequest, RolloutKind> updateRolloutKindSettings() {
return updateRolloutKindSettings;
}
/** Returns the object with the settings used for calls to deleteRolloutKind. */
public UnaryCallSettings<DeleteRolloutKindRequest, Empty> deleteRolloutKindSettings() {
return deleteRolloutKindSettings;
}
/** 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 SaasRolloutsStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcSaasRolloutsStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonSaasRolloutsStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "saasservicemgmt";
}
/** 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 "saasservicemgmt.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "saasservicemgmt.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(SaasRolloutsStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(SaasRolloutsStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return SaasRolloutsStubSettings.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 SaasRolloutsStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
listRolloutsSettings = settingsBuilder.listRolloutsSettings().build();
getRolloutSettings = settingsBuilder.getRolloutSettings().build();
createRolloutSettings = settingsBuilder.createRolloutSettings().build();
updateRolloutSettings = settingsBuilder.updateRolloutSettings().build();
deleteRolloutSettings = settingsBuilder.deleteRolloutSettings().build();
listRolloutKindsSettings = settingsBuilder.listRolloutKindsSettings().build();
getRolloutKindSettings = settingsBuilder.getRolloutKindSettings().build();
createRolloutKindSettings = settingsBuilder.createRolloutKindSettings().build();
updateRolloutKindSettings = settingsBuilder.updateRolloutKindSettings().build();
deleteRolloutKindSettings = settingsBuilder.deleteRolloutKindSettings().build();
listLocationsSettings = settingsBuilder.listLocationsSettings().build();
getLocationSettings = settingsBuilder.getLocationSettings().build();
}
/** Builder for SaasRolloutsStubSettings. */
public static class Builder extends StubSettings.Builder<SaasRolloutsStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final PagedCallSettings.Builder<
ListRolloutsRequest, ListRolloutsResponse, ListRolloutsPagedResponse>
listRolloutsSettings;
private final UnaryCallSettings.Builder<GetRolloutRequest, Rollout> getRolloutSettings;
private final UnaryCallSettings.Builder<CreateRolloutRequest, Rollout> createRolloutSettings;
private final UnaryCallSettings.Builder<UpdateRolloutRequest, Rollout> updateRolloutSettings;
private final UnaryCallSettings.Builder<DeleteRolloutRequest, Empty> deleteRolloutSettings;
private final PagedCallSettings.Builder<
ListRolloutKindsRequest, ListRolloutKindsResponse, ListRolloutKindsPagedResponse>
listRolloutKindsSettings;
private final UnaryCallSettings.Builder<GetRolloutKindRequest, RolloutKind>
getRolloutKindSettings;
private final UnaryCallSettings.Builder<CreateRolloutKindRequest, RolloutKind>
createRolloutKindSettings;
private final UnaryCallSettings.Builder<UpdateRolloutKindRequest, RolloutKind>
updateRolloutKindSettings;
private final UnaryCallSettings.Builder<DeleteRolloutKindRequest, Empty>
deleteRolloutKindSettings;
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_2_codes",
ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE)));
definitions.put(
"no_retry_6_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
definitions.put(
"retry_policy_3_codes",
ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE)));
definitions.put("no_retry_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(1000L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(10000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("retry_policy_2_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("no_retry_6_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(1000L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(10000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(540000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(540000L))
.setTotalTimeoutDuration(Duration.ofMillis(540000L))
.build();
definitions.put("retry_policy_3_params", settings);
settings = RetrySettings.newBuilder().setRpcTimeoutMultiplier(1.0).build();
definitions.put("no_retry_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
listRolloutsSettings = PagedCallSettings.newBuilder(LIST_ROLLOUTS_PAGE_STR_FACT);
getRolloutSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createRolloutSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateRolloutSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteRolloutSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listRolloutKindsSettings = PagedCallSettings.newBuilder(LIST_ROLLOUT_KINDS_PAGE_STR_FACT);
getRolloutKindSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createRolloutKindSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateRolloutKindSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteRolloutKindSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listLocationsSettings = PagedCallSettings.newBuilder(LIST_LOCATIONS_PAGE_STR_FACT);
getLocationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listRolloutsSettings,
getRolloutSettings,
createRolloutSettings,
updateRolloutSettings,
deleteRolloutSettings,
listRolloutKindsSettings,
getRolloutKindSettings,
createRolloutKindSettings,
updateRolloutKindSettings,
deleteRolloutKindSettings,
listLocationsSettings,
getLocationSettings);
initDefaults(this);
}
protected Builder(SaasRolloutsStubSettings settings) {
super(settings);
listRolloutsSettings = settings.listRolloutsSettings.toBuilder();
getRolloutSettings = settings.getRolloutSettings.toBuilder();
createRolloutSettings = settings.createRolloutSettings.toBuilder();
updateRolloutSettings = settings.updateRolloutSettings.toBuilder();
deleteRolloutSettings = settings.deleteRolloutSettings.toBuilder();
listRolloutKindsSettings = settings.listRolloutKindsSettings.toBuilder();
getRolloutKindSettings = settings.getRolloutKindSettings.toBuilder();
createRolloutKindSettings = settings.createRolloutKindSettings.toBuilder();
updateRolloutKindSettings = settings.updateRolloutKindSettings.toBuilder();
deleteRolloutKindSettings = settings.deleteRolloutKindSettings.toBuilder();
listLocationsSettings = settings.listLocationsSettings.toBuilder();
getLocationSettings = settings.getLocationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listRolloutsSettings,
getRolloutSettings,
createRolloutSettings,
updateRolloutSettings,
deleteRolloutSettings,
listRolloutKindsSettings,
getRolloutKindSettings,
createRolloutKindSettings,
updateRolloutKindSettings,
deleteRolloutKindSettings,
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
.listRolloutsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params"));
builder
.getRolloutSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params"));
builder
.createRolloutSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_6_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_6_params"));
builder
.updateRolloutSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_6_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_6_params"));
builder
.deleteRolloutSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_3_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_3_params"));
builder
.listRolloutKindsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params"));
builder
.getRolloutKindSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params"));
builder
.createRolloutKindSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_6_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_6_params"));
builder
.updateRolloutKindSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_6_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_6_params"));
builder
.deleteRolloutKindSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_2_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_2_params"));
builder
.listLocationsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.getLocationSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
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 listRollouts. */
public PagedCallSettings.Builder<
ListRolloutsRequest, ListRolloutsResponse, ListRolloutsPagedResponse>
listRolloutsSettings() {
return listRolloutsSettings;
}
/** Returns the builder for the settings used for calls to getRollout. */
public UnaryCallSettings.Builder<GetRolloutRequest, Rollout> getRolloutSettings() {
return getRolloutSettings;
}
/** Returns the builder for the settings used for calls to createRollout. */
public UnaryCallSettings.Builder<CreateRolloutRequest, Rollout> createRolloutSettings() {
return createRolloutSettings;
}
/** Returns the builder for the settings used for calls to updateRollout. */
public UnaryCallSettings.Builder<UpdateRolloutRequest, Rollout> updateRolloutSettings() {
return updateRolloutSettings;
}
/** Returns the builder for the settings used for calls to deleteRollout. */
public UnaryCallSettings.Builder<DeleteRolloutRequest, Empty> deleteRolloutSettings() {
return deleteRolloutSettings;
}
/** Returns the builder for the settings used for calls to listRolloutKinds. */
public PagedCallSettings.Builder<
ListRolloutKindsRequest, ListRolloutKindsResponse, ListRolloutKindsPagedResponse>
listRolloutKindsSettings() {
return listRolloutKindsSettings;
}
/** Returns the builder for the settings used for calls to getRolloutKind. */
public UnaryCallSettings.Builder<GetRolloutKindRequest, RolloutKind> getRolloutKindSettings() {
return getRolloutKindSettings;
}
/** Returns the builder for the settings used for calls to createRolloutKind. */
public UnaryCallSettings.Builder<CreateRolloutKindRequest, RolloutKind>
createRolloutKindSettings() {
return createRolloutKindSettings;
}
/** Returns the builder for the settings used for calls to updateRolloutKind. */
public UnaryCallSettings.Builder<UpdateRolloutKindRequest, RolloutKind>
updateRolloutKindSettings() {
return updateRolloutKindSettings;
}
/** Returns the builder for the settings used for calls to deleteRolloutKind. */
public UnaryCallSettings.Builder<DeleteRolloutKindRequest, Empty> deleteRolloutKindSettings() {
return deleteRolloutKindSettings;
}
/** 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 SaasRolloutsStubSettings build() throws IOException {
return new SaasRolloutsStubSettings(this);
}
}
}
|
apache/tez | 37,426 | tez-tools/analyzers/job-analyzer/src/test/java/org/apache/tez/analyzer/TestAnalyzer.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.tez.analyzer;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.tez.analyzer.plugins.CriticalPathAnalyzer;
import org.apache.tez.analyzer.plugins.CriticalPathAnalyzer.CriticalPathDependency;
import org.apache.tez.analyzer.plugins.CriticalPathAnalyzer.CriticalPathStep;
import org.apache.tez.analyzer.plugins.CriticalPathAnalyzer.CriticalPathStep.EntityType;
import org.apache.tez.client.TezClient;
import org.apache.tez.dag.api.DAG;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.TezConstants;
import org.apache.tez.dag.api.client.DAGClient;
import org.apache.tez.dag.api.client.DAGStatus;
import org.apache.tez.dag.history.logging.ats.ATSHistoryLoggingService;
import org.apache.tez.dag.history.logging.impl.SimpleHistoryLoggingService;
import org.apache.tez.dag.records.TaskAttemptTerminationCause;
import org.apache.tez.dag.records.TezDAGID;
import org.apache.tez.history.ATSImportTool;
import org.apache.tez.history.parser.ATSFileParser;
import org.apache.tez.history.parser.SimpleHistoryParser;
import org.apache.tez.history.parser.datamodel.DagInfo;
import org.apache.tez.test.SimpleTestDAG;
import org.apache.tez.test.SimpleTestDAG3Vertices;
import org.apache.tez.test.TestInput;
import org.apache.tez.test.TestProcessor;
import org.apache.tez.test.dag.SimpleReverseVTestDAG;
import org.apache.tez.test.dag.SimpleVTestDAG;
import org.apache.tez.tests.MiniTezClusterWithTimeline;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAnalyzer {
private static final Logger LOG = LoggerFactory.getLogger(TestAnalyzer.class);
private static String TEST_ROOT_DIR =
"target" + Path.SEPARATOR + TestAnalyzer.class.getName() + "-tmpDir";
private static String DOWNLOAD_DIR = TEST_ROOT_DIR + Path.SEPARATOR + "download";
private final static String SIMPLE_HISTORY_DIR = "/tmp/simplehistory/";
private final static String HISTORY_TXT = "history.txt";
private static MiniDFSCluster dfsCluster;
private static MiniTezClusterWithTimeline miniTezCluster;
private static Configuration conf = new Configuration();
private static FileSystem fs;
private static TezClient tezSession = null;
private boolean usingATS = true;
private boolean downloadedSimpleHistoryFile = false;
private static String yarnTimelineAddress;
@BeforeClass
public static void setupClass() throws Exception {
conf = new Configuration();
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_EDITS_NOEDITLOGCHANNELFLUSH, false);
EditLogFileOutputStream.setShouldSkipFsyncForTesting(true);
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, TEST_ROOT_DIR);
dfsCluster =
new MiniDFSCluster.Builder(conf).numDataNodes(1).format(true).build();
fs = dfsCluster.getFileSystem();
conf.set("fs.defaultFS", fs.getUri().toString());
setupTezCluster();
}
@AfterClass
public static void tearDownClass() throws Exception {
LOG.info("Stopping mini clusters");
if (miniTezCluster != null) {
miniTezCluster.stop();
miniTezCluster = null;
}
if (dfsCluster != null) {
dfsCluster.shutdown();
dfsCluster = null;
}
}
private CriticalPathAnalyzer setupCPAnalyzer() {
Configuration analyzerConf = new Configuration(false);
analyzerConf.setBoolean(CriticalPathAnalyzer.DRAW_SVG, false);
CriticalPathAnalyzer cp = new CriticalPathAnalyzer();
cp.setConf(analyzerConf);
return cp;
}
private static void setupTezCluster() throws Exception {
// make the test run faster by speeding heartbeat frequency
conf.setInt(YarnConfiguration.RM_NM_HEARTBEAT_INTERVAL_MS, 100);
conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true);
conf.setBoolean(TezConfiguration.TEZ_AM_ALLOW_DISABLED_TIMELINE_DOMAINS, true);
conf.set(TezConfiguration.TEZ_HISTORY_LOGGING_SERVICE_CLASS, ATSHistoryLoggingService
.class.getName());
miniTezCluster =
new MiniTezClusterWithTimeline(TestAnalyzer.class.getName(), 1, 1, 1, true);
miniTezCluster.init(conf);
miniTezCluster.start();
yarnTimelineAddress = miniTezCluster.getConfig().get(YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS);
}
private TezConfiguration createCommonTezLog() throws Exception {
TezConfiguration tezConf = new TezConfiguration(miniTezCluster.getConfig());
tezConf.setInt(TezConfiguration.TEZ_AM_RM_HEARTBEAT_INTERVAL_MS_MAX, 100);
Path remoteStagingDir = dfsCluster.getFileSystem().makeQualified(new Path(TEST_ROOT_DIR, String
.valueOf(new Random().nextInt(100000))));
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR,
remoteStagingDir.toString());
tezConf.setBoolean(TezConfiguration.TEZ_AM_NODE_BLACKLISTING_ENABLED, false);
return tezConf;
}
private void createTezSessionATS() throws Exception {
TezConfiguration tezConf = createCommonTezLog();
tezConf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true);
tezConf.set(YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS,
miniTezCluster.getConfig().get(YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS));
tezConf.setBoolean(TezConfiguration.TEZ_AM_ALLOW_DISABLED_TIMELINE_DOMAINS, true);
tezConf.set(TezConfiguration.TEZ_HISTORY_LOGGING_SERVICE_CLASS,
ATSHistoryLoggingService.class.getName());
Path remoteStagingDir = dfsCluster.getFileSystem().makeQualified(new Path(TEST_ROOT_DIR, String
.valueOf(new Random().nextInt(100000))));
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR,
remoteStagingDir.toString());
tezConf.setBoolean(TezConfiguration.TEZ_AM_NODE_BLACKLISTING_ENABLED, false);
tezSession = TezClient.create("TestAnalyzer", tezConf, true);
tezSession.start();
}
private void createTezSessionSimpleHistory() throws Exception {
TezConfiguration tezConf = createCommonTezLog();
tezConf.set(TezConfiguration.TEZ_HISTORY_LOGGING_SERVICE_CLASS,
SimpleHistoryLoggingService.class.getName());
tezConf.set(TezConfiguration.TEZ_SIMPLE_HISTORY_LOGGING_DIR, SIMPLE_HISTORY_DIR);
Path remoteStagingDir = dfsCluster.getFileSystem().makeQualified(new Path(TEST_ROOT_DIR, String
.valueOf(new Random().nextInt(100000))));
tezConf.set(TezConfiguration.TEZ_AM_STAGING_DIR,
remoteStagingDir.toString());
tezConf.setBoolean(TezConfiguration.TEZ_AM_NODE_BLACKLISTING_ENABLED, false);
tezSession = TezClient.create("TestFaultTolerance", tezConf, true);
tezSession.start();
}
private StepCheck createStep(String attempt, CriticalPathDependency reason) {
return createStep(attempt, reason, null, null);
}
private StepCheck createStep(String attempt, CriticalPathDependency reason,
TaskAttemptTerminationCause errCause, List<String> notes) {
return new StepCheck(attempt, reason, errCause, notes);
}
private class StepCheck {
String attempt; // attempt is the TaskAttemptInfo short name with regex
CriticalPathDependency reason;
TaskAttemptTerminationCause errCause;
List<String> notesStr;
StepCheck(String attempt, CriticalPathDependency reason,
TaskAttemptTerminationCause cause, List<String> notes) {
this.attempt = attempt;
this.reason = reason;
this.errCause = cause;
this.notesStr = notes;
}
String getAttemptDetail() {
return attempt;
}
CriticalPathDependency getReason() {
return reason;
}
TaskAttemptTerminationCause getErrCause() {
return errCause;
}
List<String> getNotesStr() {
return notesStr;
}
}
private void runDAG(DAG dag, DAGStatus.State finalState) throws Exception {
tezSession.waitTillReady();
LOG.info("ABC Running DAG name: " + dag.getName());
DAGClient dagClient = tezSession.submitDAG(dag);
DAGStatus dagStatus = dagClient.getDAGStatus(null);
while (!dagStatus.isCompleted()) {
LOG.info("Waiting for dag to complete. Sleeping for 500ms."
+ " DAG name: " + dag.getName()
+ " DAG appContext: " + dagClient.getExecutionContext()
+ " Current state: " + dagStatus.getState());
Thread.sleep(100);
dagStatus = dagClient.getDAGStatus(null);
}
Assert.assertEquals(finalState, dagStatus.getState());
}
private void verify(ApplicationId appId, int dagNum, List<StepCheck[]> steps) throws Exception {
String dagId = TezDAGID.getInstance(appId, dagNum).toString();
DagInfo dagInfo = getDagInfo(dagId);
verifyCriticalPath(dagInfo, steps);
}
private DagInfo getDagInfo(String dagId) throws Exception {
// sleep for a bit to let ATS events be sent from AM
DagInfo dagInfo = null;
if (usingATS) {
//Export the data from ATS
String[] args = { "--dagId=" + dagId, "--downloadDir=" + DOWNLOAD_DIR, "--yarnTimelineAddress=" + yarnTimelineAddress };
int result = ATSImportTool.process(args);
assertTrue(result == 0);
//Parse ATS data and verify results
//Parse downloaded contents
File downloadedFile = new File(DOWNLOAD_DIR
+ Path.SEPARATOR + dagId + ".zip");
ATSFileParser parser = new ATSFileParser(Arrays.asList(downloadedFile));
dagInfo = parser.getDAGData(dagId);
assertTrue(dagInfo.getDagId().equals(dagId));
} else {
if (!downloadedSimpleHistoryFile) {
downloadedSimpleHistoryFile = true;
TezDAGID tezDAGID = TezDAGID.fromString(dagId);
ApplicationAttemptId applicationAttemptId = ApplicationAttemptId.newInstance(tezDAGID
.getApplicationId(), 1);
Path historyPath = new Path(miniTezCluster.getConfig().get("fs.defaultFS")
+ SIMPLE_HISTORY_DIR + HISTORY_TXT + "."
+ applicationAttemptId);
FileSystem fs = historyPath.getFileSystem(miniTezCluster.getConfig());
Path localPath = new Path(DOWNLOAD_DIR, HISTORY_TXT);
fs.copyToLocalFile(historyPath, localPath);
}
//Now parse via SimpleHistory
File localFile = new File(DOWNLOAD_DIR, HISTORY_TXT);
SimpleHistoryParser parser = new SimpleHistoryParser(Arrays.asList(localFile));
dagInfo = parser.getDAGData(dagId);
assertTrue(dagInfo.getDagId().equals(dagId));
}
return dagInfo;
}
private void verifyCriticalPath(DagInfo dagInfo, List<StepCheck[]> stepsOptions) throws Exception {
CriticalPathAnalyzer cp = setupCPAnalyzer();
cp.analyze(dagInfo);
List<CriticalPathStep> criticalPath = cp.getCriticalPath();
for (CriticalPathStep step : criticalPath) {
LOG.info("ABC Step: " + step.getType());
if (step.getType() == EntityType.ATTEMPT) {
LOG.info("ABC Attempt: " + step.getAttempt().getShortName()
+ " " + step.getAttempt().getDetailedStatus());
}
LOG.info("ABC Reason: " + step.getReason());
String notes = Joiner.on(";").join(step.getNotes());
LOG.info("ABC Notes: " + notes);
}
boolean foundMatchingLength = false;
for (StepCheck[] steps : stepsOptions) {
if (steps.length + 2 == criticalPath.size()) {
foundMatchingLength = true;
Assert.assertEquals(CriticalPathStep.EntityType.VERTEX_INIT, criticalPath.get(0).getType());
Assert.assertEquals(criticalPath.get(1).getAttempt().getShortName(),
criticalPath.get(0).getAttempt().getShortName());
for (int i=1; i<criticalPath.size() - 1; ++i) {
StepCheck check = steps[i-1];
CriticalPathStep step = criticalPath.get(i);
Assert.assertEquals(CriticalPathStep.EntityType.ATTEMPT, step.getType());
Assert.assertTrue(check.getAttemptDetail(),
step.getAttempt().getShortName().matches(check.getAttemptDetail()));
Assert.assertEquals(steps[i-1].getReason(), step.getReason());
if (check.getErrCause() != null) {
Assert.assertEquals(check.getErrCause(),
TaskAttemptTerminationCause.valueOf(step.getAttempt().getTerminationCause()));
}
if (check.getNotesStr() != null) {
String notes = Joiner.on("#").join(step.getNotes());
for (String note : check.getNotesStr()) {
Assert.assertTrue(note, notes.contains(notes));
}
}
}
Assert.assertEquals(CriticalPathStep.EntityType.DAG_COMMIT,
criticalPath.get(criticalPath.size() - 1).getType());
break;
}
}
Assert.assertTrue(foundMatchingLength);
}
@Test (timeout=300000)
public void testWithATS() throws Exception {
usingATS = true;
createTezSessionATS();
runTests();
}
@Test (timeout=300000)
public void testWithSimpleHistory() throws Exception {
usingATS = false;
createTezSessionSimpleHistory();
runTests();
}
private void runTests() throws Exception {
ApplicationId appId = tezSession.getAppMasterApplicationId();
List<List<StepCheck[]>> stepsOptions = Lists.newArrayList();
// run all test dags
stepsOptions.add(testAttemptOfDownstreamVertexConnectedWithTwoUpstreamVerticesFailure());
stepsOptions.add(testInputFailureCausesRerunOfTwoVerticesWithoutExit());
stepsOptions.add(testMultiVersionInputFailureWithoutExit());
stepsOptions.add(testCascadingInputFailureWithoutExitSuccess());
stepsOptions.add(testTaskMultipleFailures());
stepsOptions.add(testBasicInputFailureWithoutExit());
stepsOptions.add(testBasicTaskFailure());
stepsOptions.add(testBasicSuccessScatterGather());
stepsOptions.add(testMultiVersionInputFailureWithExit());
stepsOptions.add(testBasicInputFailureWithExit());
stepsOptions.add(testInputFailureRerunCanSendOutputToTwoDownstreamVertices());
stepsOptions.add(testCascadingInputFailureWithExitSuccess());
stepsOptions.add(testInternalPreemption());
// close session to flush
if (tezSession != null) {
tezSession.stop();
}
Thread.sleep((TezConstants.TEZ_DAG_SLEEP_TIME_BEFORE_EXIT*3)/2);
// verify all dags
for (int i=0; i<stepsOptions.size(); ++i) {
verify(appId, i+1, stepsOptions.get(i));
}
}
private List<StepCheck[]> testBasicSuccessScatterGather() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY)
};
DAG dag = SimpleTestDAG.createDAG("testBasicSuccessScatterGather", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
private List<StepCheck[]> testBasicTaskFailure() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_DO_FAIL, "v1"), true);
testConf.set(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_FAILING_TASK_INDEX, "v1"), "0");
testConf.setInt(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_FAILING_UPTO_TASK_ATTEMPT, "v1"), 0);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.RETRY_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG.createDAG("testBasicTaskFailure", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
private List<StepCheck[]> testTaskMultipleFailures() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_DO_FAIL, "v1"), true);
testConf.set(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_FAILING_TASK_INDEX, "v1"), "0");
testConf.setInt(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_FAILING_UPTO_TASK_ATTEMPT, "v1"), 1);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.RETRY_DEPENDENCY),
createStep("v1 : 000000_2", CriticalPathDependency.RETRY_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG.createDAG("testTaskMultipleFailures", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
private List<StepCheck[]> testBasicInputFailureWithExit() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v2"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v2"), true);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v2"), "0");
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_1", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG.createDAG("testBasicInputFailureWithExit", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
private List<StepCheck[]> testBasicInputFailureWithoutExit() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v2"), true);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v2"), "0");
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG.createDAG("testBasicInputFailureWithoutExit", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
private List<StepCheck[]> testMultiVersionInputFailureWithExit() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v2"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v2"), true);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v2"), "0,1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v2"), "0");
testConf.setInt(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v2"), 1);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_1", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_2", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_2", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG.createDAG("testMultiVersionInputFailureWithExit", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
private List<StepCheck[]> testMultiVersionInputFailureWithoutExit() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleTestDAG.TEZ_SIMPLE_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v2"), true);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v2"), "0");
testConf.setInt(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v2"), 1);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_2", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG.createDAG("testMultiVersionInputFailureWithoutExit", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
/**
* Sets configuration for cascading input failure tests that
* use SimpleTestDAG3Vertices.
* @param testConf configuration
* @param failAndExit whether input failure should trigger attempt exit
*/
private void setCascadingInputFailureConfig(Configuration testConf,
boolean failAndExit,
int numTasks) {
// v2 attempt0 succeeds.
// v2 all tasks attempt1 input0 fail up to version 0.
testConf.setInt(SimpleTestDAG3Vertices.TEZ_SIMPLE_DAG_NUM_TASKS, numTasks);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v2"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v2"), failAndExit);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v2"), "-1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v2"), "1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v2"), "0");
testConf.setInt(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v2"),
0);
//v3 task0 attempt0 all inputs fails up to version 0.
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v3"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v3"), failAndExit);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v3"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v3"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v3"), "-1");
testConf.setInt(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v3"),
0);
}
/**
* Test cascading input failure without exit. Expecting success.
* v1 -- v2 -- v3
* v3 all-tasks attempt0 input0 fails. Wait. Triggering v2 rerun.
* v2 task0 attempt1 input0 fails. Wait. Triggering v1 rerun.
* v1 attempt1 rerun and succeeds. v2 accepts v1 attempt1 output. v2 attempt1 succeeds.
* v3 attempt0 accepts v2 attempt1 output.
*
* AM vertex succeeded order is v1, v2, v1, v2, v3.
* @throws Exception
*/
private List<StepCheck[]> testCascadingInputFailureWithoutExitSuccess() throws Exception {
Configuration testConf = new Configuration(false);
setCascadingInputFailureConfig(testConf, false, 1);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v2 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_1", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG3Vertices.createDAG(
"testCascadingInputFailureWithoutExitSuccess", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
/**
* Test cascading input failure with exit. Expecting success.
* v1 -- v2 -- v3
* v3 all-tasks attempt0 input0 fails. v3 attempt0 exits. Triggering v2 rerun.
* v2 task0 attempt1 input0 fails. v2 attempt1 exits. Triggering v1 rerun.
* v1 attempt1 rerun and succeeds. v2 accepts v1 attempt1 output. v2 attempt2 succeeds.
* v3 attempt1 accepts v2 attempt2 output.
*
* AM vertex succeeded order is v1, v2, v3, v1, v2, v3.
* @throws Exception
*/
private List<StepCheck[]> testCascadingInputFailureWithExitSuccess() throws Exception {
Configuration testConf = new Configuration(false);
setCascadingInputFailureConfig(testConf, true, 1);
StepCheck[] check = {
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v2 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v2 : 000000_2", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_1", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleTestDAG3Vertices.createDAG(
"testCascadingInputFailureWithExitSuccess", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
/**
* 1 NM is running and can run 4 containers based on YARN mini cluster defaults and
* Tez defaults for AM/task memory
* v3 task0 reports read errors against both tasks of v2. This re-starts both of them.
* Now all 4 slots are occupied 1 AM + 3 tasks
* Now retries of v2 report read error against 1 task of v1. That re-starts.
* Retry of v1 task has no space - so it preempts the least priority task (current tez logic)
* v3 is preempted and re-run. Shows up on critical path as preempted failure.
* Also v1 retry attempts note show that it caused preemption of v3
* @throws Exception
*/
private List<StepCheck[]> testInternalPreemption() throws Exception {
Configuration testConf = new Configuration(false);
setCascadingInputFailureConfig(testConf, false, 2);
StepCheck[] check = {
createStep("v1 : 00000[01]_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v2 : 00000[01]_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY,
TaskAttemptTerminationCause.INTERNAL_PREEMPTION, null),
createStep("v2 : 00000[01]_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY,
null, Collections.singletonList("preemption of v3")),
createStep("v2 : 00000[01]_[12]", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_1", CriticalPathDependency.DATA_DEPENDENCY)
};
DAG dag = SimpleTestDAG3Vertices.createDAG(
"testInternalPreemption", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
/**
* Input failure of v3 causes rerun of both both v1 and v2 vertices.
* v1 v2
* \ /
* v3
*
* @throws Exception
*/
private List<StepCheck[]> testInputFailureCausesRerunOfTwoVerticesWithoutExit() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleVTestDAG.TEZ_SIMPLE_V_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v3"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v3"), false);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v3"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v3"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v3"), "-1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v3"), "1");
StepCheck[] check = {
// use regex for either vertices being possible on the path
createStep("v[12] : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v[12] : 000000_[01]", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v[12] : 000000_[012]", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v[12] : 000000_[12]", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v[12] : 000000_2", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleVTestDAG.createDAG(
"testInputFailureCausesRerunOfTwoVerticesWithoutExit", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
/**
* Downstream(v3) attempt failure of a vertex connected with
* 2 upstream vertices..
* v1 v2
* \ /
* v3
*
* @throws Exception
*/
private List<StepCheck[]> testAttemptOfDownstreamVertexConnectedWithTwoUpstreamVerticesFailure()
throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleVTestDAG.TEZ_SIMPLE_V_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_DO_FAIL, "v3"), true);
testConf.set(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_FAILING_TASK_INDEX, "v3"), "0");
testConf.setInt(TestProcessor.getVertexConfName(
TestProcessor.TEZ_FAILING_PROCESSOR_FAILING_UPTO_TASK_ATTEMPT, "v3"), 1);
StepCheck[] check = {
// use regex for either vertices being possible on the path
createStep("v[12] : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v3 : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v3 : 000000_1", CriticalPathDependency.RETRY_DEPENDENCY),
createStep("v3 : 000000_2", CriticalPathDependency.RETRY_DEPENDENCY),
};
DAG dag = SimpleVTestDAG.createDAG(
"testAttemptOfDownstreamVertexConnectedWithTwoUpstreamVerticesFailure", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
/**
* Input failure of v2,v3 trigger v1 rerun.
* Both v2 and v3 report error on v1 and dont exit. So one of them triggers next
* version of v1 and also consume the output of the next version. While the other
* consumes the output of the next version of v1.
* Reruns can send output to 2 downstream vertices.
* v1
* / \
* v2 v3
*
* Also covers multiple consumer vertices report failure against same producer task.
* @throws Exception
*/
private List<StepCheck[]> testInputFailureRerunCanSendOutputToTwoDownstreamVertices() throws Exception {
Configuration testConf = new Configuration(false);
testConf.setInt(SimpleReverseVTestDAG.TEZ_SIMPLE_REVERSE_V_DAG_NUM_TASKS, 1);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v2"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v2"), false);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v2"), "-1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v2"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v2"), "-1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v2"), "0");
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL, "v3"), true);
testConf.setBoolean(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_DO_FAIL_AND_EXIT, "v3"), false);
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_INDEX, "v3"), "-1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_TASK_ATTEMPT, "v3"), "0");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_INPUT_INDEX, "v3"), "-1");
testConf.set(TestInput.getVertexConfName(
TestInput.TEZ_FAILING_INPUT_FAILING_UPTO_INPUT_ATTEMPT, "v3"), "0");
StepCheck[] check = {
// use regex for either vertices being possible on the path
createStep("v1 : 000000_0", CriticalPathDependency.INIT_DEPENDENCY),
createStep("v[23] : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
createStep("v1 : 000000_1", CriticalPathDependency.OUTPUT_RECREATE_DEPENDENCY),
createStep("v[23] : 000000_0", CriticalPathDependency.DATA_DEPENDENCY),
};
DAG dag = SimpleReverseVTestDAG.createDAG(
"testInputFailureRerunCanSendOutputToTwoDownstreamVertices", testConf);
runDAG(dag, DAGStatus.State.SUCCEEDED);
return Collections.singletonList(check);
}
}
|
googleapis/google-cloud-java | 37,305 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/UserActionReference.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/user_action_reference.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* References an API call. It contains more information about long running
* operation and Jobs that are triggered by the API call.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.UserActionReference}
*/
public final class UserActionReference extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.UserActionReference)
UserActionReferenceOrBuilder {
private static final long serialVersionUID = 0L;
// Use UserActionReference.newBuilder() to construct.
private UserActionReference(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UserActionReference() {
method_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UserActionReference();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.UserActionReferenceProto
.internal_static_google_cloud_aiplatform_v1_UserActionReference_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.UserActionReferenceProto
.internal_static_google_cloud_aiplatform_v1_UserActionReference_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.UserActionReference.class,
com.google.cloud.aiplatform.v1.UserActionReference.Builder.class);
}
private int referenceCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object reference_;
public enum ReferenceCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
OPERATION(1),
DATA_LABELING_JOB(2),
REFERENCE_NOT_SET(0);
private final int value;
private ReferenceCase(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 ReferenceCase valueOf(int value) {
return forNumber(value);
}
public static ReferenceCase forNumber(int value) {
switch (value) {
case 1:
return OPERATION;
case 2:
return DATA_LABELING_JOB;
case 0:
return REFERENCE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public ReferenceCase getReferenceCase() {
return ReferenceCase.forNumber(referenceCase_);
}
public static final int OPERATION_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return referenceCase_ == 1;
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return The operation.
*/
public java.lang.String getOperation() {
java.lang.Object ref = "";
if (referenceCase_ == 1) {
ref = reference_;
}
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 (referenceCase_ == 1) {
reference_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return The bytes for operation.
*/
public com.google.protobuf.ByteString getOperationBytes() {
java.lang.Object ref = "";
if (referenceCase_ == 1) {
ref = reference_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (referenceCase_ == 1) {
reference_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DATA_LABELING_JOB_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return Whether the dataLabelingJob field is set.
*/
public boolean hasDataLabelingJob() {
return referenceCase_ == 2;
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return The dataLabelingJob.
*/
public java.lang.String getDataLabelingJob() {
java.lang.Object ref = "";
if (referenceCase_ == 2) {
ref = reference_;
}
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 (referenceCase_ == 2) {
reference_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return The bytes for dataLabelingJob.
*/
public com.google.protobuf.ByteString getDataLabelingJobBytes() {
java.lang.Object ref = "";
if (referenceCase_ == 2) {
ref = reference_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (referenceCase_ == 2) {
reference_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int METHOD_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object method_ = "";
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @return The method.
*/
@java.lang.Override
public java.lang.String getMethod() {
java.lang.Object ref = method_;
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();
method_ = s;
return s;
}
}
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @return The bytes for method.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMethodBytes() {
java.lang.Object ref = method_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
method_ = 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 (referenceCase_ == 1) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, reference_);
}
if (referenceCase_ == 2) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, reference_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(method_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, method_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (referenceCase_ == 1) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, reference_);
}
if (referenceCase_ == 2) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, reference_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(method_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, method_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.UserActionReference)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.UserActionReference other =
(com.google.cloud.aiplatform.v1.UserActionReference) obj;
if (!getMethod().equals(other.getMethod())) return false;
if (!getReferenceCase().equals(other.getReferenceCase())) return false;
switch (referenceCase_) {
case 1:
if (!getOperation().equals(other.getOperation())) return false;
break;
case 2:
if (!getDataLabelingJob().equals(other.getDataLabelingJob())) 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) + METHOD_FIELD_NUMBER;
hash = (53 * hash) + getMethod().hashCode();
switch (referenceCase_) {
case 1:
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
break;
case 2:
hash = (37 * hash) + DATA_LABELING_JOB_FIELD_NUMBER;
hash = (53 * hash) + getDataLabelingJob().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.UserActionReference parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.aiplatform.v1.UserActionReference 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>
* References an API call. It contains more information about long running
* operation and Jobs that are triggered by the API call.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.UserActionReference}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.UserActionReference)
com.google.cloud.aiplatform.v1.UserActionReferenceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.UserActionReferenceProto
.internal_static_google_cloud_aiplatform_v1_UserActionReference_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.UserActionReferenceProto
.internal_static_google_cloud_aiplatform_v1_UserActionReference_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.UserActionReference.class,
com.google.cloud.aiplatform.v1.UserActionReference.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.UserActionReference.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
method_ = "";
referenceCase_ = 0;
reference_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.UserActionReferenceProto
.internal_static_google_cloud_aiplatform_v1_UserActionReference_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UserActionReference getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.UserActionReference.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UserActionReference build() {
com.google.cloud.aiplatform.v1.UserActionReference result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UserActionReference buildPartial() {
com.google.cloud.aiplatform.v1.UserActionReference result =
new com.google.cloud.aiplatform.v1.UserActionReference(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1.UserActionReference result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.method_ = method_;
}
}
private void buildPartialOneofs(com.google.cloud.aiplatform.v1.UserActionReference result) {
result.referenceCase_ = referenceCase_;
result.reference_ = this.reference_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.UserActionReference) {
return mergeFrom((com.google.cloud.aiplatform.v1.UserActionReference) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.UserActionReference other) {
if (other == com.google.cloud.aiplatform.v1.UserActionReference.getDefaultInstance())
return this;
if (!other.getMethod().isEmpty()) {
method_ = other.method_;
bitField0_ |= 0x00000004;
onChanged();
}
switch (other.getReferenceCase()) {
case OPERATION:
{
referenceCase_ = 1;
reference_ = other.reference_;
onChanged();
break;
}
case DATA_LABELING_JOB:
{
referenceCase_ = 2;
reference_ = other.reference_;
onChanged();
break;
}
case REFERENCE_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:
{
java.lang.String s = input.readStringRequireUtf8();
referenceCase_ = 1;
reference_ = s;
break;
} // case 10
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
referenceCase_ = 2;
reference_ = s;
break;
} // case 18
case 26:
{
method_ = 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 referenceCase_ = 0;
private java.lang.Object reference_;
public ReferenceCase getReferenceCase() {
return ReferenceCase.forNumber(referenceCase_);
}
public Builder clearReference() {
referenceCase_ = 0;
reference_ = null;
onChanged();
return this;
}
private int bitField0_;
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return referenceCase_ == 1;
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return The operation.
*/
@java.lang.Override
public java.lang.String getOperation() {
java.lang.Object ref = "";
if (referenceCase_ == 1) {
ref = reference_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (referenceCase_ == 1) {
reference_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return The bytes for operation.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOperationBytes() {
java.lang.Object ref = "";
if (referenceCase_ == 1) {
ref = reference_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (referenceCase_ == 1) {
reference_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @param value The operation to set.
* @return This builder for chaining.
*/
public Builder setOperation(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
referenceCase_ = 1;
reference_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearOperation() {
if (referenceCase_ == 1) {
referenceCase_ = 0;
reference_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* For API calls that return a long running operation.
* Resource name of the long running operation.
* Format:
* `projects/{project}/locations/{location}/operations/{operation}`
* </pre>
*
* <code>string operation = 1;</code>
*
* @param value The bytes for operation to set.
* @return This builder for chaining.
*/
public Builder setOperationBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
referenceCase_ = 1;
reference_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return Whether the dataLabelingJob field is set.
*/
@java.lang.Override
public boolean hasDataLabelingJob() {
return referenceCase_ == 2;
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return The dataLabelingJob.
*/
@java.lang.Override
public java.lang.String getDataLabelingJob() {
java.lang.Object ref = "";
if (referenceCase_ == 2) {
ref = reference_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (referenceCase_ == 2) {
reference_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return The bytes for dataLabelingJob.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDataLabelingJobBytes() {
java.lang.Object ref = "";
if (referenceCase_ == 2) {
ref = reference_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (referenceCase_ == 2) {
reference_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @param value The dataLabelingJob to set.
* @return This builder for chaining.
*/
public Builder setDataLabelingJob(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
referenceCase_ = 2;
reference_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearDataLabelingJob() {
if (referenceCase_ == 2) {
referenceCase_ = 0;
reference_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* For API calls that start a LabelingJob.
* Resource name of the LabelingJob.
* Format:
* `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}`
* </pre>
*
* <code>string data_labeling_job = 2;</code>
*
* @param value The bytes for dataLabelingJob to set.
* @return This builder for chaining.
*/
public Builder setDataLabelingJobBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
referenceCase_ = 2;
reference_ = value;
onChanged();
return this;
}
private java.lang.Object method_ = "";
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @return The method.
*/
public java.lang.String getMethod() {
java.lang.Object ref = method_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
method_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @return The bytes for method.
*/
public com.google.protobuf.ByteString getMethodBytes() {
java.lang.Object ref = method_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
method_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @param value The method to set.
* @return This builder for chaining.
*/
public Builder setMethod(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
method_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearMethod() {
method_ = getDefaultInstance().getMethod();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The method name of the API RPC call. For example,
* "/google.cloud.aiplatform.{apiVersion}.DatasetService.CreateDataset"
* </pre>
*
* <code>string method = 3;</code>
*
* @param value The bytes for method to set.
* @return This builder for chaining.
*/
public Builder setMethodBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
method_ = 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.aiplatform.v1.UserActionReference)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.UserActionReference)
private static final com.google.cloud.aiplatform.v1.UserActionReference DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.UserActionReference();
}
public static com.google.cloud.aiplatform.v1.UserActionReference getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UserActionReference> PARSER =
new com.google.protobuf.AbstractParser<UserActionReference>() {
@java.lang.Override
public UserActionReference 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<UserActionReference> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UserActionReference> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UserActionReference getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,422 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListCachedContentsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/gen_ai_cache_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Response with a list of CachedContents.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ListCachedContentsResponse}
*/
public final class ListCachedContentsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListCachedContentsResponse)
ListCachedContentsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListCachedContentsResponse.newBuilder() to construct.
private ListCachedContentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListCachedContentsResponse() {
cachedContents_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListCachedContentsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.GenAiCacheServiceProto
.internal_static_google_cloud_aiplatform_v1_ListCachedContentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.GenAiCacheServiceProto
.internal_static_google_cloud_aiplatform_v1_ListCachedContentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ListCachedContentsResponse.class,
com.google.cloud.aiplatform.v1.ListCachedContentsResponse.Builder.class);
}
public static final int CACHED_CONTENTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1.CachedContent> cachedContents_;
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1.CachedContent> getCachedContentsList() {
return cachedContents_;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1.CachedContentOrBuilder>
getCachedContentsOrBuilderList() {
return cachedContents_;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
@java.lang.Override
public int getCachedContentsCount() {
return cachedContents_.size();
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.CachedContent getCachedContents(int index) {
return cachedContents_.get(index);
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.CachedContentOrBuilder getCachedContentsOrBuilder(
int index) {
return cachedContents_.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 < cachedContents_.size(); i++) {
output.writeMessage(1, cachedContents_.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 < cachedContents_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, cachedContents_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.ListCachedContentsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.ListCachedContentsResponse other =
(com.google.cloud.aiplatform.v1.ListCachedContentsResponse) obj;
if (!getCachedContentsList().equals(other.getCachedContentsList())) 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 (getCachedContentsCount() > 0) {
hash = (37 * hash) + CACHED_CONTENTS_FIELD_NUMBER;
hash = (53 * hash) + getCachedContentsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1.ListCachedContentsResponse 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 with a list of CachedContents.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ListCachedContentsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListCachedContentsResponse)
com.google.cloud.aiplatform.v1.ListCachedContentsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.GenAiCacheServiceProto
.internal_static_google_cloud_aiplatform_v1_ListCachedContentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.GenAiCacheServiceProto
.internal_static_google_cloud_aiplatform_v1_ListCachedContentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ListCachedContentsResponse.class,
com.google.cloud.aiplatform.v1.ListCachedContentsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.ListCachedContentsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (cachedContentsBuilder_ == null) {
cachedContents_ = java.util.Collections.emptyList();
} else {
cachedContents_ = null;
cachedContentsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.GenAiCacheServiceProto
.internal_static_google_cloud_aiplatform_v1_ListCachedContentsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListCachedContentsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.ListCachedContentsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListCachedContentsResponse build() {
com.google.cloud.aiplatform.v1.ListCachedContentsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListCachedContentsResponse buildPartial() {
com.google.cloud.aiplatform.v1.ListCachedContentsResponse result =
new com.google.cloud.aiplatform.v1.ListCachedContentsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1.ListCachedContentsResponse result) {
if (cachedContentsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
cachedContents_ = java.util.Collections.unmodifiableList(cachedContents_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.cachedContents_ = cachedContents_;
} else {
result.cachedContents_ = cachedContentsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1.ListCachedContentsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.ListCachedContentsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1.ListCachedContentsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListCachedContentsResponse other) {
if (other == com.google.cloud.aiplatform.v1.ListCachedContentsResponse.getDefaultInstance())
return this;
if (cachedContentsBuilder_ == null) {
if (!other.cachedContents_.isEmpty()) {
if (cachedContents_.isEmpty()) {
cachedContents_ = other.cachedContents_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCachedContentsIsMutable();
cachedContents_.addAll(other.cachedContents_);
}
onChanged();
}
} else {
if (!other.cachedContents_.isEmpty()) {
if (cachedContentsBuilder_.isEmpty()) {
cachedContentsBuilder_.dispose();
cachedContentsBuilder_ = null;
cachedContents_ = other.cachedContents_;
bitField0_ = (bitField0_ & ~0x00000001);
cachedContentsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCachedContentsFieldBuilder()
: null;
} else {
cachedContentsBuilder_.addAllMessages(other.cachedContents_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1.CachedContent m =
input.readMessage(
com.google.cloud.aiplatform.v1.CachedContent.parser(), extensionRegistry);
if (cachedContentsBuilder_ == null) {
ensureCachedContentsIsMutable();
cachedContents_.add(m);
} else {
cachedContentsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1.CachedContent> cachedContents_ =
java.util.Collections.emptyList();
private void ensureCachedContentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
cachedContents_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1.CachedContent>(cachedContents_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.CachedContent,
com.google.cloud.aiplatform.v1.CachedContent.Builder,
com.google.cloud.aiplatform.v1.CachedContentOrBuilder>
cachedContentsBuilder_;
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1.CachedContent> getCachedContentsList() {
if (cachedContentsBuilder_ == null) {
return java.util.Collections.unmodifiableList(cachedContents_);
} else {
return cachedContentsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public int getCachedContentsCount() {
if (cachedContentsBuilder_ == null) {
return cachedContents_.size();
} else {
return cachedContentsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public com.google.cloud.aiplatform.v1.CachedContent getCachedContents(int index) {
if (cachedContentsBuilder_ == null) {
return cachedContents_.get(index);
} else {
return cachedContentsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder setCachedContents(
int index, com.google.cloud.aiplatform.v1.CachedContent value) {
if (cachedContentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCachedContentsIsMutable();
cachedContents_.set(index, value);
onChanged();
} else {
cachedContentsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder setCachedContents(
int index, com.google.cloud.aiplatform.v1.CachedContent.Builder builderForValue) {
if (cachedContentsBuilder_ == null) {
ensureCachedContentsIsMutable();
cachedContents_.set(index, builderForValue.build());
onChanged();
} else {
cachedContentsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder addCachedContents(com.google.cloud.aiplatform.v1.CachedContent value) {
if (cachedContentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCachedContentsIsMutable();
cachedContents_.add(value);
onChanged();
} else {
cachedContentsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder addCachedContents(
int index, com.google.cloud.aiplatform.v1.CachedContent value) {
if (cachedContentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCachedContentsIsMutable();
cachedContents_.add(index, value);
onChanged();
} else {
cachedContentsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder addCachedContents(
com.google.cloud.aiplatform.v1.CachedContent.Builder builderForValue) {
if (cachedContentsBuilder_ == null) {
ensureCachedContentsIsMutable();
cachedContents_.add(builderForValue.build());
onChanged();
} else {
cachedContentsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder addCachedContents(
int index, com.google.cloud.aiplatform.v1.CachedContent.Builder builderForValue) {
if (cachedContentsBuilder_ == null) {
ensureCachedContentsIsMutable();
cachedContents_.add(index, builderForValue.build());
onChanged();
} else {
cachedContentsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder addAllCachedContents(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.CachedContent> values) {
if (cachedContentsBuilder_ == null) {
ensureCachedContentsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, cachedContents_);
onChanged();
} else {
cachedContentsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder clearCachedContents() {
if (cachedContentsBuilder_ == null) {
cachedContents_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
cachedContentsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public Builder removeCachedContents(int index) {
if (cachedContentsBuilder_ == null) {
ensureCachedContentsIsMutable();
cachedContents_.remove(index);
onChanged();
} else {
cachedContentsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public com.google.cloud.aiplatform.v1.CachedContent.Builder getCachedContentsBuilder(
int index) {
return getCachedContentsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public com.google.cloud.aiplatform.v1.CachedContentOrBuilder getCachedContentsOrBuilder(
int index) {
if (cachedContentsBuilder_ == null) {
return cachedContents_.get(index);
} else {
return cachedContentsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1.CachedContentOrBuilder>
getCachedContentsOrBuilderList() {
if (cachedContentsBuilder_ != null) {
return cachedContentsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(cachedContents_);
}
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public com.google.cloud.aiplatform.v1.CachedContent.Builder addCachedContentsBuilder() {
return getCachedContentsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1.CachedContent.getDefaultInstance());
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public com.google.cloud.aiplatform.v1.CachedContent.Builder addCachedContentsBuilder(
int index) {
return getCachedContentsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1.CachedContent.getDefaultInstance());
}
/**
*
*
* <pre>
* List of cached contents.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.CachedContent cached_contents = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1.CachedContent.Builder>
getCachedContentsBuilderList() {
return getCachedContentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.CachedContent,
com.google.cloud.aiplatform.v1.CachedContent.Builder,
com.google.cloud.aiplatform.v1.CachedContentOrBuilder>
getCachedContentsFieldBuilder() {
if (cachedContentsBuilder_ == null) {
cachedContentsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.CachedContent,
com.google.cloud.aiplatform.v1.CachedContent.Builder,
com.google.cloud.aiplatform.v1.CachedContentOrBuilder>(
cachedContents_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
cachedContents_ = null;
}
return cachedContentsBuilder_;
}
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.aiplatform.v1.ListCachedContentsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListCachedContentsResponse)
private static final com.google.cloud.aiplatform.v1.ListCachedContentsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListCachedContentsResponse();
}
public static com.google.cloud.aiplatform.v1.ListCachedContentsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListCachedContentsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListCachedContentsResponse>() {
@java.lang.Override
public ListCachedContentsResponse 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<ListCachedContentsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListCachedContentsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListCachedContentsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hadoop-common | 37,529 | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDecommission.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.client.HdfsDataInputStream;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo.AdminStates;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.ha.HATestUtil;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.test.PathUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* This class tests the decommissioning of nodes.
*/
public class TestDecommission {
public static final Log LOG = LogFactory.getLog(TestDecommission.class);
static final long seed = 0xDEADBEEFL;
static final int blockSize = 8192;
static final int fileSize = 16384;
static final int HEARTBEAT_INTERVAL = 1; // heartbeat interval in seconds
static final int BLOCKREPORT_INTERVAL_MSEC = 1000; //block report in msec
static final int NAMENODE_REPLICATION_INTERVAL = 1; //replication interval
final Random myrand = new Random();
Path dir;
Path hostsFile;
Path excludeFile;
FileSystem localFileSys;
Configuration conf;
MiniDFSCluster cluster = null;
@Before
public void setup() throws IOException {
conf = new HdfsConfiguration();
// Set up the hosts/exclude files.
localFileSys = FileSystem.getLocal(conf);
Path workingDir = localFileSys.getWorkingDirectory();
dir = new Path(workingDir, PathUtils.getTestDirName(getClass()) + "/work-dir/decommission");
hostsFile = new Path(dir, "hosts");
excludeFile = new Path(dir, "exclude");
// Setup conf
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY, false);
conf.set(DFSConfigKeys.DFS_HOSTS, hostsFile.toUri().getPath());
conf.set(DFSConfigKeys.DFS_HOSTS_EXCLUDE, excludeFile.toUri().getPath());
conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 2000);
conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, HEARTBEAT_INTERVAL);
conf.setInt(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, BLOCKREPORT_INTERVAL_MSEC);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_KEY, 4);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, NAMENODE_REPLICATION_INTERVAL);
writeConfigFile(hostsFile, null);
writeConfigFile(excludeFile, null);
}
@After
public void teardown() throws IOException {
cleanupFile(localFileSys, dir);
if (cluster != null) {
cluster.shutdown();
}
}
private void writeConfigFile(Path name, ArrayList<String> nodes)
throws IOException {
// delete if it already exists
if (localFileSys.exists(name)) {
localFileSys.delete(name, true);
}
FSDataOutputStream stm = localFileSys.create(name);
if (nodes != null) {
for (Iterator<String> it = nodes.iterator(); it.hasNext();) {
String node = it.next();
stm.writeBytes(node);
stm.writeBytes("\n");
}
}
stm.close();
}
private void writeFile(FileSystem fileSys, Path name, int repl)
throws IOException {
// create and write a file that contains three blocks of data
FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf()
.getInt(CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096),
(short) repl, blockSize);
byte[] buffer = new byte[fileSize];
Random rand = new Random(seed);
rand.nextBytes(buffer);
stm.write(buffer);
stm.close();
LOG.info("Created file " + name + " with " + repl + " replicas.");
}
/**
* Verify that the number of replicas are as expected for each block in
* the given file.
* For blocks with a decommissioned node, verify that their replication
* is 1 more than what is specified.
* For blocks without decommissioned nodes, verify their replication is
* equal to what is specified.
*
* @param downnode - if null, there is no decommissioned node for this file.
* @return - null if no failure found, else an error message string.
*/
private String checkFile(FileSystem fileSys, Path name, int repl,
String downnode, int numDatanodes) throws IOException {
boolean isNodeDown = (downnode != null);
// need a raw stream
assertTrue("Not HDFS:"+fileSys.getUri(),
fileSys instanceof DistributedFileSystem);
HdfsDataInputStream dis = (HdfsDataInputStream)
fileSys.open(name);
Collection<LocatedBlock> dinfo = dis.getAllBlocks();
for (LocatedBlock blk : dinfo) { // for each block
int hasdown = 0;
DatanodeInfo[] nodes = blk.getLocations();
for (int j = 0; j < nodes.length; j++) { // for each replica
if (isNodeDown && nodes[j].getXferAddr().equals(downnode)) {
hasdown++;
//Downnode must actually be decommissioned
if (!nodes[j].isDecommissioned()) {
return "For block " + blk.getBlock() + " replica on " +
nodes[j] + " is given as downnode, " +
"but is not decommissioned";
}
//Decommissioned node (if any) should only be last node in list.
if (j != nodes.length - 1) {
return "For block " + blk.getBlock() + " decommissioned node "
+ nodes[j] + " was not last node in list: "
+ (j + 1) + " of " + nodes.length;
}
LOG.info("Block " + blk.getBlock() + " replica on " +
nodes[j] + " is decommissioned.");
} else {
//Non-downnodes must not be decommissioned
if (nodes[j].isDecommissioned()) {
return "For block " + blk.getBlock() + " replica on " +
nodes[j] + " is unexpectedly decommissioned";
}
}
}
LOG.info("Block " + blk.getBlock() + " has " + hasdown
+ " decommissioned replica.");
if(Math.min(numDatanodes, repl+hasdown) != nodes.length) {
return "Wrong number of replicas for block " + blk.getBlock() +
": " + nodes.length + ", expected " +
Math.min(numDatanodes, repl+hasdown);
}
}
return null;
}
private void cleanupFile(FileSystem fileSys, Path name) throws IOException {
assertTrue(fileSys.exists(name));
fileSys.delete(name, true);
assertTrue(!fileSys.exists(name));
}
/*
* decommission the DN at index dnIndex or one random node if dnIndex is set
* to -1 and wait for the node to reach the given {@code waitForState}.
*/
private DatanodeInfo decommissionNode(int nnIndex,
String datanodeUuid,
ArrayList<DatanodeInfo>decommissionedNodes,
AdminStates waitForState)
throws IOException {
DFSClient client = getDfsClient(cluster.getNameNode(nnIndex), conf);
DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.LIVE);
//
// pick one datanode randomly unless the caller specifies one.
//
int index = 0;
if (datanodeUuid == null) {
boolean found = false;
while (!found) {
index = myrand.nextInt(info.length);
if (!info[index].isDecommissioned()) {
found = true;
}
}
} else {
// The caller specifies a DN
for (; index < info.length; index++) {
if (info[index].getDatanodeUuid().equals(datanodeUuid)) {
break;
}
}
if (index == info.length) {
throw new IOException("invalid datanodeUuid " + datanodeUuid);
}
}
String nodename = info[index].getXferAddr();
LOG.info("Decommissioning node: " + nodename);
// write nodename into the exclude file.
ArrayList<String> nodes = new ArrayList<String>();
if (decommissionedNodes != null) {
for (DatanodeInfo dn : decommissionedNodes) {
nodes.add(dn.getName());
}
}
nodes.add(nodename);
writeConfigFile(excludeFile, nodes);
refreshNodes(cluster.getNamesystem(nnIndex), conf);
DatanodeInfo ret = NameNodeAdapter.getDatanode(
cluster.getNamesystem(nnIndex), info[index]);
waitNodeState(ret, waitForState);
return ret;
}
/* Ask a specific NN to stop decommission of the datanode and wait for each
* to reach the NORMAL state.
*/
private void recomissionNode(int nnIndex, DatanodeInfo decommissionedNode) throws IOException {
LOG.info("Recommissioning node: " + decommissionedNode);
writeConfigFile(excludeFile, null);
refreshNodes(cluster.getNamesystem(nnIndex), conf);
waitNodeState(decommissionedNode, AdminStates.NORMAL);
}
/*
* Wait till node is fully decommissioned.
*/
private void waitNodeState(DatanodeInfo node,
AdminStates state) {
boolean done = state == node.getAdminState();
while (!done) {
LOG.info("Waiting for node " + node + " to change state to "
+ state + " current state: " + node.getAdminState());
try {
Thread.sleep(HEARTBEAT_INTERVAL * 1000);
} catch (InterruptedException e) {
// nothing
}
done = state == node.getAdminState();
}
LOG.info("node " + node + " reached the state " + state);
}
/* Get DFSClient to the namenode */
private static DFSClient getDfsClient(NameNode nn,
Configuration conf) throws IOException {
return new DFSClient(nn.getNameNodeAddress(), conf);
}
/* Validate cluster has expected number of datanodes */
private static void validateCluster(DFSClient client, int numDNs)
throws IOException {
DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.LIVE);
assertEquals("Number of Datanodes ", numDNs, info.length);
}
/** Start a MiniDFSCluster
* @throws IOException */
private void startCluster(int numNameNodes, int numDatanodes,
Configuration conf) throws IOException {
cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleFederatedTopology(numNameNodes))
.numDataNodes(numDatanodes).build();
cluster.waitActive();
for (int i = 0; i < numNameNodes; i++) {
DFSClient client = getDfsClient(cluster.getNameNode(i), conf);
validateCluster(client, numDatanodes);
}
}
static void refreshNodes(final FSNamesystem ns, final Configuration conf
) throws IOException {
ns.getBlockManager().getDatanodeManager().refreshNodes(conf);
}
private void verifyStats(NameNode namenode, FSNamesystem fsn,
DatanodeInfo node, boolean decommissioning)
throws InterruptedException, IOException {
// Do the stats check over 10 iterations
for (int i = 0; i < 10; i++) {
long[] newStats = namenode.getRpcServer().getStats();
// For decommissioning nodes, ensure capacity of the DN is no longer
// counted. Only used space of the DN is counted in cluster capacity
assertEquals(newStats[0], decommissioning ? node.getDfsUsed() :
node.getCapacity());
// Ensure cluster used capacity is counted for both normal and
// decommissioning nodes
assertEquals(newStats[1], node.getDfsUsed());
// For decommissioning nodes, remaining space from the DN is not counted
assertEquals(newStats[2], decommissioning ? 0 : node.getRemaining());
// Ensure transceiver count is same as that DN
assertEquals(fsn.getTotalLoad(), node.getXceiverCount());
Thread.sleep(HEARTBEAT_INTERVAL * 1000); // Sleep heart beat interval
}
}
/**
* Tests decommission for non federated cluster
*/
@Test(timeout=360000)
public void testDecommission() throws IOException {
testDecommission(1, 6);
}
/**
* Tests decommission with replicas on the target datanode cannot be migrated
* to other datanodes and satisfy the replication factor. Make sure the
* datanode won't get stuck in decommissioning state.
*/
@Test(timeout = 360000)
public void testDecommission2() throws IOException {
LOG.info("Starting test testDecommission");
int numNamenodes = 1;
int numDatanodes = 4;
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 3);
startCluster(numNamenodes, numDatanodes, conf);
ArrayList<ArrayList<DatanodeInfo>> namenodeDecomList = new ArrayList<ArrayList<DatanodeInfo>>(
numNamenodes);
namenodeDecomList.add(0, new ArrayList<DatanodeInfo>(numDatanodes));
Path file1 = new Path("testDecommission2.dat");
int replicas = 4;
// Start decommissioning one namenode at a time
ArrayList<DatanodeInfo> decommissionedNodes = namenodeDecomList.get(0);
FileSystem fileSys = cluster.getFileSystem(0);
FSNamesystem ns = cluster.getNamesystem(0);
writeFile(fileSys, file1, replicas);
int deadDecomissioned = ns.getNumDecomDeadDataNodes();
int liveDecomissioned = ns.getNumDecomLiveDataNodes();
// Decommission one node. Verify that node is decommissioned.
DatanodeInfo decomNode = decommissionNode(0, null, decommissionedNodes,
AdminStates.DECOMMISSIONED);
decommissionedNodes.add(decomNode);
assertEquals(deadDecomissioned, ns.getNumDecomDeadDataNodes());
assertEquals(liveDecomissioned + 1, ns.getNumDecomLiveDataNodes());
// Ensure decommissioned datanode is not automatically shutdown
DFSClient client = getDfsClient(cluster.getNameNode(0), conf);
assertEquals("All datanodes must be alive", numDatanodes,
client.datanodeReport(DatanodeReportType.LIVE).length);
assertNull(checkFile(fileSys, file1, replicas, decomNode.getXferAddr(),
numDatanodes));
cleanupFile(fileSys, file1);
// Restart the cluster and ensure recommissioned datanodes
// are allowed to register with the namenode
cluster.shutdown();
startCluster(1, 4, conf);
cluster.shutdown();
}
/**
* Tests recommission for non federated cluster
*/
@Test(timeout=360000)
public void testRecommission() throws IOException {
testRecommission(1, 6);
}
/**
* Test decommission for federeated cluster
*/
@Test(timeout=360000)
public void testDecommissionFederation() throws IOException {
testDecommission(2, 2);
}
/**
* Test decommission process on standby NN.
* Verify admins can run "dfsadmin -refreshNodes" on SBN and decomm
* process can finish as long as admins run "dfsadmin -refreshNodes"
* on active NN.
* SBN used to mark excess replica upon recommission. The SBN's pick
* for excess replica could be different from the one picked by ANN.
* That creates inconsistent state and prevent SBN from finishing
* decommission.
*/
@Test(timeout=360000)
public void testDecommissionOnStandby() throws Exception {
Configuration hdfsConf = new HdfsConfiguration(conf);
hdfsConf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
hdfsConf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 30000);
hdfsConf.setInt(DFSConfigKeys.DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_KEY, 2);
// The time to wait so that the slow DN's heartbeat is considered old
// by BlockPlacementPolicyDefault and thus will choose that DN for
// excess replica.
long slowHeartbeatDNwaitTime =
hdfsConf.getLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY,
DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT) * 1000 * (hdfsConf.getInt(
DFSConfigKeys.DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_KEY,
DFSConfigKeys.DFS_NAMENODE_TOLERATE_HEARTBEAT_MULTIPLIER_DEFAULT) + 1);
cluster = new MiniDFSCluster.Builder(hdfsConf)
.nnTopology(MiniDFSNNTopology.simpleHATopology()).numDataNodes(3).build();
cluster.transitionToActive(0);
cluster.waitActive();
// Step 1, create a cluster with 4 DNs. Blocks are stored on the first 3 DNs.
// The last DN is empty. Also configure the last DN to have slow heartbeat
// so that it will be chosen as excess replica candidate during recommission.
// Step 1.a, copy blocks to the first 3 DNs. Given the replica count is the
// same as # of DNs, each DN will have a replica for any block.
Path file1 = new Path("testDecommissionHA.dat");
int replicas = 3;
FileSystem activeFileSys = cluster.getFileSystem(0);
writeFile(activeFileSys, file1, replicas);
HATestUtil.waitForStandbyToCatchUp(cluster.getNameNode(0),
cluster.getNameNode(1));
// Step 1.b, start a DN with slow heartbeat, so that we can know for sure it
// will be chosen as the target of excess replica during recommission.
hdfsConf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 30);
cluster.startDataNodes(hdfsConf, 1, true, null, null, null);
DataNode lastDN = cluster.getDataNodes().get(3);
lastDN.getDatanodeUuid();
// Step 2, decommission the first DN at both ANN and SBN.
DataNode firstDN = cluster.getDataNodes().get(0);
// Step 2.a, ask ANN to decomm the first DN
DatanodeInfo decommissionedNodeFromANN = decommissionNode(
0, firstDN.getDatanodeUuid(), null, AdminStates.DECOMMISSIONED);
// Step 2.b, ask SBN to decomm the first DN
DatanodeInfo decomNodeFromSBN = decommissionNode(1, firstDN.getDatanodeUuid(), null,
AdminStates.DECOMMISSIONED);
// Step 3, recommission the first DN on SBN and ANN to create excess replica
// It recommissions the node on SBN first to create potential
// inconsistent state. In production cluster, such insistent state can happen
// even if recommission command was issued on ANN first given the async nature
// of the system.
// Step 3.a, ask SBN to recomm the first DN.
// SBN has been fixed so that it no longer invalidates excess replica during
// recommission.
// Before the fix, SBN could get into the following state.
// 1. the last DN would have been chosen as excess replica, given its
// heartbeat is considered old.
// Please refer to BlockPlacementPolicyDefault#chooseReplicaToDelete
// 2. After recomissionNode finishes, SBN has 3 live replicas ( 0, 1, 2 )
// and one excess replica ( 3 )
// After the fix,
// After recomissionNode finishes, SBN has 4 live replicas ( 0, 1, 2, 3 )
Thread.sleep(slowHeartbeatDNwaitTime);
recomissionNode(1, decomNodeFromSBN);
// Step 3.b, ask ANN to recommission the first DN.
// To verify the fix, the test makes sure the excess replica picked by ANN
// is different from the one picked by SBN before the fix.
// To achieve that, we make sure next-to-last DN is chosen as excess replica
// by ANN.
// 1. restore LastDNprop's heartbeat interval.
// 2. Make next-to-last DN's heartbeat slow.
MiniDFSCluster.DataNodeProperties LastDNprop = cluster.stopDataNode(3);
LastDNprop.conf.setLong(
DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, HEARTBEAT_INTERVAL);
cluster.restartDataNode(LastDNprop);
MiniDFSCluster.DataNodeProperties nextToLastDNprop = cluster.stopDataNode(2);
nextToLastDNprop.conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 30);
cluster.restartDataNode(nextToLastDNprop);
cluster.waitActive();
Thread.sleep(slowHeartbeatDNwaitTime);
recomissionNode(0, decommissionedNodeFromANN);
// Step 3.c, make sure the DN has deleted the block and report to NNs
cluster.triggerHeartbeats();
HATestUtil.waitForDNDeletions(cluster);
cluster.triggerDeletionReports();
// Step 4, decommission the first DN on both ANN and SBN
// With the fix to make sure SBN no longer marks excess replica
// during recommission, SBN's decommission can finish properly
decommissionNode(0, firstDN.getDatanodeUuid(), null,
AdminStates.DECOMMISSIONED);
// Ask SBN to decomm the first DN
decommissionNode(1, firstDN.getDatanodeUuid(), null,
AdminStates.DECOMMISSIONED);
cluster.shutdown();
}
private void testDecommission(int numNamenodes, int numDatanodes)
throws IOException {
LOG.info("Starting test testDecommission");
startCluster(numNamenodes, numDatanodes, conf);
ArrayList<ArrayList<DatanodeInfo>> namenodeDecomList =
new ArrayList<ArrayList<DatanodeInfo>>(numNamenodes);
for(int i = 0; i < numNamenodes; i++) {
namenodeDecomList.add(i, new ArrayList<DatanodeInfo>(numDatanodes));
}
Path file1 = new Path("testDecommission.dat");
for (int iteration = 0; iteration < numDatanodes - 1; iteration++) {
int replicas = numDatanodes - iteration - 1;
// Start decommissioning one namenode at a time
for (int i = 0; i < numNamenodes; i++) {
ArrayList<DatanodeInfo> decommissionedNodes = namenodeDecomList.get(i);
FileSystem fileSys = cluster.getFileSystem(i);
FSNamesystem ns = cluster.getNamesystem(i);
writeFile(fileSys, file1, replicas);
int deadDecomissioned = ns.getNumDecomDeadDataNodes();
int liveDecomissioned = ns.getNumDecomLiveDataNodes();
// Decommission one node. Verify that node is decommissioned.
DatanodeInfo decomNode = decommissionNode(i, null, decommissionedNodes,
AdminStates.DECOMMISSIONED);
decommissionedNodes.add(decomNode);
assertEquals(deadDecomissioned, ns.getNumDecomDeadDataNodes());
assertEquals(liveDecomissioned + 1, ns.getNumDecomLiveDataNodes());
// Ensure decommissioned datanode is not automatically shutdown
DFSClient client = getDfsClient(cluster.getNameNode(i), conf);
assertEquals("All datanodes must be alive", numDatanodes,
client.datanodeReport(DatanodeReportType.LIVE).length);
// wait for the block to be replicated
int tries = 0;
while (tries++ < 20) {
try {
Thread.sleep(1000);
if (checkFile(fileSys, file1, replicas, decomNode.getXferAddr(),
numDatanodes) == null) {
break;
}
} catch (InterruptedException ie) {
}
}
assertTrue("Checked if block was replicated after decommission, tried "
+ tries + " times.", tries < 20);
cleanupFile(fileSys, file1);
}
}
// Restart the cluster and ensure decommissioned datanodes
// are allowed to register with the namenode
cluster.shutdown();
startCluster(numNamenodes, numDatanodes, conf);
cluster.shutdown();
}
private void testRecommission(int numNamenodes, int numDatanodes)
throws IOException {
LOG.info("Starting test testRecommission");
startCluster(numNamenodes, numDatanodes, conf);
ArrayList<ArrayList<DatanodeInfo>> namenodeDecomList =
new ArrayList<ArrayList<DatanodeInfo>>(numNamenodes);
for(int i = 0; i < numNamenodes; i++) {
namenodeDecomList.add(i, new ArrayList<DatanodeInfo>(numDatanodes));
}
Path file1 = new Path("testDecommission.dat");
int replicas = numDatanodes - 1;
for (int i = 0; i < numNamenodes; i++) {
ArrayList<DatanodeInfo> decommissionedNodes = namenodeDecomList.get(i);
FileSystem fileSys = cluster.getFileSystem(i);
writeFile(fileSys, file1, replicas);
// Decommission one node. Verify that node is decommissioned.
DatanodeInfo decomNode = decommissionNode(i, null, decommissionedNodes,
AdminStates.DECOMMISSIONED);
decommissionedNodes.add(decomNode);
// Ensure decommissioned datanode is not automatically shutdown
DFSClient client = getDfsClient(cluster.getNameNode(i), conf);
assertEquals("All datanodes must be alive", numDatanodes,
client.datanodeReport(DatanodeReportType.LIVE).length);
int tries =0;
// wait for the block to be replicated
while (tries++ < 20) {
try {
Thread.sleep(1000);
if (checkFile(fileSys, file1, replicas, decomNode.getXferAddr(),
numDatanodes) == null) {
break;
}
} catch (InterruptedException ie) {
}
}
assertTrue("Checked if block was replicated after decommission, tried "
+ tries + " times.", tries < 20);
// stop decommission and check if the new replicas are removed
recomissionNode(0, decomNode);
// wait for the block to be deleted
tries = 0;
while (tries++ < 20) {
try {
Thread.sleep(1000);
if (checkFile(fileSys, file1, replicas, null, numDatanodes) == null) {
break;
}
} catch (InterruptedException ie) {
}
}
cleanupFile(fileSys, file1);
assertTrue("Checked if node was recommissioned " + tries + " times.",
tries < 20);
LOG.info("tried: " + tries + " times before recommissioned");
}
cluster.shutdown();
}
/**
* Tests cluster storage statistics during decommissioning for non
* federated cluster
*/
@Test(timeout=360000)
public void testClusterStats() throws Exception {
testClusterStats(1);
}
/**
* Tests cluster storage statistics during decommissioning for
* federated cluster
*/
@Test(timeout=360000)
public void testClusterStatsFederation() throws Exception {
testClusterStats(3);
}
public void testClusterStats(int numNameNodes) throws IOException,
InterruptedException {
LOG.info("Starting test testClusterStats");
int numDatanodes = 1;
startCluster(numNameNodes, numDatanodes, conf);
for (int i = 0; i < numNameNodes; i++) {
FileSystem fileSys = cluster.getFileSystem(i);
Path file = new Path("testClusterStats.dat");
writeFile(fileSys, file, 1);
FSNamesystem fsn = cluster.getNamesystem(i);
NameNode namenode = cluster.getNameNode(i);
DatanodeInfo downnode = decommissionNode(i, null, null,
AdminStates.DECOMMISSION_INPROGRESS);
// Check namenode stats for multiple datanode heartbeats
verifyStats(namenode, fsn, downnode, true);
// Stop decommissioning and verify stats
writeConfigFile(excludeFile, null);
refreshNodes(fsn, conf);
DatanodeInfo ret = NameNodeAdapter.getDatanode(fsn, downnode);
waitNodeState(ret, AdminStates.NORMAL);
verifyStats(namenode, fsn, ret, false);
}
}
/**
* Test host/include file functionality. Only datanodes
* in the include file are allowed to connect to the namenode in a non
* federated cluster.
*/
@Test(timeout=360000)
public void testHostsFile() throws IOException, InterruptedException {
// Test for a single namenode cluster
testHostsFile(1);
}
/**
* Test host/include file functionality. Only datanodes
* in the include file are allowed to connect to the namenode in a
* federated cluster.
*/
@Test(timeout=360000)
public void testHostsFileFederation() throws IOException, InterruptedException {
// Test for 3 namenode federated cluster
testHostsFile(3);
}
public void testHostsFile(int numNameNodes) throws IOException,
InterruptedException {
int numDatanodes = 1;
cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleFederatedTopology(numNameNodes))
.numDataNodes(numDatanodes).setupHostsFile(true).build();
cluster.waitActive();
// Now empty hosts file and ensure the datanode is disallowed
// from talking to namenode, resulting in it's shutdown.
ArrayList<String>list = new ArrayList<String>();
final String bogusIp = "127.0.30.1";
list.add(bogusIp);
writeConfigFile(hostsFile, list);
for (int j = 0; j < numNameNodes; j++) {
refreshNodes(cluster.getNamesystem(j), conf);
DFSClient client = getDfsClient(cluster.getNameNode(j), conf);
DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.LIVE);
for (int i = 0 ; i < 5 && info.length != 0; i++) {
LOG.info("Waiting for datanode to be marked dead");
Thread.sleep(HEARTBEAT_INTERVAL * 1000);
info = client.datanodeReport(DatanodeReportType.LIVE);
}
assertEquals("Number of live nodes should be 0", 0, info.length);
// Test that non-live and bogus hostnames are considered "dead".
// The dead report should have an entry for (1) the DN that is
// now considered dead because it is no longer allowed to connect
// and (2) the bogus entry in the hosts file (these entries are
// always added last)
info = client.datanodeReport(DatanodeReportType.DEAD);
assertEquals("There should be 2 dead nodes", 2, info.length);
DatanodeID id = cluster.getDataNodes().get(0).getDatanodeId();
assertEquals(id.getHostName(), info[0].getHostName());
assertEquals(bogusIp, info[1].getHostName());
}
}
@Test(timeout=120000)
public void testDecommissionWithOpenfile() throws IOException, InterruptedException {
LOG.info("Starting test testDecommissionWithOpenfile");
//At most 4 nodes will be decommissioned
startCluster(1, 7, conf);
FileSystem fileSys = cluster.getFileSystem(0);
FSNamesystem ns = cluster.getNamesystem(0);
String openFile = "/testDecommissionWithOpenfile.dat";
writeFile(fileSys, new Path(openFile), (short)3);
// make sure the file was open for write
FSDataOutputStream fdos = fileSys.append(new Path(openFile));
LocatedBlocks lbs = NameNodeAdapter.getBlockLocations(cluster.getNameNode(0), openFile, 0, fileSize);
DatanodeInfo[] dnInfos4LastBlock = lbs.getLastLocatedBlock().getLocations();
DatanodeInfo[] dnInfos4FirstBlock = lbs.get(0).getLocations();
ArrayList<String> nodes = new ArrayList<String>();
ArrayList<DatanodeInfo> dnInfos = new ArrayList<DatanodeInfo>();
for (DatanodeInfo datanodeInfo : dnInfos4FirstBlock) {
DatanodeInfo found = datanodeInfo;
for (DatanodeInfo dif: dnInfos4LastBlock) {
if (datanodeInfo.equals(dif)) {
found = null;
}
}
if (found != null) {
nodes.add(found.getXferAddr());
dnInfos.add(found);
}
}
//decommission one of the 3 nodes which have last block
nodes.add(dnInfos4LastBlock[0].getXferAddr());
dnInfos.add(dnInfos4LastBlock[0]);
writeConfigFile(excludeFile, nodes);
refreshNodes(ns, conf);
for (DatanodeInfo dn : dnInfos) {
waitNodeState(dn, AdminStates.DECOMMISSIONED);
}
fdos.close();
}
/**
* Tests restart of namenode while datanode hosts are added to exclude file
**/
@Test(timeout=360000)
public void testDecommissionWithNamenodeRestart()throws IOException, InterruptedException {
LOG.info("Starting test testDecommissionWithNamenodeRestart");
int numNamenodes = 1;
int numDatanodes = 1;
int replicas = 1;
startCluster(numNamenodes, numDatanodes, conf);
Path file1 = new Path("testDecommission.dat");
FileSystem fileSys = cluster.getFileSystem();
writeFile(fileSys, file1, replicas);
DFSClient client = getDfsClient(cluster.getNameNode(), conf);
DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.LIVE);
DatanodeID excludedDatanodeID = info[0];
String excludedDatanodeName = info[0].getXferAddr();
writeConfigFile(excludeFile, new ArrayList<String>(Arrays.asList(excludedDatanodeName)));
//Add a new datanode to cluster
cluster.startDataNodes(conf, 1, true, null, null, null, null);
numDatanodes+=1;
assertEquals("Number of datanodes should be 2 ", 2, cluster.getDataNodes().size());
//Restart the namenode
cluster.restartNameNode();
DatanodeInfo datanodeInfo = NameNodeAdapter.getDatanode(
cluster.getNamesystem(), excludedDatanodeID);
waitNodeState(datanodeInfo, AdminStates.DECOMMISSIONED);
// Ensure decommissioned datanode is not automatically shutdown
assertEquals("All datanodes must be alive", numDatanodes,
client.datanodeReport(DatanodeReportType.LIVE).length);
// wait for the block to be replicated
int tries = 0;
while (tries++ < 20) {
try {
Thread.sleep(1000);
if (checkFile(fileSys, file1, replicas, datanodeInfo.getXferAddr(),
numDatanodes) == null) {
break;
}
} catch (InterruptedException ie) {
}
}
assertTrue("Checked if block was replicated after decommission, tried "
+ tries + " times.", tries < 20);
cleanupFile(fileSys, file1);
// Restart the cluster and ensure recommissioned datanodes
// are allowed to register with the namenode
cluster.shutdown();
startCluster(numNamenodes, numDatanodes, conf);
cluster.shutdown();
}
/**
* Test using a "registration name" in a host include file.
*
* Registration names are DataNode names specified in the configuration by
* dfs.datanode.hostname. The DataNode will send this name to the NameNode
* as part of its registration. Registration names are helpful when you
* want to override the normal first result of DNS resolution on the
* NameNode. For example, a given datanode IP may map to two hostnames,
* and you may want to choose which hostname is used internally in the
* cluster.
*
* It is not recommended to use a registration name which is not also a
* valid DNS hostname for the DataNode. See HDFS-5237 for background.
*/
@Test(timeout=360000)
public void testIncludeByRegistrationName() throws IOException,
InterruptedException {
Configuration hdfsConf = new Configuration(conf);
// Any IPv4 address starting with 127 functions as a "loopback" address
// which is connected to the current host. So by choosing 127.0.0.100
// as our registration name, we have chosen a name which is also a valid
// way of reaching the local DataNode we're going to start.
// Typically, a registration name would be a hostname, but we don't want
// to deal with DNS in this test.
final String registrationName = "127.0.0.100";
final String nonExistentDn = "127.0.0.10";
hdfsConf.set(DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY, registrationName);
cluster = new MiniDFSCluster.Builder(hdfsConf)
.numDataNodes(1).checkDataNodeHostConfig(true)
.setupHostsFile(true).build();
cluster.waitActive();
// Set up an includes file that doesn't have our datanode.
ArrayList<String> nodes = new ArrayList<String>();
nodes.add(nonExistentDn);
writeConfigFile(hostsFile, nodes);
refreshNodes(cluster.getNamesystem(0), hdfsConf);
// Wait for the DN to be marked dead.
DFSClient client = getDfsClient(cluster.getNameNode(0), hdfsConf);
while (true) {
DatanodeInfo info[] = client.datanodeReport(DatanodeReportType.DEAD);
if (info.length == 1) {
break;
}
LOG.info("Waiting for datanode to be marked dead");
Thread.sleep(HEARTBEAT_INTERVAL * 1000);
}
// Use a non-empty include file with our registration name.
// It should work.
int dnPort = cluster.getDataNodes().get(0).getXferPort();
nodes = new ArrayList<String>();
nodes.add(registrationName + ":" + dnPort);
writeConfigFile(hostsFile, nodes);
refreshNodes(cluster.getNamesystem(0), hdfsConf);
cluster.restartDataNode(0);
// Wait for the DN to come back.
while (true) {
DatanodeInfo info[] = client.datanodeReport(DatanodeReportType.LIVE);
if (info.length == 1) {
Assert.assertFalse(info[0].isDecommissioned());
Assert.assertFalse(info[0].isDecommissionInProgress());
assertEquals(registrationName, info[0].getHostName());
break;
}
LOG.info("Waiting for datanode to come back");
Thread.sleep(HEARTBEAT_INTERVAL * 1000);
}
}
}
|
apache/felix-dev | 37,558 | http/jetty12/src/main/java/org/apache/felix/http/jetty/internal/ConfigMetaTypeProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.http.jetty.internal;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.felix.http.base.internal.HttpConfig;
import org.apache.felix.http.base.internal.logger.SystemLogger;
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.session.HouseKeeper;
import org.osgi.framework.Bundle;
import org.osgi.service.metatype.AttributeDefinition;
import org.osgi.service.metatype.MetaTypeProvider;
import org.osgi.service.metatype.ObjectClassDefinition;
class ConfigMetaTypeProvider implements MetaTypeProvider
{
private final Bundle bundle;
public ConfigMetaTypeProvider(final Bundle bundle)
{
this.bundle = bundle;
}
/**
* @see org.osgi.service.metatype.MetaTypeProvider#getLocales()
*/
@Override
public String[] getLocales()
{
return null;
}
/**
* @see org.osgi.service.metatype.MetaTypeProvider#getObjectClassDefinition(java.lang.String, java.lang.String)
*/
@Override
public ObjectClassDefinition getObjectClassDefinition( String id, String locale )
{
if ( !JettyService.PID.equals( id ) )
{
return null;
}
final ArrayList<AttributeDefinition> adList = new ArrayList<>();
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HOST,
"Host Name",
"IP Address or Host Name of the interface to which HTTP and HTTPS bind. The default is " +
"\"0.0.0.0\" indicating all interfaces.",
"0.0.0.0",
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HOST)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_ENABLE,
"Enable HTTP",
"Whether or not HTTP is enabled. Defaults to true thus HTTP enabled.",
true,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.HTTP_PORT,
"HTTP Port",
"Port to listen on for HTTP requests. Defaults to 8080.",
8080,
bundle.getBundleContext().getProperty(JettyConfig.HTTP_PORT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.HTTP_TIMEOUT,
"Connection Timeout",
"Time limit for reaching an timeout specified in milliseconds. This property applies to both HTTP and HTTP connections. Defaults to 60 seconds.",
60000,
bundle.getBundleContext().getProperty(JettyConfig.HTTP_TIMEOUT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTPS_ENABLE,
"Enable HTTPS",
"Whether or not HTTPS is enabled. Defaults to false thus HTTPS disabled.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTPS_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.HTTPS_PORT,
"HTTPS Port",
"Port to listen on for HTTPS requests. Defaults to 443.",
443,
bundle.getBundleContext().getProperty(JettyConfig.HTTPS_PORT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_KEYSTORE,
"Keystore",
"Absolute Path to the Keystore to use for HTTPS. Only used if HTTPS is enabled in which case this property is required.",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_KEYSTORE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_KEYSTORE_PASSWORD,
"Keystore Password",
"Password to access the Keystore. Only used if HTTPS is enabled."));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_KEYSTORE_KEY_PASSWORD,
"Key Password",
"Password to unlock the secret key from the Keystore. Only used if HTTPS is enabled."));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_TRUSTSTORE,
"Truststore",
"Absolute Path to the Truststore to use for HTTPS. Only used if HTTPS is enabled.",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_TRUSTSTORE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_TRUSTSTORE_PASSWORD,
"Truststore Password",
"Password to access the Truststore. Only used if HTTPS is enabled."));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTPS_CLIENT_CERT,
"Client Certificate",
"Requirement for the Client to provide a valid certificate. Defaults to none.",
AttributeDefinition.STRING,
new String[] {"none"},
0,
new String[] {"No Client Certificate", "Client Certificate Wanted", "Client Certificate Needed"},
new String[] {"none", "wants", "needs"},
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTPS_CLIENT_CERT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_CONTEXT_PATH,
"Context Path",
"The Servlet Context Path to use for the Http Service. If this property is not configured it " +
"defaults to \"/\". This must be a valid path starting with a slash and not ending with a slash (unless it is the root context).",
"/",
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_CONTEXT_PATH)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_MBEANS,
"Register MBeans",
"Whether or not to use register JMX MBeans from the servlet container (Jetty). If this is " +
"enabled Jetty Request and Connector statistics are also added. The default is to not enable JMX.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_MBEANS)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_STATISTICS_HANDLER_ENABLE,
"Enable Statistics",
"Whether or not to use enable Statistics in the servlet container (Jetty).",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_STATISTICS_HANDLER_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_SESSION_TIMEOUT,
"Session Timeout",
"Default lifetime of an HTTP session specified in a whole number of minutes. If the timeout is 0 or less, sessions will by default never timeout. The default is 0.",
0,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_SESSION_TIMEOUT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_THREADPOOL_MAX,
"Thread Pool Max",
"Maximum number of jetty threads. Using the default -1 uses Jetty's default (200).",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_THREADPOOL_MAX)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_USE_VIRTUAL_THREADS,
"Use Virtual Threads",
"Use virtual threads in Jetty (JDK 21 or higher). Defaults to false.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_USE_VIRTUAL_THREADS)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_ACCEPTORS,
"Acceptors",
"Number of acceptor threads to use, or -1 for a default value. Acceptors accept new TCP/IP connections. If 0, then the selector threads are used to accept connections.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_ACCEPTORS)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SELECTORS,
"Selectors",
"Number of selector threads, or <=0 for a default value. Selectors notice and schedule established connection that can make IO progress.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SELECTORS)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_HEADER_BUFFER_SIZE,
"Header Buffer Size",
"Size of the buffer for request and response headers. Default is 16KB.",
16384,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_HEADER_BUFFER_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_REQUEST_BUFFER_SIZE,
"Request Buffer Size",
"Size of the buffer for requests not fitting the header buffer. Default is 8KB.",
8192,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_REQUEST_BUFFER_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_RESPONSE_BUFFER_SIZE,
"Response Buffer Size",
"Size of the buffer for responses. Default is 24KB.",
24576,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_RESPONSE_BUFFER_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_MAX_FORM_SIZE,
"Maximum Form Size in bytes",
"Size of Body for submitted form content. Default is 200KB.",
204800,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_MAX_FORM_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_REQUEST_SIZE_LIMIT,
"Maximum request size in bytes",
"Maximum size of the request body in bytes. Default is unlimited.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_REQUEST_SIZE_LIMIT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_RESPONSE_SIZE_LIMIT,
"Maximum response size in bytes",
"Maximum size of the response body in bytes. Default is unlimited.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_RESPONSE_SIZE_LIMIT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_ACCEPT_QUEUE_SIZE,
"Jetty accept queue size",
"Felix specific property to configure the accept queue size.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_ACCEPT_QUEUE_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_ERROR_PAGE_CUSTOM_HEADERS,
"Custom headers to add to error pages",
"Felix specific property to configure the custom headers to add to all error pages served by Jetty. Separate key-value pairs with ##.",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_ERROR_PAGE_CUSTOM_HEADERS)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_PATH_EXCLUSIONS,
"Path Exclusions",
"Contains a list of context path prefixes. If a Web Application Bundle is started with a context path matching any " +
"of these prefixes, it will not be deployed in the servlet container.",
AttributeDefinition.STRING,
new String[] {"/system"},
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_PATH_EXCLUSIONS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_EXCLUDED_SUITES,
"Excluded Cipher Suites",
"List of cipher suites that should be excluded. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_EXCLUDED_SUITES))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_INCLUDED_SUITES,
"Included Cipher Suites",
"List of cipher suites that should be included. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_INCLUDED_SUITES))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SEND_SERVER_HEADER,
"Send Server Header",
"If enabled, the server header is sent.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SEND_SERVER_HEADER)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_INCLUDED_PROTOCOLS,
"Included Protocols",
"List of SSL protocols to include by default. Protocols may be any supported by the Java " +
"platform such as SSLv2Hello, SSLv3, TLSv1, TLSv1.1, or TLSv1.2. Any listed protocol " +
"not supported is silently ignored. Default is none assuming to use any protocol enabled " +
"and supported on the platform.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_INCLUDED_PROTOCOLS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_EXCLUDED_PROTOCOLS,
"Excluded Protocols",
"List of SSL protocols to exclude. This property further restricts the enabled protocols by " +
"explicitly disabling. Any protocol listed in both this property and the Included " +
"protocols property is excluded. Default is none such as to accept all protocols enabled " +
"on platform or explicitly listed by the Included protocols property.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_EXCLUDED_PROTOCOLS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_PROXY_LOAD_BALANCER_CONNECTION_ENABLE,
"Enable Proxy/Load Balancer Connection",
"Whether or not the Proxy/Load Balancer Connection is enabled. Defaults to false thus disabled.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_PROXY_LOAD_BALANCER_CONNECTION_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_RENEGOTIATION_ALLOWED,
"Renegotiation allowed",
"Whether TLS renegotiation is allowed (true by default)",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_RENEGOTIATION_ALLOWED)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SESSION_COOKIE_HTTP_ONLY,
"Session Cookie httpOnly",
"Session Cookie httpOnly (true by default)",
true,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SESSION_COOKIE_HTTP_ONLY)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SESSION_COOKIE_SECURE,
"Session Cookie secure",
"Session Cookie secure (false by default)",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SESSION_COOKIE_SECURE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_URI_COMPLIANCE_MODE,
"Jetty URI compliance mode",
"Jetty URI compliance mode (if not set, Jetty will configure a default)",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_URI_COMPLIANCE_MODE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SERVLET_SESSION_ID_PATH_PARAMETER_NAME,
"Session Id path parameter",
"Defaults to jsessionid. If set to null or \"none\" no URL rewriting will be done.",
"jsessionid",
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SERVLET_SESSION_ID_PATH_PARAMETER_NAME)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SERVLET_CHECK_REMOTE_SESSION_ENCODING,
"Check remote session encoding",
"If true, Jetty will add JSESSIONID parameter even when encoding external urls with calls to encodeURL() (true by default)",
true,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SERVLET_CHECK_REMOTE_SESSION_ENCODING)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SERVLET_SESSION_COOKIE_NAME,
"Session Cookie Name",
"Session Cookie Name",
"JSESSIONID",
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SERVLET_SESSION_COOKIE_NAME)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SERVLET_SESSION_DOMAIN,
"Session Domain",
"If this property is set, then it is used as the domain for session cookies. If it is not set, then no domain is specified for the session cookie. Default is none.",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SERVLET_SESSION_DOMAIN)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SERVLET_SESSION_PATH,
"Session Path",
"If this property is set, then it is used as the path for the session cookie. Default is context path.",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SERVLET_SESSION_DOMAIN)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SERVLET_SESSION_MAX_AGE,
"Session Max Age",
"Max age for the session cookie. Default is -1.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SERVLET_SESSION_MAX_AGE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_SESSION_SCAVENGING_INTERVAL,
"Session Scavenging Interval",
"Interval of session scavenging in seconds. Default is " + String.valueOf(HouseKeeper.DEFAULT_PERIOD_MS / 1000),
HouseKeeper.DEFAULT_PERIOD_MS / 1000,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_SESSION_SCAVENGING_INTERVAL)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_SERVICE_NAME,
"HTTP Service Name",
"HTTP Service Name used in service filter to target specific HTTP instance. Default is null.",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_SERVICE_NAME)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_HANDLER_ENABLE,
"Enable GzipHandler",
"Whether the server should use a server-wide gzip handler. Default is false.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_HANDLER_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_MIN_GZIP_SIZE,
"Gzip Min Size",
String.format("The minimum response size to trigger dynamic compression. Default is %d.", GzipHandler.DEFAULT_MIN_GZIP_SIZE),
GzipHandler.DEFAULT_MIN_GZIP_SIZE,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_MIN_GZIP_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_INFLATE_BUFFER_SIZE,
"Gzip Inflate Buffer Size",
"The size in bytes of the buffer to inflate compressed request, or <= 0 for no inflation. Default is -1.",
-1,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_INFLATE_BUFFER_SIZE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_SYNC_FLUSH,
"Gzip Sync Flush",
"True if Deflater#SYNC_FLUSH should be used, else Deflater#NO_FLUSH will be used. Default is false.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_SYNC_FLUSH)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_INCLUDED_METHODS,
"Gzip Include Methods",
"The additional http methods to include in compression. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_INCLUDED_METHODS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_EXCLUDED_METHODS,
"Gzip Exclude Methods",
"The additional http methods to exclude in compression. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_EXCLUDED_METHODS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_INCLUDED_PATHS,
"Gzip Included Paths",
"The additional path specs to include. Inclusion takes precedence over exclusion. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_INCLUDED_PATHS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_EXCLUDED_PATHS,
"Gzip Excluded Paths",
"The additional path specs to exclude. Inclusion takes precedence over exclusion. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_EXCLUDED_PATHS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_INCLUDED_MIME_TYPES,
"Gzip Included Mime Types",
"The included mime types. Inclusion takes precedence over exclusion. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_INCLUDED_MIME_TYPES))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_GZIP_EXCLUDED_MIME_TYPES,
"Gzip Excluded Mime Types",
"The excluded mime types. Inclusion takes precedence over exclusion. Default is none.",
AttributeDefinition.STRING,
null,
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_GZIP_EXCLUDED_MIME_TYPES))));
adList.add(new AttributeDefinitionImpl(HttpConfig.PROP_INVALIDATE_SESSION,
"Invalidate Container Session",
"If this property is set, the container session is automatically validated.",
HttpConfig.DEFAULT_INVALIDATE_SESSION,
bundle.getBundleContext().getProperty(HttpConfig.PROP_INVALIDATE_SESSION)));
adList.add(new AttributeDefinitionImpl(HttpConfig.PROP_CONTAINER_ADDED_ATTRIBUTE,
"Attributes added by server.",
"The attributes added by underlying session. Use this to invalidate session.",
AttributeDefinition.STRING,
new String[] {"org.eclipse.jetty.security.sessionCreatedSecure"},
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(HttpConfig.PROP_CONTAINER_ADDED_ATTRIBUTE))));
adList.add(new AttributeDefinitionImpl(HttpConfig.PROP_UNIQUE_SESSION_ID,
"Unique Session Id",
"If this property is set, each http context gets a unique session id (derived from the container session).",
HttpConfig.DEFAULT_UNIQUE_SESSION_ID,
bundle.getBundleContext().getProperty(HttpConfig.PROP_UNIQUE_SESSION_ID)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_STOP_TIMEOUT, "Server stop timeout",
"If not -1, stop timeout for the server in milliseconds.", -1L,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_STOP_TIMEOUT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP2_ENABLE,
"Enable Http/2",
"Whether to enable HTTP/2. Default is false.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP2_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_HTTP2_MAX_CONCURRENT_STREAMS,
"Http/2 Max Concurrent Streams",
"The max number of concurrent streams per connection. Default is 128.",
128,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_HTTP2_MAX_CONCURRENT_STREAMS)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_HTTP2_INITIAL_STREAM_RECV_WINDOW,
"Http/2 Initial Stream Recieve Window",
"The initial stream receive window (client to server). Default is 524288.",
524288,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_HTTP2_INITIAL_STREAM_RECV_WINDOW)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_HTTP2_INITIAL_SESSION_RECV_WINDOW,
"Http/2 Initial Session Recieve Window",
"The initial session receive window (client to server). Default is 1048576.",
1048576,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_HTTP2_INITIAL_SESSION_RECV_WINDOW)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_ALPN_PROTOCOLS,
"ALPN Protocols",
"The ALPN protocols to consider. Default is h2, http/1.1.",
AttributeDefinition.STRING,
new String[] {"h2", "http/1.1"},
2147483647,
null, null,
getStringArray(bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_ALPN_PROTOCOLS))));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_ALPN_DEFAULT_PROTOCOL,
"ALPN Default Protocol",
"The default protocol when negotiation fails. Default is http/1.1.",
"http/1.1",
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_ALPN_DEFAULT_PROTOCOL)));
// most important request logging attributes
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_REQUEST_LOG_FILE_PATH,
"Request Log File Path",
"The path to the log file which is receiving request log entries. If empty no request log file is created",
null,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_REQUEST_LOG_FILE_PATH)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_REQUEST_LOG_FILE_FORMAT,
"Request Log File Format",
"The format of the request log file entries. Only relevant if 'Request Log File Path' is set. Valid placeholders are described in https://www.eclipse.org/jetty/documentation/jetty-11/operations-guide/index.html#og-module-requestlog",
CustomRequestLog.NCSA_FORMAT,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_REQUEST_LOG_FILE_FORMAT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_REQUEST_LOG_OSGI_ENABLE,
"Enable SLF4J Request Logging",
"Select to log requests through SLF4J logger with given name (on level INFO)",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_REQUEST_LOG_OSGI_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_REQUEST_LOG_OSGI_LOGGER_NAME,
"SLF4J Request Log Logger Name",
"The name of the SLF4J request logger. Only relevant if 'Enable SLF4J Request Logging' is checked.",
SystemLogger.LOGGER.getName(),
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_REQUEST_LOG_OSGI_LOGGER_NAME)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_HTTP_REQUEST_LOG_FORMAT,
"SLF4J Request Log Format",
"The format of the request log entries. Only relevant if 'Enable SLF4J Request Logging' is checked. Valid placeholders are described in https://www.eclipse.org/jetty/documentation/jetty-11/operations-guide/index.html#og-module-requestlog",
CustomRequestLog.NCSA_FORMAT,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_HTTP_REQUEST_LOG_FORMAT)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JAKARTA_WEBSOCKET_ENABLE,
"Enable Jakarta standard WebSocket support",
"Whether to enable jakarta standard WebSocket support. Default is false.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JAKARTA_WEBSOCKET_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_WEBSOCKET_ENABLE,
"Enable Jetty specific WebSocket support",
"Whether to enable jetty specific WebSocket support. Default is false.",
false,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_WEBSOCKET_ENABLE)));
adList.add(new AttributeDefinitionImpl(JettyConfig.FELIX_JETTY_ALLOW_RELATIVE_REDIRECTS,
"Allow Relative Redirects",
"Whether or not relative redirects are allowed. Defaults to true thus relative redirects are allowed.",
true,
bundle.getBundleContext().getProperty(JettyConfig.FELIX_JETTY_ALLOW_RELATIVE_REDIRECTS)));
return new ObjectClassDefinition()
{
private final AttributeDefinition[] attrs = adList
.toArray(new AttributeDefinition[adList.size()]);
@Override
public String getName()
{
return "Apache Felix Jetty Based Http Service";
}
@Override
public InputStream getIcon(int arg0)
{
return null;
}
@Override
public String getID()
{
return JettyService.PID;
}
@Override
public String getDescription()
{
return "Configuration for the embedded Jetty Servlet Container.";
}
@Override
public AttributeDefinition[] getAttributeDefinitions(int filter)
{
return (filter == OPTIONAL) ? null : attrs;
}
};
}
private String [] getStringArray(final String value)
{
if ( value != null )
{
return value.trim().split(",");
}
return null;
}
private static class AttributeDefinitionImpl implements AttributeDefinition
{
private final String id;
private final String name;
private final String description;
private final int type;
private final String[] defaultValues;
private final int cardinality;
private final String[] optionLabels;
private final String[] optionValues;
/**
* Constructor for password properties
* @param id The id of the property
* @param name The property name
* @param description The property description
*/
AttributeDefinitionImpl( final String id, final String name, final String description )
{
this( id, name, description, PASSWORD, (String[])null, 0, null, null, (String[])null );
}
AttributeDefinitionImpl( final String id, final String name, final String description, final String defaultValue, final String overrideValue )
{
this( id, name, description, STRING, defaultValue == null ? null : new String[] { defaultValue }, 0, null, null, overrideValue == null ? null : new String[] { overrideValue } );
}
AttributeDefinitionImpl( final String id, final String name, final String description, final long defaultValue, final String overrideValue )
{
this( id, name, description, LONG, new String[]
{ String.valueOf(defaultValue) }, 0, null, null, overrideValue == null ? null : new String[] { overrideValue } );
}
AttributeDefinitionImpl( final String id, final String name, final String description, final int defaultValue, final String overrideValue )
{
this( id, name, description, INTEGER, new String[]
{ String.valueOf(defaultValue) }, 0, null, null, overrideValue == null ? null : new String[] { overrideValue } );
}
AttributeDefinitionImpl( final String id, final String name, final String description, final boolean defaultValue, final String overrideValue )
{
this( id, name, description, BOOLEAN, new String[]
{ String.valueOf(defaultValue) }, 0, null, null, overrideValue == null ? null : new String[] { overrideValue } );
}
AttributeDefinitionImpl( final String id, final String name, final String description, final int type,
final String[] defaultValues, final int cardinality, final String[] optionLabels,
final String[] optionValues,
final String overrideValue)
{
this(id, name, description, type, defaultValues, cardinality, optionLabels, optionValues, overrideValue == null ? null : new String[] { overrideValue });
}
AttributeDefinitionImpl( final String id, final String name, final String description, final int type,
final String[] defaultValues, final int cardinality, final String[] optionLabels,
final String[] optionValues,
final String[] overrideValues)
{
this.id = id;
this.name = name;
this.description = description;
this.type = type;
if ( overrideValues != null )
{
this.defaultValues = overrideValues;
}
else
{
this.defaultValues = defaultValues;
}
this.cardinality = cardinality;
this.optionLabels = optionLabels;
this.optionValues = optionValues;
}
@Override
public int getCardinality()
{
return cardinality;
}
@Override
public String[] getDefaultValue()
{
return defaultValues;
}
@Override
public String getDescription()
{
return description;
}
@Override
public String getID()
{
return id;
}
@Override
public String getName()
{
return name;
}
@Override
public String[] getOptionLabels()
{
return optionLabels;
}
@Override
public String[] getOptionValues()
{
return optionValues;
}
@Override
public int getType()
{
return type;
}
@Override
public String validate( String arg0 )
{
return null;
}
}
}
|
googleapis/google-cloud-java | 37,404 | java-dataproc/proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/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/dataproc/v1/sessions.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dataproc.v1;
/**
*
*
* <pre>
* A list of interactive sessions.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.ListSessionsResponse}
*/
public final class ListSessionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.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.dataproc.v1.SessionsProto
.internal_static_google_cloud_dataproc_v1_ListSessionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.SessionsProto
.internal_static_google_cloud_dataproc_v1_ListSessionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.ListSessionsResponse.class,
com.google.cloud.dataproc.v1.ListSessionsResponse.Builder.class);
}
public static final int SESSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.dataproc.v1.Session> sessions_;
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dataproc.v1.Session> getSessionsList() {
return sessions_;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dataproc.v1.SessionOrBuilder>
getSessionsOrBuilderList() {
return sessions_;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public int getSessionsCount() {
return sessions_.size();
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataproc.v1.Session getSessions(int index) {
return sessions_.get(index);
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataproc.v1.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>
* 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 < 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.dataproc.v1.ListSessionsResponse)) {
return super.equals(obj);
}
com.google.cloud.dataproc.v1.ListSessionsResponse other =
(com.google.cloud.dataproc.v1.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.dataproc.v1.ListSessionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.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.dataproc.v1.ListSessionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.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.dataproc.v1.ListSessionsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ListSessionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ListSessionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.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.dataproc.v1.ListSessionsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.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.dataproc.v1.ListSessionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.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.dataproc.v1.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>
* A list of interactive sessions.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.ListSessionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.ListSessionsResponse)
com.google.cloud.dataproc.v1.ListSessionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataproc.v1.SessionsProto
.internal_static_google_cloud_dataproc_v1_ListSessionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.SessionsProto
.internal_static_google_cloud_dataproc_v1_ListSessionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.ListSessionsResponse.class,
com.google.cloud.dataproc.v1.ListSessionsResponse.Builder.class);
}
// Construct using com.google.cloud.dataproc.v1.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.dataproc.v1.SessionsProto
.internal_static_google_cloud_dataproc_v1_ListSessionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ListSessionsResponse getDefaultInstanceForType() {
return com.google.cloud.dataproc.v1.ListSessionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ListSessionsResponse build() {
com.google.cloud.dataproc.v1.ListSessionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.ListSessionsResponse buildPartial() {
com.google.cloud.dataproc.v1.ListSessionsResponse result =
new com.google.cloud.dataproc.v1.ListSessionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.dataproc.v1.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.dataproc.v1.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.dataproc.v1.ListSessionsResponse) {
return mergeFrom((com.google.cloud.dataproc.v1.ListSessionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataproc.v1.ListSessionsResponse other) {
if (other == com.google.cloud.dataproc.v1.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.dataproc.v1.Session m =
input.readMessage(
com.google.cloud.dataproc.v1.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.dataproc.v1.Session> sessions_ =
java.util.Collections.emptyList();
private void ensureSessionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
sessions_ = new java.util.ArrayList<com.google.cloud.dataproc.v1.Session>(sessions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dataproc.v1.Session,
com.google.cloud.dataproc.v1.Session.Builder,
com.google.cloud.dataproc.v1.SessionOrBuilder>
sessionsBuilder_;
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public java.util.List<com.google.cloud.dataproc.v1.Session> getSessionsList() {
if (sessionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(sessions_);
} else {
return sessionsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public int getSessionsCount() {
if (sessionsBuilder_ == null) {
return sessions_.size();
} else {
return sessionsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.dataproc.v1.Session getSessions(int index) {
if (sessionsBuilder_ == null) {
return sessions_.get(index);
} else {
return sessionsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setSessions(int index, com.google.cloud.dataproc.v1.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>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setSessions(
int index, com.google.cloud.dataproc.v1.Session.Builder builderForValue) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.set(index, builderForValue.build());
onChanged();
} else {
sessionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addSessions(com.google.cloud.dataproc.v1.Session value) {
if (sessionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSessionsIsMutable();
sessions_.add(value);
onChanged();
} else {
sessionsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addSessions(int index, com.google.cloud.dataproc.v1.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>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addSessions(com.google.cloud.dataproc.v1.Session.Builder builderForValue) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.add(builderForValue.build());
onChanged();
} else {
sessionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addSessions(
int index, com.google.cloud.dataproc.v1.Session.Builder builderForValue) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.add(index, builderForValue.build());
onChanged();
} else {
sessionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addAllSessions(
java.lang.Iterable<? extends com.google.cloud.dataproc.v1.Session> values) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, sessions_);
onChanged();
} else {
sessionsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder clearSessions() {
if (sessionsBuilder_ == null) {
sessions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
sessionsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder removeSessions(int index) {
if (sessionsBuilder_ == null) {
ensureSessionsIsMutable();
sessions_.remove(index);
onChanged();
} else {
sessionsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.dataproc.v1.Session.Builder getSessionsBuilder(int index) {
return getSessionsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.dataproc.v1.SessionOrBuilder getSessionsOrBuilder(int index) {
if (sessionsBuilder_ == null) {
return sessions_.get(index);
} else {
return sessionsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public java.util.List<? extends com.google.cloud.dataproc.v1.SessionOrBuilder>
getSessionsOrBuilderList() {
if (sessionsBuilder_ != null) {
return sessionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(sessions_);
}
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.dataproc.v1.Session.Builder addSessionsBuilder() {
return getSessionsFieldBuilder()
.addBuilder(com.google.cloud.dataproc.v1.Session.getDefaultInstance());
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.dataproc.v1.Session.Builder addSessionsBuilder(int index) {
return getSessionsFieldBuilder()
.addBuilder(index, com.google.cloud.dataproc.v1.Session.getDefaultInstance());
}
/**
*
*
* <pre>
* Output only. The sessions from the specified collection.
* </pre>
*
* <code>
* repeated .google.cloud.dataproc.v1.Session sessions = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public java.util.List<com.google.cloud.dataproc.v1.Session.Builder> getSessionsBuilderList() {
return getSessionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dataproc.v1.Session,
com.google.cloud.dataproc.v1.Session.Builder,
com.google.cloud.dataproc.v1.SessionOrBuilder>
getSessionsFieldBuilder() {
if (sessionsBuilder_ == null) {
sessionsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dataproc.v1.Session,
com.google.cloud.dataproc.v1.Session.Builder,
com.google.cloud.dataproc.v1.SessionOrBuilder>(
sessions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
sessions_ = null;
}
return sessionsBuilder_;
}
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.dataproc.v1.ListSessionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.ListSessionsResponse)
private static final com.google.cloud.dataproc.v1.ListSessionsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.ListSessionsResponse();
}
public static com.google.cloud.dataproc.v1.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.dataproc.v1.ListSessionsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,442 | java-dlp/proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/ListProjectDataProfilesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2/dlp.proto
// Protobuf Java Version: 3.25.8
package com.google.privacy.dlp.v2;
/**
*
*
* <pre>
* List of profiles generated for a given organization or project.
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2.ListProjectDataProfilesResponse}
*/
public final class ListProjectDataProfilesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.privacy.dlp.v2.ListProjectDataProfilesResponse)
ListProjectDataProfilesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListProjectDataProfilesResponse.newBuilder() to construct.
private ListProjectDataProfilesResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListProjectDataProfilesResponse() {
projectDataProfiles_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListProjectDataProfilesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListProjectDataProfilesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListProjectDataProfilesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.class,
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.Builder.class);
}
public static final int PROJECT_DATA_PROFILES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.privacy.dlp.v2.ProjectDataProfile> projectDataProfiles_;
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.privacy.dlp.v2.ProjectDataProfile> getProjectDataProfilesList() {
return projectDataProfiles_;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder>
getProjectDataProfilesOrBuilderList() {
return projectDataProfiles_;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
@java.lang.Override
public int getProjectDataProfilesCount() {
return projectDataProfiles_.size();
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
@java.lang.Override
public com.google.privacy.dlp.v2.ProjectDataProfile getProjectDataProfiles(int index) {
return projectDataProfiles_.get(index);
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
@java.lang.Override
public com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder getProjectDataProfilesOrBuilder(
int index) {
return projectDataProfiles_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < projectDataProfiles_.size(); i++) {
output.writeMessage(1, projectDataProfiles_.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 < projectDataProfiles_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(1, projectDataProfiles_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.privacy.dlp.v2.ListProjectDataProfilesResponse)) {
return super.equals(obj);
}
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse other =
(com.google.privacy.dlp.v2.ListProjectDataProfilesResponse) obj;
if (!getProjectDataProfilesList().equals(other.getProjectDataProfilesList())) 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 (getProjectDataProfilesCount() > 0) {
hash = (37 * hash) + PROJECT_DATA_PROFILES_FIELD_NUMBER;
hash = (53 * hash) + getProjectDataProfilesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse 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 profiles generated for a given organization or project.
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2.ListProjectDataProfilesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2.ListProjectDataProfilesResponse)
com.google.privacy.dlp.v2.ListProjectDataProfilesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListProjectDataProfilesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListProjectDataProfilesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.class,
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.Builder.class);
}
// Construct using com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (projectDataProfilesBuilder_ == null) {
projectDataProfiles_ = java.util.Collections.emptyList();
} else {
projectDataProfiles_ = null;
projectDataProfilesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListProjectDataProfilesResponse_descriptor;
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListProjectDataProfilesResponse getDefaultInstanceForType() {
return com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListProjectDataProfilesResponse build() {
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListProjectDataProfilesResponse buildPartial() {
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse result =
new com.google.privacy.dlp.v2.ListProjectDataProfilesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.privacy.dlp.v2.ListProjectDataProfilesResponse result) {
if (projectDataProfilesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
projectDataProfiles_ = java.util.Collections.unmodifiableList(projectDataProfiles_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.projectDataProfiles_ = projectDataProfiles_;
} else {
result.projectDataProfiles_ = projectDataProfilesBuilder_.build();
}
}
private void buildPartial0(com.google.privacy.dlp.v2.ListProjectDataProfilesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.privacy.dlp.v2.ListProjectDataProfilesResponse) {
return mergeFrom((com.google.privacy.dlp.v2.ListProjectDataProfilesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.privacy.dlp.v2.ListProjectDataProfilesResponse other) {
if (other == com.google.privacy.dlp.v2.ListProjectDataProfilesResponse.getDefaultInstance())
return this;
if (projectDataProfilesBuilder_ == null) {
if (!other.projectDataProfiles_.isEmpty()) {
if (projectDataProfiles_.isEmpty()) {
projectDataProfiles_ = other.projectDataProfiles_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.addAll(other.projectDataProfiles_);
}
onChanged();
}
} else {
if (!other.projectDataProfiles_.isEmpty()) {
if (projectDataProfilesBuilder_.isEmpty()) {
projectDataProfilesBuilder_.dispose();
projectDataProfilesBuilder_ = null;
projectDataProfiles_ = other.projectDataProfiles_;
bitField0_ = (bitField0_ & ~0x00000001);
projectDataProfilesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getProjectDataProfilesFieldBuilder()
: null;
} else {
projectDataProfilesBuilder_.addAllMessages(other.projectDataProfiles_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.privacy.dlp.v2.ProjectDataProfile m =
input.readMessage(
com.google.privacy.dlp.v2.ProjectDataProfile.parser(), extensionRegistry);
if (projectDataProfilesBuilder_ == null) {
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.add(m);
} else {
projectDataProfilesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.privacy.dlp.v2.ProjectDataProfile> projectDataProfiles_ =
java.util.Collections.emptyList();
private void ensureProjectDataProfilesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
projectDataProfiles_ =
new java.util.ArrayList<com.google.privacy.dlp.v2.ProjectDataProfile>(
projectDataProfiles_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2.ProjectDataProfile,
com.google.privacy.dlp.v2.ProjectDataProfile.Builder,
com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder>
projectDataProfilesBuilder_;
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public java.util.List<com.google.privacy.dlp.v2.ProjectDataProfile>
getProjectDataProfilesList() {
if (projectDataProfilesBuilder_ == null) {
return java.util.Collections.unmodifiableList(projectDataProfiles_);
} else {
return projectDataProfilesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public int getProjectDataProfilesCount() {
if (projectDataProfilesBuilder_ == null) {
return projectDataProfiles_.size();
} else {
return projectDataProfilesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public com.google.privacy.dlp.v2.ProjectDataProfile getProjectDataProfiles(int index) {
if (projectDataProfilesBuilder_ == null) {
return projectDataProfiles_.get(index);
} else {
return projectDataProfilesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder setProjectDataProfiles(
int index, com.google.privacy.dlp.v2.ProjectDataProfile value) {
if (projectDataProfilesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.set(index, value);
onChanged();
} else {
projectDataProfilesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder setProjectDataProfiles(
int index, com.google.privacy.dlp.v2.ProjectDataProfile.Builder builderForValue) {
if (projectDataProfilesBuilder_ == null) {
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.set(index, builderForValue.build());
onChanged();
} else {
projectDataProfilesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder addProjectDataProfiles(com.google.privacy.dlp.v2.ProjectDataProfile value) {
if (projectDataProfilesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.add(value);
onChanged();
} else {
projectDataProfilesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder addProjectDataProfiles(
int index, com.google.privacy.dlp.v2.ProjectDataProfile value) {
if (projectDataProfilesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.add(index, value);
onChanged();
} else {
projectDataProfilesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder addProjectDataProfiles(
com.google.privacy.dlp.v2.ProjectDataProfile.Builder builderForValue) {
if (projectDataProfilesBuilder_ == null) {
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.add(builderForValue.build());
onChanged();
} else {
projectDataProfilesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder addProjectDataProfiles(
int index, com.google.privacy.dlp.v2.ProjectDataProfile.Builder builderForValue) {
if (projectDataProfilesBuilder_ == null) {
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.add(index, builderForValue.build());
onChanged();
} else {
projectDataProfilesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder addAllProjectDataProfiles(
java.lang.Iterable<? extends com.google.privacy.dlp.v2.ProjectDataProfile> values) {
if (projectDataProfilesBuilder_ == null) {
ensureProjectDataProfilesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, projectDataProfiles_);
onChanged();
} else {
projectDataProfilesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder clearProjectDataProfiles() {
if (projectDataProfilesBuilder_ == null) {
projectDataProfiles_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
projectDataProfilesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public Builder removeProjectDataProfiles(int index) {
if (projectDataProfilesBuilder_ == null) {
ensureProjectDataProfilesIsMutable();
projectDataProfiles_.remove(index);
onChanged();
} else {
projectDataProfilesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public com.google.privacy.dlp.v2.ProjectDataProfile.Builder getProjectDataProfilesBuilder(
int index) {
return getProjectDataProfilesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder getProjectDataProfilesOrBuilder(
int index) {
if (projectDataProfilesBuilder_ == null) {
return projectDataProfiles_.get(index);
} else {
return projectDataProfilesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public java.util.List<? extends com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder>
getProjectDataProfilesOrBuilderList() {
if (projectDataProfilesBuilder_ != null) {
return projectDataProfilesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(projectDataProfiles_);
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public com.google.privacy.dlp.v2.ProjectDataProfile.Builder addProjectDataProfilesBuilder() {
return getProjectDataProfilesFieldBuilder()
.addBuilder(com.google.privacy.dlp.v2.ProjectDataProfile.getDefaultInstance());
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public com.google.privacy.dlp.v2.ProjectDataProfile.Builder addProjectDataProfilesBuilder(
int index) {
return getProjectDataProfilesFieldBuilder()
.addBuilder(index, com.google.privacy.dlp.v2.ProjectDataProfile.getDefaultInstance());
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.ProjectDataProfile project_data_profiles = 1;</code>
*/
public java.util.List<com.google.privacy.dlp.v2.ProjectDataProfile.Builder>
getProjectDataProfilesBuilderList() {
return getProjectDataProfilesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2.ProjectDataProfile,
com.google.privacy.dlp.v2.ProjectDataProfile.Builder,
com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder>
getProjectDataProfilesFieldBuilder() {
if (projectDataProfilesBuilder_ == null) {
projectDataProfilesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2.ProjectDataProfile,
com.google.privacy.dlp.v2.ProjectDataProfile.Builder,
com.google.privacy.dlp.v2.ProjectDataProfileOrBuilder>(
projectDataProfiles_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
projectDataProfiles_ = null;
}
return projectDataProfilesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2.ListProjectDataProfilesResponse)
}
// @@protoc_insertion_point(class_scope:google.privacy.dlp.v2.ListProjectDataProfilesResponse)
private static final com.google.privacy.dlp.v2.ListProjectDataProfilesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.privacy.dlp.v2.ListProjectDataProfilesResponse();
}
public static com.google.privacy.dlp.v2.ListProjectDataProfilesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListProjectDataProfilesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListProjectDataProfilesResponse>() {
@java.lang.Override
public ListProjectDataProfilesResponse 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<ListProjectDataProfilesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListProjectDataProfilesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListProjectDataProfilesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/coherence | 37,477 | prj/coherence-core/src/main/java/com/tangosol/internal/util/processor/BinaryProcessors.java | /*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package com.tangosol.internal.util.processor;
import com.tangosol.io.ExternalizableLite;
import com.tangosol.io.ReadBuffer;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
import com.tangosol.net.GuardSupport;
import com.tangosol.net.Guardian;
import com.tangosol.net.cache.CacheMap;
import com.tangosol.util.Binary;
import com.tangosol.util.BinaryEntry;
import com.tangosol.util.ExternalizableHelper;
import com.tangosol.util.InvocableMap;
import com.tangosol.util.InvocableMap.EntryProcessor;
import com.tangosol.util.LiteMap;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A utility class of {@link EntryProcessor} classes that use {@link Binary}
* keys and values to avoid needless deserialization.
*
* @author Mahesh Kannan 2019.11.01
* @author Jonathan Knight 2019.11.07
* @since 14.1.2
*/
public final class BinaryProcessors
{
// ----- constructors ---------------------------------------------------
/**
* Utility class must not have public constructor.
*/
private BinaryProcessors()
{
}
/**
* Obtain an instance of the {@link BinaryGetProcessor}.
*
* @return an instance of the {@link BinaryGetProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> get()
{
return BinaryGetProcessor.INSTANCE;
}
/**
* Obtain an instance of the {@link BinaryPutProcessor}.
*
* @param value the serialized value to put into the cache
* @param ttl the expiry value for the entry
*
* @return an instance of the {@link BinaryPutProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> put(Binary value, long ttl)
{
return new BinaryPutProcessor(value, ttl);
}
/**
* Obtain an instance of the {@link BinaryBlindPutProcessor}.
*
* @param value the serialized value to put into the cache
* @param ttl the expiry value for the entry
*
* @return an instance of the {@link BinaryBlindPutProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> blindPut(Binary value, long ttl)
{
return new BinaryBlindPutProcessor(value, ttl);
}
/**
* Obtain an instance of the {@link BinaryPutAllProcessor}.
*
* @param map the {@link Map} of {@link Binary} keys and values to add to the cache
*
* @return an instance of the {@link BinaryPutProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> putAll(Map<Binary, Binary> map)
{
return new BinaryPutAllProcessor(map);
}
/**
* Obtain an instance of the {@link BinaryPutAllProcessor}.
*
* @param map the {@link Map} of {@link Binary} keys and values to add to the cache
* @param cMillis the expiry delay to apply to the entries
*
* @return an instance of the {@link BinaryPutProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> putAll(Map<Binary, Binary> map, long cMillis)
{
return cMillis == CacheMap.EXPIRY_DEFAULT
? new BinaryPutAllProcessor(map)
: new BinaryPutAllWithExpiryProcessor(map, cMillis);
}
/**
* Obtain an instance of the {@link BinaryPutIfAbsentProcessor}.
*
* @param value the serialized value to put into the cache
* @param ttl the expiry value for the entry
*
* @return an instance of the {@link BinaryPutIfAbsentProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> putIfAbsent(Binary value, long ttl)
{
return new BinaryPutIfAbsentProcessor(value, ttl);
}
/**
* Obtain an instance of the {@link BinaryRemoveProcessor}.
*
* @return an instance of the {@link BinaryRemoveProcessor}
*/
public static InvocableMap.EntryProcessor<Binary, Binary, Binary> remove()
{
return BinaryRemoveProcessor.INSTANCE;
}
// ----- class: BaseProcessor -------------------------------------------
/**
* A base {@link com.tangosol.util.InvocableMap.EntryProcessor}.
*
* @param <R> the type of the {@link com.tangosol.util.InvocableMap.EntryProcessor}'s result
*/
public abstract static class BaseProcessor<R>
implements EntryProcessor<Binary, Binary, R>,
ExternalizableLite, PortableObject
{
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput dataInput) throws IOException
{
}
@Override
public void writeExternal(DataOutput dataOutput) throws IOException
{
}
@Override
public void readExternal(PofReader pofReader) throws IOException
{
}
@Override
public void writeExternal(PofWriter pofWriter) throws IOException
{
}
}
// ----- class: BinaryProcessorWithValue --------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that contains a value.
*
* @param <T> the return type of this {@link EntryProcessor}
*/
public abstract static class BinaryProcessorWithValue<T>
extends BaseProcessor<T>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
protected BinaryProcessorWithValue()
{
}
/**
* Create a {@link BinaryProcessorWithValue}.
*
* @param value the {@link com.tangosol.util.Binary} value to set as the
* cache entry value
*/
protected BinaryProcessorWithValue(Binary value)
{
this.m_binValue = value;
}
// ----- helper methods ---------------------------------------------
/**
* Return the {@link Binary} value.
*
* @return the {@link Binary} value
*/
protected Binary getValue()
{
return m_binValue;
}
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput in) throws IOException
{
m_binValue = ExternalizableHelper.readObject(in);
}
@Override
public void writeExternal(DataOutput out) throws IOException
{
ExternalizableHelper.writeObject(out, m_binValue);
}
@Override
public void readExternal(PofReader pofReader) throws IOException
{
m_binValue = pofReader.readBinary(2);
}
@Override
public void writeExternal(PofWriter pofWriter) throws IOException
{
pofWriter.writeBinary(2, m_binValue);
}
// ----- data members -----------------------------------------------
/**
* The {@link com.tangosol.util.Binary} that is used by this
* {@link com.tangosol.util.InvocableMap.EntryProcessor}.
*/
protected Binary m_binValue;
}
// ----- class: BinaryContainsValueProcessor ----------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that checks if the mapping for the
* key exists in the cache.
*/
public static class BinaryContainsValueProcessor
extends BinaryProcessorWithValue<Boolean>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
@SuppressWarnings("unused")
public BinaryContainsValueProcessor()
{
}
/**
* Create a {@link BinaryContainsValueProcessor}.
*
* @param value the {@link com.tangosol.util.Binary} value to check
*/
public BinaryContainsValueProcessor(Binary value)
{
super(value);
}
// ----- Processor interface ----------------------------------------
@Override
public Boolean process(InvocableMap.Entry<Binary, Binary> entry)
{
if (entry.isPresent())
{
Binary bin = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
ReadBuffer buffer = ExternalizableHelper.getUndecorated((ReadBuffer) bin);
return getValue().equals(buffer.toBinary());
}
return false;
}
}
// ----- class: BinarySyntheticRemoveBlindProcessor ---------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that removes a cache entry
* without de-serializing keys or values and returns no
* result.
*/
public static class BinarySyntheticRemoveBlindProcessor
extends BaseProcessor<Void>
{
// ----- Processor interface ----------------------------------------
@Override
public Void process(InvocableMap.Entry<Binary, Binary> entry)
{
if (entry.isPresent())
{
entry.remove(true);
}
return null;
}
// ----- EntryProcessor methods -------------------------------------
@Override
public Map<Binary, Void> processAll(Set<? extends InvocableMap.Entry<Binary, Binary>> entries)
{
Guardian.GuardContext ctxGuard = GuardSupport.getThreadContext();
long cMillis = ctxGuard == null ? 0L : ctxGuard.getTimeoutMillis();
Iterator<? extends InvocableMap.Entry<Binary, Binary>> iter = entries.iterator();
while (iter.hasNext())
{
InvocableMap.Entry<Binary, Binary> entry = iter.next();
process(entry);
iter.remove();
if (ctxGuard != null)
{
ctxGuard.heartbeat(cMillis);
}
}
return Collections.emptyMap();
}
// ----- constants --------------------------------------------------
/**
* Singleton RemoveBlindProcessor.
*/
public static final BinarySyntheticRemoveBlindProcessor INSTANCE = new BinarySyntheticRemoveBlindProcessor();
}
// ----- class: BinaryPutProcessor --------------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that updates the mapping
* of a key to a value in a cache.
*/
public static class BinaryPutProcessor
extends BaseProcessor<Binary>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
public BinaryPutProcessor()
{
}
/**
* Create a {@link BinaryPutProcessor}.
*
* @param value the {@link com.tangosol.util.Binary} value to set as the
* cache entry value
* @param cTtl the expiry value for the entry
*/
BinaryPutProcessor(Binary value, long cTtl)
{
this.m_binValue = value;
this.m_cTtl = cTtl;
}
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
BinaryEntry<Binary, Binary> binaryEntry = (BinaryEntry<Binary, Binary>) entry;
Binary result = null;
if (entry.isPresent())
{
result = binaryEntry.getBinaryValue();
}
binaryEntry.updateBinaryValue(m_binValue);
binaryEntry.expire(m_cTtl);
return result;
}
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput in) throws IOException
{
m_binValue = ExternalizableHelper.readObject(in);
m_cTtl = in.readLong();
}
@Override
public void writeExternal(DataOutput out) throws IOException
{
ExternalizableHelper.writeObject(out, m_binValue);
out.writeLong(m_cTtl);
}
@Override
public void readExternal(PofReader in) throws IOException
{
m_binValue = in.readBinary(0);
m_cTtl = in.readLong(1);
}
@Override
public void writeExternal(PofWriter out) throws IOException
{
out.writeBinary(0, m_binValue);
out.writeLong(1, m_cTtl);
}
// ----- helper methods ---------------------------------------------
/**
* Return the {@link Binary} value.
*
* @return the {@link Binary} value
*/
protected Binary getValue()
{
return m_binValue;
}
/**
* Return the {@code TTL}.
*
* @return the {@code TTL}
*/
protected long getTtl()
{
return m_cTtl;
}
// ----- data members -----------------------------------------------
/**
* The {@link Binary} value to map to the entry.
*/
protected Binary m_binValue;
/**
* The expiry value for the entry.
*/
protected long m_cTtl;
}
// ----- class: BinaryBlindPutProcessor ---------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that updates the mapping
* of a key to a value in a cache.
*/
public static class BinaryBlindPutProcessor
extends BaseProcessor<Binary>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
public BinaryBlindPutProcessor()
{
}
/**
* Create a {@link BinaryPutProcessor}.
*
* @param value the {@link com.tangosol.util.Binary} value to set as the
* cache entry value
* @param cTtl the expiry value for the entry
*/
BinaryBlindPutProcessor(Binary value, long cTtl)
{
this.m_binValue = value;
this.m_cTtl = cTtl;
}
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
BinaryEntry<Binary, Binary> binaryEntry = (BinaryEntry<Binary, Binary>) entry;
binaryEntry.updateBinaryValue(m_binValue);
binaryEntry.expire(m_cTtl);
return null;
}
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput in) throws IOException
{
m_binValue = ExternalizableHelper.readObject(in);
m_cTtl = in.readLong();
}
@Override
public void writeExternal(DataOutput out) throws IOException
{
ExternalizableHelper.writeObject(out, m_binValue);
out.writeLong(m_cTtl);
}
@Override
public void readExternal(PofReader in) throws IOException
{
m_binValue = in.readBinary(0);
m_cTtl = in.readLong(1);
}
@Override
public void writeExternal(PofWriter out) throws IOException
{
out.writeBinary(0, m_binValue);
out.writeLong(1, m_cTtl);
}
// ----- helper methods ---------------------------------------------
/**
* Return the {@link Binary} value.
*
* @return the {@link Binary} value
*/
protected Binary getValue()
{
return m_binValue;
}
/**
* Return the {@code TTL}.
*
* @return the {@code TTL}
*/
protected long getTtl()
{
return m_cTtl;
}
// ----- data members -----------------------------------------------
/**
* The {@link Binary} value to map to the entry.
*/
protected Binary m_binValue;
/**
* The expiry value for the entry.
*/
protected long m_cTtl;
}
// ----- class: BinaryPutAllProcessor -----------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that updates the mapping
* of a number of key to values in a cache.
*/
public static class BinaryPutAllProcessor
extends BaseProcessor<Binary>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
@SuppressWarnings("unused")
public BinaryPutAllProcessor()
{
this(new HashMap<>());
}
/**
* Create a {@link BinaryPutAllProcessor}.
*
* @param map the {@link Map} of {@link Binary} key and values to add to the cache
*/
BinaryPutAllProcessor(Map<Binary, Binary> map)
{
this.m_map = map;
}
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
BinaryEntry<Binary, Binary> binaryEntry = (BinaryEntry<Binary, Binary>) entry;
Binary binaryKey = binaryEntry.getBinaryKey();
Binary binary = m_map.get(binaryKey);
if (binary == null)
{
// try the undecorated key
Binary binNoDeco = ExternalizableHelper.getUndecorated((ReadBuffer) binaryKey).toBinary();
binary = m_map.get(binNoDeco);
}
if (binary == null)
{
entry.setValue(null);
}
else
{
binaryEntry.updateBinaryValue(binary);
}
return null;
}
// ----- EntryProcessor methods -------------------------------------
@Override
public Map<Binary, Binary> processAll(Set<? extends InvocableMap.Entry<Binary, Binary>> entries)
{
Guardian.GuardContext ctxGuard = GuardSupport.getThreadContext();
long cMillis = ctxGuard == null ? 0L : ctxGuard.getTimeoutMillis();
Iterator<? extends InvocableMap.Entry<Binary, Binary>> iterator = entries.iterator();
while (iterator.hasNext())
{
InvocableMap.Entry<Binary, Binary> entry = iterator.next();
this.process(entry);
iterator.remove();
if (ctxGuard != null)
{
ctxGuard.heartbeat(cMillis);
}
}
return new LiteMap<>();
}
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput in) throws IOException
{
ExternalizableHelper.readMap(in, this.m_map, null);
}
@Override
public void writeExternal(DataOutput out) throws IOException
{
ExternalizableHelper.writeMap(out, this.m_map);
}
@Override
public void readExternal(PofReader in) throws IOException
{
this.m_map = in.readMap(0, new HashMap<>());
}
@Override
public void writeExternal(PofWriter out) throws IOException
{
out.writeMap(0, this.m_map, Binary.class, Binary.class);
}
// ----- helper methods ---------------------------------------------
/**
* Returns the map of keys and values that were/are to be stored.
*
* @return the map of keys and values that were/are to be stored
*/
Map<Binary, Binary> getMap()
{
return m_map;
}
// ----- data members ----------------------------------------------0
/**
* The {@link Binary} value to map to the entry.
*/
protected Map<Binary, Binary> m_map;
}
// ----- class: BinaryPutAllProcessor -----------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that updates the mapping
* of a number of key to values in a cache.
*/
public static class BinaryPutAllWithExpiryProcessor
extends BaseProcessor<Binary>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
@SuppressWarnings("unused")
public BinaryPutAllWithExpiryProcessor()
{
this(new HashMap<>(), CacheMap.EXPIRY_DEFAULT);
}
/**
* Create a {@link BinaryPutAllProcessor}.
*
* @param map the {@link Map} of {@link Binary} key and values to add to the cache
*/
BinaryPutAllWithExpiryProcessor(Map<Binary, Binary> map, long cMillis)
{
m_map = map;
m_cMillis = cMillis;
}
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
BinaryEntry<Binary, Binary> binaryEntry = (BinaryEntry<Binary, Binary>) entry;
Binary binaryKey = binaryEntry.getBinaryKey();
Binary binary = m_map.get(binaryKey);
if (binary == null)
{
// try the undecorated key
Binary binNoDeco = ExternalizableHelper.getUndecorated((ReadBuffer) binaryKey).toBinary();
binary = m_map.get(binNoDeco);
}
if (binary == null)
{
entry.setValue(null);
}
else
{
binaryEntry.updateBinaryValue(binary);
}
binaryEntry.expire(m_cMillis);
return null;
}
// ----- EntryProcessor methods -------------------------------------
@Override
public Map<Binary, Binary> processAll(Set<? extends InvocableMap.Entry<Binary, Binary>> entries)
{
Guardian.GuardContext ctxGuard = GuardSupport.getThreadContext();
long cMillis = ctxGuard == null ? 0L : ctxGuard.getTimeoutMillis();
Iterator<? extends InvocableMap.Entry<Binary, Binary>> iterator = entries.iterator();
while (iterator.hasNext())
{
InvocableMap.Entry<Binary, Binary> entry = iterator.next();
process(entry);
iterator.remove();
if (ctxGuard != null)
{
ctxGuard.heartbeat(cMillis);
}
}
return new LiteMap<>();
}
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput in) throws IOException
{
ExternalizableHelper.readMap(in, m_map, null);
m_cMillis = in.readLong();
}
@Override
public void writeExternal(DataOutput out) throws IOException
{
ExternalizableHelper.writeMap(out, m_map);
out.writeLong(m_cMillis);
}
@Override
public void readExternal(PofReader in) throws IOException
{
m_map = in.readMap(0, new HashMap<>());
m_cMillis = in.readLong(1);
}
@Override
public void writeExternal(PofWriter out) throws IOException
{
out.writeMap(0, m_map, Binary.class, Binary.class);
out.writeLong(1, m_cMillis);
}
// ----- helper methods ---------------------------------------------
/**
* Returns the map of keys and values that were/are to be stored.
*
* @return the map of keys and values that were/are to be stored
*/
Map<Binary, Binary> getMap()
{
return m_map;
}
/**
* Return the expiry delay.
*
* @return the expiry delay
*/
public long getExpiry()
{
return m_cMillis;
}
// ----- data members ----------------------------------------------0
/**
* The {@link Binary} value to map to the entry.
*/
protected Map<Binary, Binary> m_map;
/**
* The expiry delay for the entries.
*/
protected long m_cMillis;
}
// ----- class: BinaryPutIfAbsentProcessor ------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that puts the specified value in the cache
* only if there is no existing mapping for the key.
*/
public static class BinaryPutIfAbsentProcessor
extends BinaryPutProcessor
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
@SuppressWarnings("unused")
public BinaryPutIfAbsentProcessor()
{
}
/**
* Create a {@link BinaryPutIfAbsentProcessor}.
*
* @param value the {@link com.tangosol.util.Binary} value to set as the
* cache entry value
* @param cTtl the expiry value for the entry
*/
BinaryPutIfAbsentProcessor(Binary value, long cTtl)
{
super(value, cTtl);
}
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
if (entry.isPresent())
{
BinaryEntry<Binary, Binary> binaryEntry = entry.asBinaryEntry();
Binary binNull = (Binary) binaryEntry.getContext()
.getValueToInternalConverter().convert(null);
Binary binary = binaryEntry.getBinaryValue();
if (!ExternalizableHelper.getUndecorated(binary).equals(binNull))
{
return binary;
}
}
return super.process(entry);
}
}
// ----- class: BinaryGetProcessor --------------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that obtains the {@link com.tangosol.util.Binary}
* value mapped to a given key in a cache.
*/
public static class BinaryGetProcessor
extends BaseProcessor<Binary>
{
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
Binary prevValue = null;
if (entry.isPresent())
{
prevValue = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
}
else
{
entry.getValue(); // maybe trigger a CacheStore load
if (entry.isPresent())
{
prevValue = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
}
}
return prevValue;
}
// ----- EntryProcessor methods -------------------------------------
@Override
public Map<Binary, Binary> processAll(Set<? extends InvocableMap.Entry<Binary, Binary>> setEntries)
{
Map<Binary, Binary> mapResults = new LiteMap<>();
Guardian.GuardContext ctxGuard = GuardSupport.getThreadContext();
long cMillis = ctxGuard == null ? 0L : ctxGuard.getTimeoutMillis();
Iterator<? extends InvocableMap.Entry<Binary, Binary>> iter = setEntries.iterator();
while (iter.hasNext())
{
InvocableMap.Entry<Binary, Binary> entry = iter.next();
if (entry.isPresent())
{
mapResults.put(((BinaryEntry<Binary, Binary>) entry).getBinaryKey(), this.process(entry));
}
else
{
entry.getValue(); // maybe trigger a CacheStore load
if (entry.isPresent())
{
mapResults.put(((BinaryEntry<Binary, Binary>) entry).getBinaryKey(), this.process(entry));
}
}
iter.remove();
if (ctxGuard != null)
{
ctxGuard.heartbeat(cMillis);
}
}
return mapResults;
}
// ----- constants --------------------------------------------------
/**
* The singleton {@link BinaryGetProcessor}.
*/
public static final BinaryGetProcessor INSTANCE = new BinaryGetProcessor();
}
// ----- class: BinaryRemoveProcessor -----------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that obtains the {@link com.tangosol.util.Binary}
* value mapped to a given key in a cache.
*/
public static class BinaryRemoveProcessor
extends BaseProcessor<Binary>
{
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
Binary prevValue = null;
if (entry.isPresent())
{
prevValue = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
entry.remove(false);
}
else
{
entry.getValue(); // maybe trigger a CacheStore load...
if (entry.isPresent())
{
prevValue = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
entry.remove(false);
}
}
return prevValue;
}
// ----- constants --------------------------------------------------
/**
* The singleton {@link BinaryRemoveProcessor}.
*/
public static final BinaryRemoveProcessor INSTANCE = new BinaryRemoveProcessor();
}
// ----- class: BinaryReplaceProcessor ----------------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that replaces an existing mapping in a cache.
*/
public static class BinaryReplaceProcessor
extends BinaryProcessorWithValue<Binary>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
@SuppressWarnings("unused")
public BinaryReplaceProcessor()
{
}
/**
* Create a {@link BinaryReplaceProcessor}.
*
* @param value the {@link Binary} value to set as the
* cache entry value
*/
public BinaryReplaceProcessor(Binary value)
{
super(value);
}
// ----- Processor interface ----------------------------------------
@Override
public Binary process(InvocableMap.Entry<Binary, Binary> entry)
{
Binary result = null;
if (entry.isPresent())
{
result = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
((BinaryEntry<Binary, Binary>) entry).updateBinaryValue(getValue());
}
return result;
}
}
// ----- class: BinaryReplaceMappingProcessor ---------------------------
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} that replaces a specific existing mapping in a cache.
*/
public static class BinaryReplaceMappingProcessor
extends BinaryProcessorWithValue<Boolean>
{
// ----- constructors -----------------------------------------------
/**
* Default constructor for serialization.
*/
@SuppressWarnings("unused")
public BinaryReplaceMappingProcessor()
{
}
/**
* Create a {@link BinaryReplaceMappingProcessor}.
*
* @param previousValue the {@link com.tangosol.util.Binary} value of the existing mapping
* @param newValue the {@link com.tangosol.util.Binary} value of the new mapping
*/
public BinaryReplaceMappingProcessor(Binary previousValue, Binary newValue)
{
super(previousValue);
this.m_binNewValue = newValue;
}
// ----- static factory methods -------------------------------------
/**
* Create an instance of {@link BinaryReplaceMappingProcessor}.
*
* @param previousValue the {@link com.tangosol.util.Binary} value of the existing mapping
* @param newValue the {@link com.tangosol.util.Binary} value of the new mapping
*
* @return an instance of {@link BinaryReplaceMappingProcessor}
*/
public static BinaryReplaceMappingProcessor create(Binary previousValue, Binary newValue)
{
return new BinaryReplaceMappingProcessor(previousValue, newValue);
}
// ----- Processor interface ----------------------------------------
@Override
public Boolean process(InvocableMap.Entry<Binary, Binary> entry)
{
boolean result = false;
if (entry.isPresent())
{
Binary prevValue = ((BinaryEntry<Binary, Binary>) entry).getBinaryValue();
if (prevValue.equals(getValue()))
{
((BinaryEntry<Binary, Binary>) entry).updateBinaryValue(m_binNewValue);
result = true;
}
}
return result;
}
// ----- helper methods ---------------------------------------------
/**
* Return the new {@link Binary} value.
*
* @return the new {@link Binary} value
*/
protected Binary getNewValue()
{
return m_binNewValue;
}
// ----- ExternalizableLite interface -------------------------------
@Override
public void readExternal(DataInput in) throws IOException
{
super.readExternal(in);
m_binNewValue = ExternalizableHelper.readObject(in);
}
@Override
public void writeExternal(DataOutput out) throws IOException
{
super.writeExternal(out);
ExternalizableHelper.writeObject(out, m_binNewValue);
}
@Override
public void readExternal(PofReader pofReader) throws IOException
{
super.readExternal(pofReader);
m_binNewValue = pofReader.readBinary(5);
}
@Override
public void writeExternal(PofWriter pofWriter) throws IOException
{
super.writeExternal(pofWriter);
pofWriter.writeBinary(5, m_binNewValue);
}
// ----- data members -----------------------------------------------
/**
* New {@link Binary} value.
*/
protected Binary m_binNewValue;
}
}
|
apache/hop | 37,462 | ui/src/main/java/org/apache/hop/ui/core/database/dialog/DatabaseExplorerDialog.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.database.dialog;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.hop.core.Const;
import org.apache.hop.core.DbCache;
import org.apache.hop.core.Props;
import org.apache.hop.core.database.Catalog;
import org.apache.hop.core.database.Database;
import org.apache.hop.core.database.DatabaseMeta;
import org.apache.hop.core.database.DatabaseMetaInformation;
import org.apache.hop.core.database.Schema;
import org.apache.hop.core.exception.HopDatabaseException;
import org.apache.hop.core.gui.plugin.GuiPlugin;
import org.apache.hop.core.gui.plugin.toolbar.GuiToolbarElement;
import org.apache.hop.core.gui.plugin.toolbar.GuiToolbarElementType;
import org.apache.hop.core.logging.ILogChannel;
import org.apache.hop.core.logging.ILoggingObject;
import org.apache.hop.core.logging.LogChannel;
import org.apache.hop.core.logging.LoggingObject;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.ui.core.ConstUi;
import org.apache.hop.ui.core.PropsUi;
import org.apache.hop.ui.core.dialog.EnterNumberDialog;
import org.apache.hop.ui.core.dialog.EnterSelectionDialog;
import org.apache.hop.ui.core.dialog.ErrorDialog;
import org.apache.hop.ui.core.dialog.MessageBox;
import org.apache.hop.ui.core.dialog.PreviewRowsDialog;
import org.apache.hop.ui.core.dialog.TransformFieldsDialog;
import org.apache.hop.ui.core.gui.GuiResource;
import org.apache.hop.ui.core.gui.GuiToolbarWidgets;
import org.apache.hop.ui.core.gui.WindowProperty;
import org.apache.hop.ui.hopgui.HopGui;
import org.apache.hop.ui.pipeline.transform.BaseTransformDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/**
* This dialog represents an explorer type of interface on a given database connection. It shows the
* tables defined in the visible schemas or catalogs on that connection. The interface also allows
* you to get all kinds of information on those tables.
*/
@GuiPlugin
public class DatabaseExplorerDialog extends Dialog {
private static final Class<?> PKG = DatabaseExplorerDialog.class;
public static final String GUI_PLUGIN_TOOLBAR_PARENT_ID = "DatabaseExplorerDialog-Toolbar";
public static final String TOOLBAR_ITEM_EXPAND_ALL = "DatabaseExplorer-ToolBar-10100-ExpandAll";
public static final String TOOLBAR_ITEM_COLLAPSE_ALL =
"DatabaseExplorer-ToolBar-10200-CollapseAll";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_100 =
"DatabaseExplorerDialog.Menu.Preview100";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_N =
"DatabaseExplorerDialog.Menu.PreviewN";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_SIZE =
"DatabaseExplorerDialog.Menu.ShowSize";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_LAYOUT =
"DatabaseExplorerDialog.Menu.ShowLayout";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_OPEN_SQL =
"DatabaseExplorerDialog.Menu.OpenSQL";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDL =
"DatabaseExplorerDialog.Menu.GenDDL";
public static final String CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDLOTHER_CONN =
"DatabaseExplorerDialog.Menu.GenDDLOtherConn";
private final ILogChannel log;
private final PropsUi props;
private DatabaseMeta dbMeta;
private final IVariables variables;
private final DbCache dbcache;
private final ILoggingObject loggingObject;
private static final String STRING_CATALOG =
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Catalogs.Label");
private static final String STRING_SCHEMAS =
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Schemas.Label");
private static final String STRING_TABLES =
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Tables.Label");
private static final String STRING_VIEWS =
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Views.Label");
private static final String STRING_SYNONYMS =
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Synonyms.Label");
private final Shell parent;
private Shell shell;
private Tree wTree;
private TreeItem tiTree;
private String tableName;
private final boolean justLook;
private String selectedSchema;
private String selectedTable;
private final List<DatabaseMeta> databases;
private boolean splitSchemaAndTable;
private String schemaName;
private Composite buttonsComposite;
private Button bPrev;
private Button bPrevN;
private Button bCount;
private Button bShow;
private Button bDDL;
private Button bDDL2;
private Button bSql;
private String activeSchemaTable;
private Button bTruncate;
private ToolBar toolBar;
public DatabaseExplorerDialog(
Shell parent,
int style,
IVariables variables,
DatabaseMeta conn,
List<DatabaseMeta> databases) {
this(parent, style, variables, conn, databases, false, true);
}
public DatabaseExplorerDialog(
Shell parent,
int style,
IVariables variables,
DatabaseMeta conn,
List<DatabaseMeta> databases,
boolean look,
boolean splitSchemaAndTable) {
super(parent, style);
this.parent = parent;
this.dbMeta = conn;
this.variables = variables;
this.databases = databases;
this.justLook = look;
this.splitSchemaAndTable = splitSchemaAndTable;
this.loggingObject = new LoggingObject("Database Explorer");
selectedSchema = null;
selectedTable = null;
props = PropsUi.getInstance();
log = new LogChannel("DBExplorer");
dbcache = DbCache.getInstance();
}
public void setSelectedTable(String selectedTable) {
this.selectedTable = selectedTable;
}
public boolean open() {
tableName = null;
if (Const.isLinux()) {
shell =
new Shell(
parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
} else {
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
}
PropsUi.setLook(shell);
shell.setImage(GuiResource.getInstance().getImageDatabase());
shell.setText(BaseMessages.getString(PKG, "DatabaseExplorerDialog.Title", dbMeta.toString()));
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = PropsUi.getFormMargin();
formLayout.marginHeight = PropsUi.getFormMargin();
shell.setLayout(formLayout);
int margin = PropsUi.getMargin();
// Main buttons at the bottom
//
List<Button> buttons = new ArrayList<>();
Button wOk = new Button(shell, SWT.PUSH);
wOk.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wOk.addListener(SWT.Selection, e -> ok());
buttons.add(wOk);
Button wRefresh = new Button(shell, SWT.PUSH);
wRefresh.setText(BaseMessages.getString(PKG, "System.Button.Refresh"));
wRefresh.addListener(SWT.Selection, e -> getData());
buttons.add(wRefresh);
if (!justLook) {
Button wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
wCancel.addListener(SWT.Selection, e -> cancel());
buttons.add(wCancel);
}
BaseTransformDialog.positionBottomButtons(shell, buttons.toArray(new Button[0]), margin, null);
// Add a toolbar
//
toolBar = new ToolBar(shell, SWT.WRAP | SWT.LEFT | SWT.HORIZONTAL);
GuiToolbarWidgets toolBarWidgets = new GuiToolbarWidgets();
toolBarWidgets.registerGuiPluginObject(this);
toolBarWidgets.createToolbarWidgets(toolBar, GUI_PLUGIN_TOOLBAR_PARENT_ID);
FormData layoutData = new FormData();
layoutData.top = new FormAttachment(0, 0);
layoutData.left = new FormAttachment(0, 0);
layoutData.right = new FormAttachment(100, 0);
toolBar.setLayoutData(layoutData);
toolBar.pack();
PropsUi.setLook(toolBar, Props.WIDGET_STYLE_TOOLBAR);
addRightButtons();
refreshButtons(null);
// Tree
wTree = new Tree(shell, SWT.SINGLE | SWT.BORDER /*| (multiple?SWT.CHECK:SWT.NONE)*/);
PropsUi.setLook(wTree);
FormData fdTree = new FormData();
fdTree.left = new FormAttachment(0, 0); // To the right of the label
fdTree.top = new FormAttachment(toolBar, margin);
fdTree.right = new FormAttachment(buttonsComposite, -margin);
fdTree.bottom = new FormAttachment(wOk, -2 * margin);
wTree.setLayoutData(fdTree);
if (!getData()) {
return false;
}
wTree.addListener(SWT.Selection, e -> refreshButtons(getSchemaTable()));
wTree.addListener(SWT.DefaultSelection, this::openSchema);
wTree.addListener(
SWT.MouseDown,
e -> {
if (e.button == 3) // right click!
{
setTreeMenu();
}
});
shell.addListener(SWT.Close, e -> cancel());
BaseTransformDialog.setSize(shell);
shell.open();
// Handle the event loop until we're done with this shell...
//
Display display = shell.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return tableName != null;
}
private void cancel() {
log.logBasic("SelectTableDialog", "CANCEL SelectTableDialog", null);
dbMeta = null;
dispose();
}
private void addRightButtons() {
buttonsComposite = new Composite(shell, SWT.NONE);
PropsUi.setLook(buttonsComposite);
buttonsComposite.setLayout(new FormLayout());
activeSchemaTable = null;
bPrev = new Button(buttonsComposite, SWT.PUSH);
bPrev.setText(
BaseMessages.getString(
PKG,
CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_100,
Const.NVL(activeSchemaTable, "?")));
bPrev.setEnabled(activeSchemaTable != null);
bPrev.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
previewTable(activeSchemaTable, false);
}
});
FormData prevData = new FormData();
prevData.left = new FormAttachment(0, 0);
prevData.right = new FormAttachment(100, 0);
prevData.top = new FormAttachment(0, 0);
bPrev.setLayoutData(prevData);
bPrevN = new Button(buttonsComposite, SWT.PUSH);
bPrevN.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_N, Const.NVL(activeSchemaTable, "?")));
bPrevN.setEnabled(activeSchemaTable != null);
bPrevN.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
previewTable(activeSchemaTable, true);
}
});
FormData prevNData = new FormData();
prevNData.left = new FormAttachment(0, 0);
prevNData.right = new FormAttachment(100, 0);
prevNData.top = new FormAttachment(bPrev, PropsUi.getMargin());
bPrevN.setLayoutData(prevNData);
bCount = new Button(buttonsComposite, SWT.PUSH);
bCount.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_SIZE, Const.NVL(activeSchemaTable, "?")));
bCount.setEnabled(activeSchemaTable != null);
bCount.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
showCount(activeSchemaTable);
}
});
FormData countData = new FormData();
countData.left = new FormAttachment(0, 0);
countData.right = new FormAttachment(100, 0);
countData.top = new FormAttachment(bPrevN, PropsUi.getMargin());
bCount.setLayoutData(countData);
bShow = new Button(buttonsComposite, SWT.PUSH);
bShow.setText(
BaseMessages.getString(
PKG,
CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_LAYOUT,
Const.NVL(activeSchemaTable, "?")));
bShow.setEnabled(activeSchemaTable != null);
bShow.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
showTable(activeSchemaTable);
}
});
FormData showData = new FormData();
showData.left = new FormAttachment(0, 0);
showData.right = new FormAttachment(100, 0);
showData.top = new FormAttachment(bCount, PropsUi.getMargin() * 7);
bShow.setLayoutData(showData);
bDDL = new Button(buttonsComposite, SWT.PUSH);
bDDL.setText(BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDL));
bDDL.setEnabled(activeSchemaTable != null);
bDDL.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getDDL(activeSchemaTable);
}
});
FormData ddlData = new FormData();
ddlData.left = new FormAttachment(0, 0);
ddlData.right = new FormAttachment(100, 0);
ddlData.top = new FormAttachment(bShow, PropsUi.getMargin());
bDDL.setLayoutData(ddlData);
bDDL2 = new Button(buttonsComposite, SWT.PUSH);
bDDL2.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDLOTHER_CONN));
bDDL2.setEnabled(activeSchemaTable != null);
bDDL2.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getDDLForOther(activeSchemaTable);
}
});
bDDL2.setEnabled(databases != null);
FormData ddl2Data = new FormData();
ddl2Data.left = new FormAttachment(0, 0);
ddl2Data.right = new FormAttachment(100, 0);
ddl2Data.top = new FormAttachment(bDDL, PropsUi.getMargin());
bDDL2.setLayoutData(ddl2Data);
bSql = new Button(buttonsComposite, SWT.PUSH);
bSql.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_OPEN_SQL, Const.NVL(activeSchemaTable, "?")));
bSql.setEnabled(activeSchemaTable != null);
bSql.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getSql(activeSchemaTable);
}
});
FormData sqlData = new FormData();
sqlData.left = new FormAttachment(0, 0);
sqlData.right = new FormAttachment(100, 0);
sqlData.top = new FormAttachment(bDDL2, PropsUi.getMargin());
bSql.setLayoutData(sqlData);
bTruncate = new Button(buttonsComposite, SWT.PUSH);
bTruncate.setText(
BaseMessages.getString(
PKG, "DatabaseExplorerDialog.Menu.Truncate", Const.NVL(activeSchemaTable, "?")));
bTruncate.setEnabled(activeSchemaTable != null);
bTruncate.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getTruncate(activeSchemaTable);
}
});
FormData truncateData = new FormData();
truncateData.left = new FormAttachment(0, 0);
truncateData.right = new FormAttachment(100, 0);
truncateData.top = new FormAttachment(bSql, PropsUi.getMargin() * 7);
bTruncate.setLayoutData(truncateData);
FormData fdComposite = new FormData();
fdComposite.right = new FormAttachment(100, 0);
fdComposite.top = new FormAttachment(0, toolBar.getBounds().height);
buttonsComposite.setLayoutData(fdComposite);
}
@GuiToolbarElement(
root = GUI_PLUGIN_TOOLBAR_PARENT_ID,
id = TOOLBAR_ITEM_EXPAND_ALL,
toolTip = "i18n::DatabaseExplorerDialog.Toolbar.ExpandAll.Tooltip",
type = GuiToolbarElementType.BUTTON,
image = "ui/images/expand-all.svg")
public void expandAll() {
expandAllItems(wTree.getItems(), true);
}
@GuiToolbarElement(
root = GUI_PLUGIN_TOOLBAR_PARENT_ID,
id = TOOLBAR_ITEM_COLLAPSE_ALL,
toolTip = "i18n::DatabaseExplorerDialog.Toolbar.CollapseAll.Tooltip",
type = GuiToolbarElementType.BUTTON,
image = "ui/images/collapse-all.svg")
public void collapseAll() {
expandAllItems(wTree.getItems(), false);
}
private void expandAllItems(TreeItem[] treeitems, boolean expand) {
for (TreeItem item : treeitems) {
item.setExpanded(expand);
if (item.getItemCount() > 0) {
expandAllItems(item.getItems(), expand);
}
}
}
private void refreshButtons(String table) {
activeSchemaTable = table;
bPrev.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_100, Const.NVL(table, "?")));
bPrev.setEnabled(table != null);
bPrevN.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_N, Const.NVL(table, "?")));
bPrevN.setEnabled(table != null);
bCount.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_SIZE, Const.NVL(table, "?")));
bCount.setEnabled(table != null);
bShow.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_LAYOUT, Const.NVL(table, "?")));
bShow.setEnabled(table != null);
bDDL.setText(BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDL));
bDDL.setEnabled(table != null);
bDDL2.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDLOTHER_CONN));
bDDL2.setEnabled(table != null);
bSql.setText(
BaseMessages.getString(
PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_OPEN_SQL, Const.NVL(table, "?")));
bSql.setEnabled(table != null);
bTruncate.setText(
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Menu.Truncate", Const.NVL(table, "?")));
bTruncate.setEnabled(table != null);
shell.layout(true, true);
}
private boolean getData() {
GetDatabaseInfoProgressDialog gdipd =
new GetDatabaseInfoProgressDialog(shell, variables, dbMeta);
DatabaseMetaInformation dmi = gdipd.open();
if (dmi != null) {
// Clear the tree top entry
if (tiTree != null && !tiTree.isDisposed()) {
tiTree.dispose();
}
// New entry in the tree
tiTree = new TreeItem(wTree, SWT.NONE);
tiTree.setImage(GuiResource.getInstance().getImageDatabase());
tiTree.setText(dbMeta == null ? "" : dbMeta.getName());
// Show the catalogs...
Catalog[] catalogs = dmi.getCatalogs();
if (catalogs != null) {
TreeItem tiCat = new TreeItem(tiTree, SWT.NONE);
tiCat.setImage(GuiResource.getInstance().getImageFolder());
tiCat.setText(STRING_CATALOG);
for (int i = 0; i < catalogs.length; i++) {
TreeItem newCat = new TreeItem(tiCat, SWT.NONE);
newCat.setImage(GuiResource.getInstance().getImageFolder());
newCat.setText(catalogs[i].getCatalogName());
for (int j = 0; j < catalogs[i].getItems().length; j++) {
String tableName = catalogs[i].getItems()[j];
TreeItem ti = new TreeItem(newCat, SWT.NONE);
ti.setImage(GuiResource.getInstance().getImageTable());
ti.setText(tableName);
}
}
}
// The schema's
Schema[] schemas = dmi.getSchemas();
if (schemas != null) {
TreeItem tiSch = new TreeItem(tiTree, SWT.NONE);
tiSch.setImage(GuiResource.getInstance().getImageFolder());
tiSch.setText(STRING_SCHEMAS);
for (int i = 0; i < schemas.length; i++) {
TreeItem newSch = new TreeItem(tiSch, SWT.NONE);
newSch.setImage(GuiResource.getInstance().getImageSchema());
newSch.setText(schemas[i].getSchemaName());
for (int j = 0; j < schemas[i].getItems().length; j++) {
String tableName = schemas[i].getItems()[j];
TreeItem ti = new TreeItem(newSch, SWT.NONE);
ti.setImage(GuiResource.getInstance().getImageTable());
ti.setText(tableName);
}
}
}
// The tables in general...
TreeItem tiTab = null;
String[] tabnames = dmi.getTables();
if (tabnames != null) {
tiTab = new TreeItem(tiTree, SWT.NONE);
tiTab.setImage(GuiResource.getInstance().getImageFolder());
tiTab.setText(STRING_TABLES);
tiTab.setExpanded(true);
for (int i = 0; i < tabnames.length; i++) {
TreeItem newTab = new TreeItem(tiTab, SWT.NONE);
newTab.setImage(GuiResource.getInstance().getImageTable());
newTab.setText(tabnames[i]);
}
}
// The views...
TreeItem tiView = null;
String[] views = dmi.getViews();
if (views != null) {
tiView = new TreeItem(tiTree, SWT.NONE);
tiView.setImage(GuiResource.getInstance().getImageFolder());
tiView.setText(STRING_VIEWS);
for (int i = 0; i < views.length; i++) {
TreeItem newView = new TreeItem(tiView, SWT.NONE);
newView.setImage(GuiResource.getInstance().getImageView());
newView.setText(views[i]);
}
}
// The synonyms
TreeItem tiSyn = null;
String[] syn = dmi.getSynonyms();
if (syn != null) {
tiSyn = new TreeItem(tiTree, SWT.NONE);
tiSyn.setImage(GuiResource.getInstance().getImageFolder());
tiSyn.setText(STRING_SYNONYMS);
for (int i = 0; i < syn.length; i++) {
TreeItem newSyn = new TreeItem(tiSyn, SWT.NONE);
newSyn.setImage(GuiResource.getInstance().getImageSynonym());
newSyn.setText(syn[i]);
}
}
// Make sure the selected table is shown...
if (!StringUtils.isEmpty(selectedTable)) {
TreeItem ti = null;
if (ti == null && tiTab != null) {
ti = ConstUi.findTreeItem(tiTab, selectedSchema, selectedTable);
}
if (ti == null && tiView != null) {
ti = ConstUi.findTreeItem(tiView, selectedSchema, selectedTable);
}
if (ti == null && tiTree != null) {
ti = ConstUi.findTreeItem(tiTree, selectedSchema, selectedTable);
}
if (ti == null && tiSyn != null) {
ti = ConstUi.findTreeItem(tiSyn, selectedSchema, selectedTable);
}
if (ti != null) {
wTree.setSelection(new TreeItem[] {ti});
wTree.showSelection();
refreshButtons(
dbMeta.getQuotedSchemaTableCombination(variables, selectedSchema, selectedTable));
}
selectedTable = null;
}
tiTree.setExpanded(true);
} else {
return false;
}
return true;
}
private String getSchemaTable() {
TreeItem[] ti = wTree.getSelection();
if (ti.length == 1) {
// Get the parent.
TreeItem parent = ti[0].getParentItem();
if (parent != null) {
String schemaName = parent.getText();
String tableName = ti[0].getText();
if (ti[0].getItemCount() == 0) // No children, only the tables themselves...
{
String tab = null;
if (schemaName.equalsIgnoreCase(STRING_TABLES)
|| schemaName.equalsIgnoreCase(STRING_VIEWS)
|| schemaName.equalsIgnoreCase(STRING_SYNONYMS)
|| (schemaName != null && schemaName.isEmpty())) {
tab = tableName;
} else {
tab = dbMeta.getQuotedSchemaTableCombination(variables, schemaName, tableName);
}
return tab;
}
}
}
return null;
}
public void setTreeMenu() {
final String table = getSchemaTable();
if (table != null) {
Menu mTree = new Menu(shell, SWT.POP_UP);
MenuItem miPrev = new MenuItem(mTree, SWT.PUSH);
miPrev.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_100, table));
miPrev.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
previewTable(table, false);
}
});
MenuItem miPrevN = new MenuItem(mTree, SWT.PUSH);
miPrevN.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_PREVIEW_N, table));
miPrevN.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
previewTable(table, true);
}
});
MenuItem miCount = new MenuItem(mTree, SWT.PUSH);
miCount.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_SIZE, table));
miCount.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
showCount(table);
}
});
new MenuItem(mTree, SWT.SEPARATOR);
MenuItem miShow = new MenuItem(mTree, SWT.PUSH);
miShow.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_SHOW_LAYOUT, table));
miShow.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
showTable(table);
}
});
MenuItem miDDL = new MenuItem(mTree, SWT.PUSH);
miDDL.setText(BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDL));
miDDL.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getDDL(table);
}
});
MenuItem miDDL2 = new MenuItem(mTree, SWT.PUSH);
miDDL2.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_GEN_DDLOTHER_CONN));
miDDL2.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getDDLForOther(table);
}
});
miDDL2.setEnabled(databases != null);
MenuItem miSql = new MenuItem(mTree, SWT.PUSH);
miSql.setText(
BaseMessages.getString(PKG, CONST_DATABASE_EXPLORER_DIALOG_MENU_OPEN_SQL, table));
miSql.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getSql(table);
}
});
wTree.setMenu(mTree);
} else {
wTree.setMenu(null);
}
}
public void previewTable(String tableName, boolean asklimit) {
int limit = 100;
if (asklimit) {
// Ask how many lines we should preview.
String shellText = BaseMessages.getString(PKG, "DatabaseExplorerDialog.PreviewTable.Title");
String lineText = BaseMessages.getString(PKG, "DatabaseExplorerDialog.PreviewTable.Message");
EnterNumberDialog end = new EnterNumberDialog(shell, limit, shellText, lineText);
int samples = end.open();
if (samples >= 0) {
limit = samples;
}
}
String[] tableNameParts = tableName.split("\\.");
GetPreviewTableProgressDialog pd = null;
if (schemaName == null && tableNameParts.length == 2) {
// Table name contains both schema name and table name concatenated
pd =
new GetPreviewTableProgressDialog(
shell, variables, dbMeta, tableNameParts[0], tableNameParts[1], limit);
} else {
pd = new GetPreviewTableProgressDialog(shell, variables, dbMeta, null, tableName, limit);
}
List<Object[]> rows = pd.open();
if (rows != null) // otherwise an already shown error...
{
if (!rows.isEmpty()) {
PreviewRowsDialog prd =
new PreviewRowsDialog(shell, variables, SWT.NONE, tableName, pd.getRowMeta(), rows);
prd.open();
} else {
MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
mb.setMessage(BaseMessages.getString(PKG, "DatabaseExplorerDialog.NoRows.Message"));
mb.setText(BaseMessages.getString(PKG, "DatabaseExplorerDialog.NoRows.Title"));
mb.open();
}
}
}
public void showTable(String tableName) {
String sql = dbMeta.getSqlQueryFields(tableName);
IRowMeta result = null;
Database db = new Database(HopGui.getInstance().getLoggingObject(), variables, dbMeta);
try {
db.connect();
result = db.getQueryFields(sql, false);
} catch (Exception e) {
// Do Nothing
} finally {
db.disconnect();
}
if (result != null) {
TransformFieldsDialog sfd =
new TransformFieldsDialog(shell, variables, SWT.NONE, tableName, result);
sfd.open();
}
}
public void showCount(String tableName) {
String realTableName =
(tableName.contains(".") ? tableName.substring(tableName.indexOf(".") + 1) : tableName);
GetTableSizeProgressDialog pd =
new GetTableSizeProgressDialog(shell, variables, dbMeta, realTableName);
Long size = pd.open();
if (size != null) {
MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
mb.setMessage(
BaseMessages.getString(
PKG, "DatabaseExplorerDialog.TableSize.Message", tableName, size.toString()));
mb.setText(BaseMessages.getString(PKG, "DatabaseExplorerDialog.TableSize.Title"));
mb.open();
}
}
public void getDDL(String tableName) {
Database db = new Database(loggingObject, variables, dbMeta);
try {
db.connect();
IRowMeta r = db.getTableFields(tableName);
String realTableName =
(tableName.contains(".") ? tableName.substring(tableName.indexOf(".") + 1) : tableName);
String sql = db.getCreateTableStatement(realTableName, r, null, false, null, true);
SqlEditor se = new SqlEditor(shell, SWT.NONE, variables, dbMeta, dbcache, sql);
se.open();
} catch (HopDatabaseException dbe) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "Dialog.Error.Header"),
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Error.RetrieveLayout"),
dbe);
} finally {
db.disconnect();
}
}
public void getDDLForOther(String tableName) {
if (databases != null) {
Database database = new Database(loggingObject, variables, dbMeta);
try {
database.connect();
String realTableName =
(tableName.contains(".") ? tableName.substring(tableName.indexOf(".") + 1) : tableName);
IRowMeta rowMeta = database.getTableFields(realTableName);
// Now select the other connection...
// Only take non-SAP ERP connections....
List<DatabaseMeta> databaseMetaList = new ArrayList<>();
for (int i = 0; i < databases.size(); i++) {
databaseMetaList.add(databases.get(i));
}
String[] connectionNames = new String[databaseMetaList.size()];
for (int i = 0; i < connectionNames.length; i++) {
connectionNames[i] = (databaseMetaList.get(i)).getName();
}
EnterSelectionDialog enterSelectionDialog =
new EnterSelectionDialog(
shell,
connectionNames,
BaseMessages.getString(PKG, "DatabaseExplorerDialog.TargetDatabase.Title"),
BaseMessages.getString(PKG, "DatabaseExplorerDialog.TargetDatabase.Message"));
String target = enterSelectionDialog.open();
if (target != null) {
DatabaseMeta targetDatabaseMeta = DatabaseMeta.findDatabase(databaseMetaList, target);
Database targetDatabase = new Database(loggingObject, variables, targetDatabaseMeta);
String sql =
targetDatabase.getCreateTableStatement(tableName, rowMeta, null, false, null, true);
SqlEditor sqlEditor = new SqlEditor(shell, SWT.NONE, variables, dbMeta, dbcache, sql);
sqlEditor.open();
}
} catch (HopDatabaseException dbe) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "Dialog.Error.Header"),
BaseMessages.getString(PKG, "DatabaseExplorerDialog.Error.GenDDL"),
dbe);
} finally {
database.disconnect();
}
} else {
MessageBox mb = new MessageBox(shell, SWT.NONE | SWT.ICON_INFORMATION);
mb.setMessage(
BaseMessages.getString(PKG, "DatabaseExplorerDialog.NoConnectionsKnown.Message"));
mb.setText(BaseMessages.getString(PKG, "DatabaseExplorerDialog.NoConnectionsKnown.Title"));
mb.open();
}
}
public void getSql(String tableName) {
String realTableName =
(tableName.contains(".") ? tableName.substring(tableName.indexOf(".") + 1) : tableName);
SqlEditor sqlEditor =
new SqlEditor(
shell, SWT.NONE, variables, dbMeta, dbcache, "SELECT * FROM " + realTableName);
sqlEditor.open();
}
public void getTruncate(String activeSchemaTable) {
SqlEditor sql =
new SqlEditor(
shell, SWT.NONE, variables, dbMeta, dbcache, "-- TRUNCATE TABLE " + activeSchemaTable);
sql.open();
}
public void dispose() {
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
public void ok() {
if (justLook) {
dispose();
return;
}
TreeItem[] ti = wTree.getSelection();
if (ti.length == 1) {
// Get the parent.
String table = ti[0].getText();
String[] path = ConstUi.getTreeStrings(ti[0]);
if (path.length == 3) {
if (STRING_TABLES.equalsIgnoreCase(path[1])
|| STRING_VIEWS.equalsIgnoreCase(path[1])
|| STRING_SYNONYMS.equalsIgnoreCase(path[1])) {
schemaName = null;
tableName = table;
String[] st = tableName.split("\\.", 2);
if (st.length > 1) { // we have a dot in there and need to separate
schemaName = st[0];
tableName = st[1];
}
dispose();
}
}
if (path.length == 4) {
if (STRING_SCHEMAS.equals(path[1]) || STRING_CATALOG.equals(path[1])) {
if (splitSchemaAndTable) {
schemaName = path[2];
tableName = path[3];
} else {
schemaName = null;
tableName = dbMeta.getQuotedSchemaTableCombination(variables, path[2], path[3]);
}
dispose();
}
}
}
}
public void openSchema(Event e) {
TreeItem sel = (TreeItem) e.item;
TreeItem up1 = sel.getParentItem();
if (up1 != null) {
TreeItem up2 = up1.getParentItem();
if (up2 != null) {
TreeItem up3 = up2.getParentItem();
if (up3 != null) {
tableName = sel.getText();
if (!justLook) {
ok();
} else {
previewTable(tableName, false);
}
}
}
}
}
/**
* @return the schemaName
*/
public String getSchemaName() {
return schemaName;
}
/**
* @param schemaName the schemaName to set
*/
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
/**
* @return the tableName
*/
public String getTableName() {
return tableName;
}
/**
* @param tableName the tableName to set
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
/**
* @return the splitSchemaAndTable
*/
public boolean isSplitSchemaAndTable() {
return splitSchemaAndTable;
}
/**
* @param splitSchemaAndTable the splitSchemaAndTable to set
*/
public void setSplitSchemaAndTable(boolean splitSchemaAndTable) {
this.splitSchemaAndTable = splitSchemaAndTable;
}
/**
* @return the selectSchema
*/
public String getSelectedSchema() {
return selectedSchema;
}
/**
* @param selectSchema the selectSchema to set
*/
public void setSelectedSchema(String selectSchema) {
this.selectedSchema = selectSchema;
}
public void setSelectedSchemaAndTable(String schemaName, String tableName) {
this.selectedSchema = schemaName;
this.selectedTable = tableName;
}
}
|
apache/kylin | 35,223 | src/query/src/test/java/org/apache/kylin/query/security/HackSelectStarWithColumnACLWithSelectStarLowercaseTest.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.kylin.query.security;
import static org.apache.kylin.common.util.TestUtils.getTestConfig;
import java.util.Arrays;
import java.util.List;
import org.apache.kylin.common.QueryContext;
import org.apache.kylin.guava30.shaded.common.collect.Lists;
import org.apache.kylin.guava30.shaded.common.collect.Sets;
import org.apache.kylin.junit.annotation.MetadataInfo;
import org.apache.kylin.junit.annotation.OverwriteProp;
import org.apache.kylin.metadata.acl.AclTCR;
import org.apache.kylin.metadata.acl.AclTCRManager;
import org.apache.kylin.metadata.model.ColumnDesc;
import org.apache.kylin.metadata.model.NTableMetadataManager;
import org.apache.kylin.metadata.model.TableDesc;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@MetadataInfo
@OverwriteProp(value = "true", key = "kylin.pushdown.select-star-lowercase-enabled")
class HackSelectStarWithColumnACLWithSelectStarLowercaseTest {
private static final String PROJECT = "default";
private static final String SCHEMA = "DEFAULT";
private static final HackSelectStarWithColumnACL TRANSFORMER = new HackSelectStarWithColumnACL();
QueryContext current = QueryContext.current();
@BeforeEach
void setup() {
getTestConfig().setProperty("kylin.query.security.acl-tcr-enabled", "true");
prepareBasic();
current.setAclInfo(new QueryContext.AclInfo("u1", Sets.newHashSet("g1"), false));
}
@AfterAll
static void afterAll() {
QueryContext.current().close();
}
@Test
void testJoin() {
// without alias
{
String sql = "select * from TEST_KYLIN_FACT join TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with alias
{
String sql = "select * from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with alias without select star
{
String sql = "select t1.ORDER_ID from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select t1.ORDER_ID from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with tow alias
{
String sql = "select * from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID"
+ " join TEST_ORDER t3 on t1.ORDER_ID = t3.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"T3\" "
+ "on t1.ORDER_ID = t3.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with tow alias without select star
{
String sql = "select t1.ORDER_ID from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID"
+ " join TEST_ORDER t3 on t1.ORDER_ID = t3.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select t1.ORDER_ID from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID "
+ "join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"T3\" "
+ "on t1.ORDER_ID = t3.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// nested select star
{
String sql = "select * from (select * from TEST_KYLIN_FACT) t1 join TEST_ORDER t2 "
+ "on t1.ORDER_ID = t2.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from (" //
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\""
+ ") t1 join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\""
+ ") as \"T2\" on t1.ORDER_ID = t2.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testWithSubQuery() {
// simple case
{
String sql = "with test_order as (select * from test_order)\n"
+ "select * from TEST_KYLIN_FACT join TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (select * from ( "
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")\n"
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "join \"TEST_ORDER\" on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with-item has alias in with-body
{
String sql = "with \"TEMP_DEPT\" as (select fpd.order_id, fpd.buyer_id "
+ "from test_order as fpd group by fpd.order_id, fpd.buyer_id)\n"
+ "select fpd.order_id, fpd.buyer_id from temp_dept as fpd";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with \"TEMP_DEPT\" as (select fpd.order_id, fpd.buyer_id from ( "
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", \"TEST_ORDER\".\"test_date_enc\" "
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"FPD\" group by fpd.order_id, fpd.buyer_id)\n"
+ "select fpd.order_id, fpd.buyer_id from \"TEMP_DEPT\" as \"FPD\"";
Assertions.assertEquals(expected, converted);
}
// some content of with-body reuse with-items
{
String sql = "with test_order as (select * from test_order)\n"
+ "select * from TEST_KYLIN_FACT join (select * from TEST_ORDER) TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (select * from ( "
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")\n"
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "join (select * from \"TEST_ORDER\") TEST_ORDER on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// all contexts of with-body do not reuse any with-items
{
String sql = "with test_order as (select * from test_order)\n"
+ "select * from TEST_KYLIN_FACT join (select * from \"DEFAULT\".\"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (select * from ( "
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")\n"
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" " //
+ "join (select * from ( " //
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" "
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// all contexts of with-body reuse with-items
{
String sql = "with test_order as (select * from test_order), "
+ "test_kylin_fact as (select * from test_kylin_fact)\n"
+ "select * from TEST_KYLIN_FACT join (select * from TEST_ORDER) TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (" //
+ "select * from ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" " //
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\"), " //
+ "test_kylin_fact as ("
+ "select * from ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")\n"
+ "select * from \"TEST_KYLIN_FACT\" join (select * from \"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testResolvedSorted() {
{
String sql = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from TEST_ORDER ) as o2" //
+ " from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from " //
+ "( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" " //
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" ) as o2" //
+ " from ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
{
String sql = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from TEST_KYLIN_FACT ) as o2" //
+ " from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from " //
+ "( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" ) as o2" //
+ " from ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testWithoutSubQueryFrom() {
// without from
{
String sql = "select -((select sum(ORDER_ID) from test_kylin_fact)"
+ " -(select sum(ORDER_ID) from test_kylin_fact)" //
+ ") as a1";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ " -(select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1";
Assertions.assertEquals(expected, converted);
}
// without from and with SqlIdentifier in selectList
{
String sql = "select -((select sum(ORDER_ID) from test_kylin_fact)"
+ " -(select sum(ORDER_ID) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ " -(select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
// without from and with SqlWith in selectList
{
String sql = "select -((" //
+ "with test_kylin_fact1 as (select * from test_kylin_fact) "
+ "select sum(ORDER_ID) from test_kylin_fact1)" //
+ " -(select sum(PRICE) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((" //
+ "with test_kylin_fact1 as ("
+ "select * from ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\") " //
+ "select sum(ORDER_ID) from \"TEST_KYLIN_FACT1\")" //
+ " -(select sum(PRICE) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
{
String sql = "select -((" //
+ "with test_order as (select * from test_order), "
+ "test_kylin_fact1 as (select * from test_kylin_fact) "
+ "select sum(TEST_KYLIN_FACT1.ORDER_ID) from TEST_KYLIN_FACT1"
+ " join (select * from TEST_ORDER) TEST_ORDER "
+ "on TEST_KYLIN_FACT1.ORDER_ID = TEST_ORDER.ORDER_ID limit 1)" //
+ " -(select sum(PRICE) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((" //
+ "with test_order as (" //
+ "select * from ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" " //
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\"), " //
+ "test_kylin_fact1 as ("
+ "select * from ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\") "
+ "select sum(TEST_KYLIN_FACT1.ORDER_ID) from \"TEST_KYLIN_FACT1\""
+ " join (select * from \"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT1.ORDER_ID = TEST_ORDER.ORDER_ID limit 1)" //
+ " -(select sum(PRICE) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
// without from and with SqlJoin in selectList
{
String sql = "select -((" //
+ "select sum(t1.ORDER_ID) from (select * from TEST_KYLIN_FACT) t1 join TEST_ORDER t2 "
+ "on t1.ORDER_ID = t2.ORDER_ID)" //
+ " -(select sum(PRICE) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((" //
+ "select sum(t1.ORDER_ID) from (" //
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\""
+ ") t1 join ( select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\""
+ ") as \"T2\" on t1.ORDER_ID = t2.ORDER_ID)"//
+ " -(select sum(PRICE) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
// without from with null
{
String sql = "select (select sum(ORDER_ID), null from test_kylin_fact)"
+ ",(select sum(ORDER_ID) from test_kylin_fact) as a1";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select (select sum(ORDER_ID), null from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ",(select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\") as a1";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testUnion() {
// without outer select
{
String sql = "select * from test_order union select * from test_order";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" "
+ "union select * from ( " //
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\"";
Assertions.assertEquals(expected, converted);
}
// with outer select
{
String sql = "select * from (select * from test_order union select * from test_order)";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from (select * from ( " //
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" "
+ "union select * from ( " //
+ "select \"TEST_ORDER\".\"order_id\", \"TEST_ORDER\".\"buyer_id\", "
+ "\"TEST_ORDER\".\"test_date_enc\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testInSubQuery() {
String sql = "select * from TEST_KYLIN_FACT "
+ "where ITEM_COUNT in (select ITEM_COUNT from (select * from TEST_KYLIN_FACT) )";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "where ITEM_COUNT in (select ITEM_COUNT from (select * from TEST_KYLIN_FACT) )";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
@Test
void testCaseWhen() {
{
String sql = "select (case when ITEM_COUNT > 0 " //
+ "then (case when order_id > 0 then order_id else 1 end) " //
+ "else null end)\n" //
+ "from TEST_KYLIN_FACT";
String expected = "select (case when ITEM_COUNT > 0 " //
+ "then (case when order_id > 0 then order_id else 1 end) " //
+ "else null end)\n" //
+ "from ( select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", " //
+ "\"TEST_KYLIN_FACT\".\"item_count\" " //
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
{
String sql = "select * from test_kylin_fact " //
+ "where case when ITEM_COUNT > 10 then item_count else 0 end";
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", " //
+ "\"TEST_KYLIN_FACT\".\"item_count\" " //
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "where case when ITEM_COUNT > 10 then item_count else 0 end";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
}
@Test
void testSingleTable() {
// without limit
{
String sql = "select * from \"DEFAULT\".\"TEST_KYLIN_FACT\"";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// with alias
{
String sql = "select * from test_kylin_fact as test_kylin_fact";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// with limit-offset
{
String sql = "select * from test_kylin_fact as test_kylin_fact limit 10 offset 2";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" limit 10 offset 2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// agg
{
String sql = "select count(*) from \"DEFAULT\".\"TEST_KYLIN_FACT\"";
String expected = "select count(*) from ( "
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
}
@Test
void testKeywordAsColName() {
prepareMore();
NTableMetadataManager tableMetadataManager = NTableMetadataManager.getInstance(getTestConfig(), PROJECT);
TableDesc tableDesc = tableMetadataManager.getTableDesc("DEFAULT.TEST_KYLIN_FACT");
ColumnDesc[] columns = tableDesc.getColumns();
ColumnDesc colStartsWithNumber = new ColumnDesc(columns[0]);
colStartsWithNumber.setId("13");
colStartsWithNumber.setDatatype("date");
colStartsWithNumber.setName("2d");
ColumnDesc colWithKeyword = new ColumnDesc(columns[0]);
colWithKeyword.setId("14");
colWithKeyword.setDatatype("date");
colWithKeyword.setName("YEAR");
List<ColumnDesc> columnDescs = Lists.newArrayList(columns);
columnDescs.add(colStartsWithNumber);
columnDescs.add(colWithKeyword);
tableDesc.setColumns(columnDescs.toArray(new ColumnDesc[0]));
tableMetadataManager.updateTableDesc(tableDesc);
String sql = "select * from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", \"TEST_KYLIN_FACT\".\"price\", "
+ "\"TEST_KYLIN_FACT\".\"item_count\", \"TEST_KYLIN_FACT\".\"2d\", \"TEST_KYLIN_FACT\".\"year\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
@Test
void testColumnNameStartsWithNumber() {
prepareMore();
NTableMetadataManager tableMetadataManager = NTableMetadataManager.getInstance(getTestConfig(), PROJECT);
TableDesc tableDesc = tableMetadataManager.getTableDesc("DEFAULT.TEST_KYLIN_FACT");
ColumnDesc[] columns = tableDesc.getColumns();
ColumnDesc colStartsWithNumber = new ColumnDesc(columns[0]);
colStartsWithNumber.setId("13");
colStartsWithNumber.setDatatype("date");
colStartsWithNumber.setName("2d");
ColumnDesc colWithKeyword = new ColumnDesc(columns[0]);
colWithKeyword.setId("14");
colWithKeyword.setDatatype("date");
colWithKeyword.setName("YEAR");
List<ColumnDesc> columnDescs = Lists.newArrayList(columns);
columnDescs.add(colStartsWithNumber);
columnDescs.add(colWithKeyword);
tableDesc.setColumns(columnDescs.toArray(new ColumnDesc[0]));
tableMetadataManager.updateTableDesc(tableDesc);
String sql = "select * from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"order_id\", " //
+ "\"TEST_KYLIN_FACT\".\"price\", " //
+ "\"TEST_KYLIN_FACT\".\"item_count\", " //
+ "\"TEST_KYLIN_FACT\".\"2d\", " //
+ "\"TEST_KYLIN_FACT\".\"year\" " //
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
@Test
void testExplainSyntax() {
String sql = "explain plan for select * from t";
Assertions.assertEquals(sql, TRANSFORMER.convert("explain plan for select * from t", PROJECT, SCHEMA));
}
private void prepareMore() {
AclTCRManager manager = AclTCRManager.getInstance(getTestConfig(), PROJECT);
AclTCR g1a1 = new AclTCR();
AclTCR.Table g1t1 = new AclTCR.Table();
AclTCR.ColumnRow g1cr1 = new AclTCR.ColumnRow();
AclTCR.Column g1c1 = new AclTCR.Column();
g1c1.addAll(Arrays.asList("ORDER_ID", "2d", "YEAR"));
g1cr1.setColumn(g1c1);
g1t1.put("DEFAULT.TEST_KYLIN_FACT", g1cr1);
g1a1.setTable(g1t1);
manager.updateAclTCR(g1a1, "g1", false);
}
private void prepareBasic() {
AclTCRManager manager = AclTCRManager.getInstance(getTestConfig(), PROJECT);
AclTCR u1a1 = new AclTCR();
AclTCR.Table u1t1 = new AclTCR.Table();
AclTCR.ColumnRow u1cr1 = new AclTCR.ColumnRow();
AclTCR.Column u1c1 = new AclTCR.Column();
u1c1.addAll(Arrays.asList("PRICE", "ITEM_COUNT"));
u1cr1.setColumn(u1c1);
AclTCR.ColumnRow u1cr2 = new AclTCR.ColumnRow();
AclTCR.Column u1c2 = new AclTCR.Column();
u1c2.addAll(Arrays.asList("ORDER_ID", "BUYER_ID", "TEST_DATE_ENC"));
u1cr2.setColumn(u1c2);
u1t1.put("DEFAULT.TEST_KYLIN_FACT", u1cr1);
u1t1.put("DEFAULT.TEST_ORDER", u1cr2);
u1a1.setTable(u1t1);
manager.updateAclTCR(u1a1, "u1", true);
AclTCR g1a1 = new AclTCR();
AclTCR.Table g1t1 = new AclTCR.Table();
AclTCR.ColumnRow g1cr1 = new AclTCR.ColumnRow();
AclTCR.Column g1c1 = new AclTCR.Column();
g1c1.add("ORDER_ID");
g1cr1.setColumn(g1c1);
g1t1.put("DEFAULT.TEST_KYLIN_FACT", g1cr1);
g1a1.setTable(g1t1);
manager.updateAclTCR(g1a1, "g1", false);
}
}
|
apache/jackrabbit-oak | 37,670 | oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/binary/BinaryAccessIT.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.jackrabbit.oak.jcr.binary;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.getBinary;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.httpGet;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.httpPut;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.isFailedHttpPut;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.isSuccessfulHttpPut;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.putBinary;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.storeBinary;
import static org.apache.jackrabbit.oak.jcr.binary.util.BinaryAccessTestUtils.storeBinaryAndRetrieve;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.jcr.AccessDeniedException;
import javax.jcr.Binary;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.io.IOUtils;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.api.JackrabbitValueFactory;
import org.apache.jackrabbit.api.ReferenceBinary;
import org.apache.jackrabbit.api.binary.BinaryDownload;
import org.apache.jackrabbit.api.binary.BinaryDownloadOptions;
import org.apache.jackrabbit.api.binary.BinaryUpload;
import org.apache.jackrabbit.oak.blob.cloud.s3.S3DataStore;
import org.apache.jackrabbit.oak.commons.collections.IterableUtils;
import org.apache.jackrabbit.oak.fixture.NodeStoreFixture;
import org.apache.jackrabbit.oak.jcr.binary.util.Content;
import org.apache.jackrabbit.oak.plugins.blob.datastore.directaccess.ConfigurableDataRecordAccessProvider;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Integration test for direct binary GET/PUT via HTTP, that requires a fully working data store
* (such as S3) for each {@link AbstractBinaryAccessIT#dataStoreFixtures() configured fixture}.
* The data store in question must support direct GET/PUT access via a URI.
*
* Data store must be configured through e.g. aws.properties.
*
* Run this IT in maven using either:
*
* single test:
* mvn clean test -Dtest=BinaryAccessIT
*
* as part of all integration tests:
* mvn -PintegrationTesting clean install
*/
@RunWith(Parameterized.class)
public class BinaryAccessIT extends AbstractBinaryAccessIT {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String FILE_PATH = "/file";
private static final int REGULAR_WRITE_EXPIRY = 60*5; // seconds
private static final int REGULAR_READ_EXPIRY = 60*5; // seconds
public BinaryAccessIT(NodeStoreFixture fixture) {
// reuse NodeStore (and DataStore) across all tests in this class
super(fixture, true);
}
private JackrabbitValueFactory uploadProvider;
private JackrabbitValueFactory anonymousUploadProvider;
@Before
public void cleanRepoContents() throws RepositoryException {
Session anonymousSession = getAnonymousSession();
uploadProvider = (JackrabbitValueFactory) getAdminSession().getValueFactory();
anonymousUploadProvider = (JackrabbitValueFactory) anonymousSession.getValueFactory();
if (getAdminSession().nodeExists(FILE_PATH)) {
getAdminSession().getNode(FILE_PATH).remove();
getAdminSession().save();
}
}
// F1 - basic test
@Test
public void testUpload() throws Exception {
// enable writable URI feature
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
Content content = Content.createRandom(256);
assertTrue(getAdminSession().getValueFactory() instanceof JackrabbitValueFactory);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 1);
assertNotNull(upload);
// very small test binary
assertTrue(content.size() < upload.getMaxPartSize());
URI uri = upload.getUploadURIs().iterator().next();
assertNotNull(uri);
log.info("- uploading binary via PUT to {}", uri.toString());
int code = httpPut(uri, content.size(), content.getStream());
assertTrue("PUT to pre-signed URI failed",
isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
Binary writeBinary = uploadProvider.completeBinaryUpload(upload.getUploadToken());
putBinary(getAdminSession(), FILE_PATH, writeBinary);
Binary readBinary = getBinary(getAdminSession(), FILE_PATH);
content.assertEqualsWith(readBinary.getStream());
}
// F3 - Multi-part upload
@Test
public void testMultiPartUpload() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
assertTrue(getAdminSession().getValueFactory() instanceof JackrabbitValueFactory);
// 25MB is a good size to ensure chunking is done
Content content = Content.createRandom(1024 * 1024 * 25);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 50);
assertNotNull(upload);
List<URI> uris = new ArrayList<>();
upload.getUploadURIs().forEach(uris::add);
// this follows the upload algorithm from BinaryUpload
if (content.size() / upload.getMaxPartSize() > uris.size()) {
fail("exact binary size was provided but implementation failed to provide enough upload URIs");
}
if (content.size() < upload.getMinPartSize()) {
// single upload
content.httpPUT(uris.get(0));
} else {
// multipart upload
final long basePartSize = (long) Math.ceil(content.size() / (double) uris.size());
long offset = 0;
for (URI uri : uris) {
final long partSize = Math.min(basePartSize, content.size() - offset);
int code = content.httpPUT(uri, offset, partSize);
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
offset += partSize;
// fail safe check, shouldn't be necessary
if (offset >= content.size()) {
break;
}
}
}
Binary writeBinary = uploadProvider.completeBinaryUpload(upload.getUploadToken());
putBinary(getAdminSession(), FILE_PATH, writeBinary);
Binary readBinary = getBinary(getAdminSession(), FILE_PATH);
content.assertEqualsWith(readBinary.getStream());
}
// F8 - test reading getBinary().toInputStream() once uploaded
@Test
public void testStreamBinaryThroughJCRAfterURIWrite() throws Exception {
// enable writable URI feature
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
// 1. add binary and upload
Content content = Content.createRandom(256);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 10);
int code = content.httpPUT(upload.getUploadURIs().iterator().next());
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
Binary binaryWrite = uploadProvider.completeBinaryUpload(upload.getUploadToken());
storeBinary(getAdminSession(), FILE_PATH, binaryWrite);
// 2. stream through JCR and validate it's the same
Session session = createAdminSession();
try {
Binary binaryRead = getBinary(session, FILE_PATH);
content.assertEqualsWith(binaryRead.getStream());
} finally {
session.logout();
}
}
// F10 - GET Binary when created via repo
@Test
public void testGetBinary() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
// Must be larger than the minimum file size, to keep it from being inlined in the node store.
Content content = Content.createRandom(1024*20);
// make sure to test getting a fresh Binary
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
assertTrue(binary instanceof BinaryDownload);
URI downloadURI = ((BinaryDownload) binary).getURI(BinaryDownloadOptions.DEFAULT);
assertNotNull("HTTP download URI is null", downloadURI);
content.assertEqualsWith(httpGet(downloadURI));
// different way to retrieve binary
// TODO: also test multivalue binary prop
binary = getAdminSession().getNode(FILE_PATH)
.getNode(JcrConstants.JCR_CONTENT)
.getProperty(JcrConstants.JCR_DATA).getValue().getBinary();
downloadURI = ((BinaryDownload) binary).getURI(BinaryDownloadOptions.DEFAULT);
assertNotNull("HTTP download URI is null", downloadURI);
}
// F9 - GET Binary for binary after write using direct PUT
@Test
public void testGetBinaryAfterPut() throws Exception {
// enable writable and readable URI feature
ConfigurableDataRecordAccessProvider provider = getConfigurableHttpDataRecordProvider();
provider.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
provider.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
// 1. add binary and upload
Content content = Content.createRandom(1024*20);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 10);
int code = content.httpPUT(upload.getUploadURIs().iterator().next());
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
Binary writeBinary = uploadProvider.completeBinaryUpload(upload.getUploadToken());
storeBinary(getAdminSession(), FILE_PATH, writeBinary);
// 2. read binary, get the URI
Binary binary = getBinary(getAdminSession(), FILE_PATH);
URI downloadURI = ((BinaryDownload)(binary)).getURI(BinaryDownloadOptions.DEFAULT);
// 3. GET on URI and verify contents are the same
content.assertEqualsWith(httpGet(downloadURI));
}
@Test
public void testGetSmallBinaryReturnsNull() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
// Must be smaller than the minimum file size, (inlined binary)
Content content = Content.createRandom(256);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
URI downloadURI = ((BinaryDownload)(binary)).getURI(BinaryDownloadOptions.DEFAULT);
assertNull(downloadURI);
}
@Test
public void testGetBinaryWithSpecificMediaType() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
String expectedMediaType = "image/png";
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withMediaType(expectedMediaType)
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String mediaType = conn.getHeaderField("Content-Type");
assertNotNull(mediaType);
assertEquals(expectedMediaType, mediaType);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
@Test
public void testGetBinaryWithSpecificMediaTypeAndEncoding() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
String expectedMediaType = "text/plain";
String expectedCharacterEncoding = "utf-8";
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withMediaType(expectedMediaType)
.withCharacterEncoding(expectedCharacterEncoding)
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String mediaType = conn.getHeaderField("Content-Type");
assertNotNull(mediaType);
assertEquals(String.format("%s; charset=%s", expectedMediaType, expectedCharacterEncoding),
mediaType);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
@Test
public void testGetBinaryWithCharacterEncodingOnly() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
String expectedCharacterEncoding = "utf-8";
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withCharacterEncoding(expectedCharacterEncoding)
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String mediaType = conn.getHeaderField("Content-Type");
// application/octet-stream is the default Content-Type if none is
// set in the signed URI
assertEquals("application/octet-stream", mediaType);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
@Test
public void testGetBinaryWithSpecificFileName() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
String expectedName = "beautiful landscape.png";
String encodedName = "beautiful%20landscape.png";
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withFileName(expectedName)
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String contentDisposition = conn.getHeaderField("Content-Disposition");
assertNotNull(contentDisposition);
assertEquals(
String.format("inline; filename=\"%s\"; filename*=UTF-8''%s",
expectedName, encodedName),
contentDisposition
);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
@Test
public void testGetBinaryWithSpecificFileNameAndDispositionType() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
String expectedName = "beautiful landscape.png";
String encodedName = "beautiful%20landscape.png";
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withFileName(expectedName)
.withDispositionTypeAttachment()
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String contentDisposition = conn.getHeaderField("Content-Disposition");
assertNotNull(contentDisposition);
assertEquals(
String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
expectedName, encodedName),
contentDisposition
);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
@Test
public void testGetBinaryWithDispositionType() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withDispositionTypeInline()
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String contentDisposition = conn.getHeaderField("Content-Disposition");
// Should be no header since filename was not set and disposition type
// is "inline"
assertNull(contentDisposition);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
downloadOptions = BinaryDownloadOptions
.builder()
.withDispositionTypeAttachment()
.build();
downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
conn = (HttpURLConnection) downloadURI.toURL().openConnection();
contentDisposition = conn.getHeaderField("Content-Disposition");
// Content-Disposition should exist now because "attachment" was set
assertNotNull(contentDisposition);
assertEquals("attachment", contentDisposition);
}
@Test
public void testGetBinarySetsAllHeaders() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
String expectedMediaType = "image/png";
String expectedCharacterEncoding = "utf-8";
String expectedName = "beautiful landscape.png";
String encodedName = "beautiful%20landscape.png";
BinaryDownloadOptions downloadOptions = BinaryDownloadOptions
.builder()
.withMediaType(expectedMediaType)
.withCharacterEncoding(expectedCharacterEncoding)
.withFileName(expectedName)
.withDispositionTypeAttachment()
.build();
URI downloadURI = ((BinaryDownload)(binary)).getURI(downloadOptions);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String mediaType = conn.getHeaderField("Content-Type");
assertNotNull(mediaType);
assertEquals(
String.format("%s; charset=%s", expectedMediaType, expectedCharacterEncoding),
mediaType);
String contentDisposition = conn.getHeaderField("Content-Disposition");
assertNotNull(contentDisposition);
assertEquals(
String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
expectedName, encodedName),
contentDisposition
);
String cacheControl = conn.getHeaderField("Cache-Control");
assertNotNull(cacheControl);
assertEquals(String.format("private, max-age=%d, immutable", REGULAR_READ_EXPIRY), cacheControl);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
@Test
public void testGetBinaryDefaultOptions() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
URI downloadURI = ((BinaryDownload)(binary)).getURI(BinaryDownloadOptions.DEFAULT);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
String mediaType = conn.getHeaderField("Content-Type");
assertNotNull(mediaType);
assertEquals("application/octet-stream", mediaType);
String contentDisposition = conn.getHeaderField("Content-Disposition");
assertNull(contentDisposition);
String cacheControl = conn.getHeaderField("Cache-Control");
assertNotNull(cacheControl);
assertEquals(String.format("private, max-age=%d, immutable", REGULAR_READ_EXPIRY), cacheControl);
// Verify response content
assertEquals(200, conn.getResponseCode());
content.assertEqualsWith(conn.getInputStream());
}
// A6 - Client MUST only get permission to add a blob referenced in a JCR binary property
// where the user has JCR set_property permission.
@Test
@Ignore("OAK-7602") // michid FIXME OAK-7602
public void testUnprivilegedSessionCannotUploadBinary() throws Exception {
// enable writable URI feature
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
anonymousUploadProvider.initiateBinaryUpload(1024*20, 10);
fail();
}
catch (AccessDeniedException e) { }
}
// A2 - disable write URIs entirely
@Test
public void testDisableDirectHttpUpload() throws Exception {
// disable in data store config by setting expiry to zero
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(0);
Content content = Content.createRandom(256);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 10);
assertNull(upload);
}
// A2 - disable get URIs entirely
@Test
public void testDisableDirectHttpDownload() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectDownloadURIExpirySeconds(0);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
URI downloadURI = ((BinaryDownload)(binary)).getURI(BinaryDownloadOptions.DEFAULT);
assertNull(downloadURI);
}
// A2/A3 - configure short expiry time, wait, ensure upload fails after expired
@Test
public void testPutURIExpires() throws Exception {
// short timeout
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(1);
Content content = Content.createRandom(1024*20);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 10);
// wait to pass timeout: 2 seconds
Thread.sleep(2 * 1000);
// ensure PUT fails with 403 or anything 400+
assertTrue(content.httpPUT(upload.getUploadURIs().iterator().next()) >= HttpURLConnection.HTTP_BAD_REQUEST);
}
// F2 - transfer accelerator (S3 only feature)
@Test
public void testTransferAcceleration() throws Exception {
ConfigurableDataRecordAccessProvider provider = getConfigurableHttpDataRecordProvider();
// This test is S3 specific
if (provider instanceof S3DataStore) {
provider.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
provider.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
provider.setBinaryTransferAccelerationEnabled(true);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(1024 * 20, 1);
URI uri = upload.getUploadURIs().iterator().next();
assertNotNull(uri);
log.info("accelerated URI: {}", uri.toString());
assertTrue(uri.getHost().endsWith(".s3-accelerate.amazonaws.com"));
provider.setBinaryTransferAccelerationEnabled(false);
upload = uploadProvider.initiateBinaryUpload(1024*20, 1);
uri = upload.getUploadURIs().iterator().next();
assertNotNull(uri);
log.info("non-accelerated URI: {}", uri.toString());
assertFalse(uri.getHost().endsWith(".s3-accelerate.amazonaws.com"));
}
}
// A1 - get put URI, change it and try uploading it
@Test
public void testModifiedPutURIFails() throws Exception {
// enable writable URI feature
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
Content content = Content.createRandom(1024*20);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 1);
URI uri = upload.getUploadURIs().iterator().next();
URI changedURI = new URI(
String.format("%s://%s/%sX?%s", // NOTE the injected "X" in the URI filename
uri.getScheme(),
uri.getHost(),
uri.getPath(),
uri.getQuery())
);
int code = content.httpPUT(changedURI);
assertTrue("Expected failed request but got " + String.valueOf(code), isFailedHttpPut(code));
}
// A1 - get put URI, upload, then try reading from the same URI
@Test
public void testCannotReadFromPutURI() throws Exception {
// enable writable URI and readable URI feature
ConfigurableDataRecordAccessProvider provider = getConfigurableHttpDataRecordProvider();
provider.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
provider.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 1);
URI uri = upload.getUploadURIs().iterator().next();
int code = content.httpPUT(uri);
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
code = conn.getResponseCode();
assertTrue(isFailedHttpPut(code));
}
// A1 - add binary via JCR, then get put URI, and modify to try to upload over first binary
@Test
public void testCannotModifyExistingBinaryViaPutURI() throws Exception {
// enable writable URI and readable URI feature
ConfigurableDataRecordAccessProvider provider = getConfigurableHttpDataRecordProvider();
provider.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
provider.setDirectDownloadURIExpirySeconds(REGULAR_READ_EXPIRY);
Content content = Content.createRandom(1024*20);
Binary binary = storeBinaryAndRetrieve(getAdminSession(), FILE_PATH, content);
URI downloadURI = ((BinaryDownload)(binary)).getURI(BinaryDownloadOptions.DEFAULT);
assertNotNull(downloadURI);
Content moreContent = Content.createRandom(1024*20);
uploadProvider.initiateBinaryUpload(moreContent.size(), 1);
HttpURLConnection conn = (HttpURLConnection) downloadURI.toURL().openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
IOUtils.copy(moreContent.getStream(), conn.getOutputStream());
int code = conn.getResponseCode();
assertTrue(isFailedHttpPut(code));
content.assertEqualsWith(httpGet(downloadURI));
}
// D1 - immutable after initial upload
@Test
public void testUploadedBinaryIsImmutable() throws Exception {
// enable writable URI feature
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
// 1. upload and store first binary
Content content = Content.createRandom(1024*20);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 1);
assertNotNull(upload);
int code = content.httpPUT(upload.getUploadURIs().iterator().next());
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
Binary uploadedBinary = uploadProvider.completeBinaryUpload(upload.getUploadToken());
storeBinary(getAdminSession(), FILE_PATH, uploadedBinary);
Binary binary1 = getBinary(getAdminSession(), FILE_PATH);
// 2. upload different binary content, but store at the same JCR location
Content moreContent = Content.createRandom(1024*21);
upload = uploadProvider.initiateBinaryUpload(moreContent.size(), 1);
assertNotNull(upload);
code = moreContent.httpPUT(upload.getUploadURIs().iterator().next());
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
uploadedBinary = uploadProvider.completeBinaryUpload(upload.getUploadToken());
storeBinary(getAdminSession(), FILE_PATH, uploadedBinary);
Binary binary2 = getBinary(getAdminSession(), FILE_PATH);
// 3. verify they have different references
assertTrue(binary1 instanceof ReferenceBinary);
assertTrue(binary2 instanceof ReferenceBinary);
assertNotEquals(((ReferenceBinary) binary1).getReference(), ((ReferenceBinary) binary2).getReference());
}
// D2 - unique identifiers
@Test
public void testUploadPathsAreUnique() throws Exception {
// Every upload destination should be unique with no regard to file content
// The content is not read by the Oak code so no deduplication can be performed
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
Content content = Content.createRandom(1024*20);
BinaryUpload upload1 = uploadProvider.initiateBinaryUpload(content.size(), 1);
assertNotNull(upload1);
BinaryUpload upload2 = uploadProvider.initiateBinaryUpload(content.size(), 1);
assertNotNull(upload2);
assertNotEquals(upload1.getUploadURIs().iterator().next().toString(),
upload2.getUploadURIs().iterator().next().toString());
}
// D3 - do not delete directly => copy nt:file node, delete one, ensure binary still there
@Test
public void testBinaryNotDeletedWithNode() throws Exception {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
Content content = Content.createRandom(1024*20);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(content.size(), 1);
int code = content.httpPUT(upload.getUploadURIs().iterator().next());
assertTrue(isSuccessfulHttpPut(code, getConfigurableHttpDataRecordProvider()));
Binary binary = uploadProvider.completeBinaryUpload(upload.getUploadToken());
storeBinary(getAdminSession(), FILE_PATH+"2", binary);
storeBinary(getAdminSession(), FILE_PATH, binary);
getAdminSession().getNode(FILE_PATH+"2").remove();
getAdminSession().save();
Binary savedBinary = getBinary(getAdminSession(), FILE_PATH);
assertNotNull(savedBinary);
assertTrue(binary instanceof ReferenceBinary);
assertTrue(savedBinary instanceof ReferenceBinary);
assertEquals(((ReferenceBinary) binary).getReference(),
((ReferenceBinary) savedBinary).getReference());
}
// D5 - blob ref not persisted in NodeStore until binary uploaded and immutable
// NOTE: not test needed for this, as the API guarantees the Binary is only returned after
// the blob was persisted in completeBinaryUpload() and client code is responsible
// for writing it to the JCR
// more tests
@Test
public void testInitiateHttpUploadWithZeroSizeFails() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
uploadProvider.initiateBinaryUpload(0, 1);
fail();
}
catch (IllegalArgumentException e) { }
}
@Test
public void testInitiateHttpUploadWithZeroURIsFails() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
uploadProvider.initiateBinaryUpload(1024 * 20, 0);
fail();
}
catch (IllegalArgumentException e) { }
}
@Test
public void testInitiateHttpUploadWithUnsupportedNegativeNumberURIsFails()
throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
uploadProvider.initiateBinaryUpload(1024 * 20, -2);
fail();
}
catch (IllegalArgumentException e) { }
}
@Test
public void testInitiateHttpUploadWithUnlimitedURIs() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(1024 * 1024 * 1024, -1);
assertNotNull(upload);
assertTrue(IterableUtils.size(upload.getUploadURIs()) > 50);
// 50 is our default expected client max -
// this is to make sure we will give as many as needed
// if the client doesn't specify their own limit
}
@Test
public void testInitiateHttpUploadLargeSinglePut() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(1024 * 1024 * 100, 1);
assertNotNull(upload);
assertEquals(1, IterableUtils.size(upload.getUploadURIs()));
}
@Test
public void testInitiateHttpUploadTooLargeForSinglePut() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
uploadProvider.initiateBinaryUpload(1024L * 1024L * 1024L * 10L, 1);
fail();
}
catch (IllegalArgumentException e) { }
}
@Test
public void testInitiateHttpUploadTooLargeForUpload() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
uploadProvider.initiateBinaryUpload(1024L * 1024L * 1024L * 1024L * 10L, -1);
fail();
}
catch (IllegalArgumentException e) { }
}
@Test
public void testInitiateHttpUploadTooLargeForRequestedNumURIs() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
try {
uploadProvider.initiateBinaryUpload(1024L * 1024L * 1024L * 10L, 10);
fail();
}
catch (IllegalArgumentException e) { }
}
@Test
public void testCompleteHttpUploadWithInvalidTokenFails() throws RepositoryException {
getConfigurableHttpDataRecordProvider()
.setDirectUploadURIExpirySeconds(REGULAR_WRITE_EXPIRY);
BinaryUpload upload = uploadProvider.initiateBinaryUpload(256, 10);
assertNotNull(upload);
try {
uploadProvider.completeBinaryUpload(upload.getUploadToken() + "X");
fail();
}
catch (IllegalArgumentException e) { }
}
}
|
apache/tajo | 37,678 | tajo-core/src/main/java/org/apache/tajo/querymaster/Query.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tajo.querymaster;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.state.*;
import org.apache.hadoop.yarn.util.Clock;
import org.apache.tajo.ExecutionBlockId;
import org.apache.tajo.QueryId;
import org.apache.tajo.QueryVars;
import org.apache.tajo.SessionVars;
import org.apache.tajo.TajoProtos.QueryState;
import org.apache.tajo.catalog.*;
import org.apache.tajo.catalog.proto.CatalogProtos.PartitionDescProto;
import org.apache.tajo.catalog.proto.CatalogProtos.UpdateTableStatsProto;
import org.apache.tajo.catalog.statistics.StatisticsUtil;
import org.apache.tajo.catalog.statistics.TableStats;
import org.apache.tajo.conf.TajoConf;
import org.apache.tajo.engine.planner.global.ExecutionBlock;
import org.apache.tajo.engine.planner.global.ExecutionBlockCursor;
import org.apache.tajo.engine.planner.global.ExecutionQueue;
import org.apache.tajo.engine.planner.global.MasterPlan;
import org.apache.tajo.engine.query.QueryContext;
import org.apache.tajo.error.Errors.SerializedException;
import org.apache.tajo.exception.ErrorUtil;
import org.apache.tajo.master.event.*;
import org.apache.tajo.plan.logical.*;
import org.apache.tajo.plan.util.PlannerUtil;
import org.apache.tajo.schema.IdentifierUtil;
import org.apache.tajo.storage.StorageConstants;
import org.apache.tajo.storage.Tablespace;
import org.apache.tajo.storage.TablespaceManager;
import org.apache.tajo.util.history.QueryHistory;
import org.apache.tajo.util.history.StageHistory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Query implements EventHandler<QueryEvent> {
private static final Log LOG = LogFactory.getLog(Query.class);
// Facilities for Query
private final TajoConf systemConf;
private final Clock clock;
private final String queryStr;
private final Map<ExecutionBlockId, Stage> stages;
private final EventHandler eventHandler;
private final MasterPlan plan;
QueryMasterTask.QueryMasterTaskContext context;
private ExecutionBlockCursor cursor;
private ExecutionQueue execution;
// Query Status
private final QueryId id;
private long appSubmitTime;
private long startTime;
private long finishTime;
private TableDesc resultDesc;
private volatile int completedStagesCount = 0;
private volatile int succeededStagesCount = 0;
private volatile int killedStagesCount = 0;
private volatile int failedStagesCount = 0;
private volatile int erroredStagesCount = 0;
private volatile SerializedException failureReason;
private final List<String> diagnostics = new ArrayList<>();
// Internal Variables
private final Lock readLock;
private final Lock writeLock;
private int priority = 100;
// State Machine
private final StateMachine<QueryState, QueryEventType, QueryEvent> stateMachine;
private QueryState queryState;
// Transition Handler
private static final InternalErrorTransition INTERNAL_ERROR_TRANSITION = new InternalErrorTransition();
private static final DiagnosticsUpdateTransition DIAGNOSTIC_UPDATE_TRANSITION = new DiagnosticsUpdateTransition();
private static final StageCompletedTransition STAGE_COMPLETED_TRANSITION = new StageCompletedTransition();
private static final QueryCompletedTransition QUERY_COMPLETED_TRANSITION = new QueryCompletedTransition();
protected static final StateMachineFactory
<Query,QueryState,QueryEventType,QueryEvent> stateMachineFactory =
new StateMachineFactory<Query, QueryState, QueryEventType, QueryEvent>
(QueryState.QUERY_NEW)
// Transitions from NEW state
.addTransition(QueryState.QUERY_NEW, QueryState.QUERY_RUNNING,
QueryEventType.START,
new StartTransition())
.addTransition(QueryState.QUERY_NEW, QueryState.QUERY_NEW,
QueryEventType.DIAGNOSTIC_UPDATE,
DIAGNOSTIC_UPDATE_TRANSITION)
.addTransition(QueryState.QUERY_NEW, QueryState.QUERY_KILLED,
QueryEventType.KILL,
new KillNewQueryTransition())
.addTransition(QueryState.QUERY_NEW, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Transitions from RUNNING state
.addTransition(QueryState.QUERY_RUNNING, QueryState.QUERY_RUNNING,
QueryEventType.STAGE_COMPLETED,
STAGE_COMPLETED_TRANSITION)
.addTransition(QueryState.QUERY_RUNNING,
EnumSet.of(QueryState.QUERY_SUCCEEDED, QueryState.QUERY_FAILED, QueryState.QUERY_KILLED,
QueryState.QUERY_ERROR),
QueryEventType.QUERY_COMPLETED,
QUERY_COMPLETED_TRANSITION)
.addTransition(QueryState.QUERY_RUNNING, QueryState.QUERY_RUNNING,
QueryEventType.DIAGNOSTIC_UPDATE,
DIAGNOSTIC_UPDATE_TRANSITION)
.addTransition(QueryState.QUERY_RUNNING, QueryState.QUERY_KILL_WAIT,
QueryEventType.KILL,
new KillAllStagesTransition())
.addTransition(QueryState.QUERY_RUNNING, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Transitions from QUERY_SUCCEEDED state
.addTransition(QueryState.QUERY_SUCCEEDED, QueryState.QUERY_SUCCEEDED,
QueryEventType.DIAGNOSTIC_UPDATE,
DIAGNOSTIC_UPDATE_TRANSITION)
// ignore-able transitions
.addTransition(QueryState.QUERY_SUCCEEDED, QueryState.QUERY_SUCCEEDED,
QueryEventType.STAGE_COMPLETED,
STAGE_COMPLETED_TRANSITION)
.addTransition(QueryState.QUERY_SUCCEEDED, QueryState.QUERY_SUCCEEDED,
QueryEventType.KILL)
.addTransition(QueryState.QUERY_SUCCEEDED, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Transitions from KILL_WAIT state
.addTransition(QueryState.QUERY_KILL_WAIT, QueryState.QUERY_KILL_WAIT,
QueryEventType.STAGE_COMPLETED,
STAGE_COMPLETED_TRANSITION)
.addTransition(QueryState.QUERY_KILL_WAIT,
EnumSet.of(QueryState.QUERY_SUCCEEDED, QueryState.QUERY_FAILED, QueryState.QUERY_KILLED,
QueryState.QUERY_ERROR),
QueryEventType.QUERY_COMPLETED,
QUERY_COMPLETED_TRANSITION)
.addTransition(QueryState.QUERY_KILL_WAIT, QueryState.QUERY_KILL_WAIT,
QueryEventType.DIAGNOSTIC_UPDATE,
DIAGNOSTIC_UPDATE_TRANSITION)
.addTransition(QueryState.QUERY_KILL_WAIT, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Ignore-able transitions
.addTransition(QueryState.QUERY_KILL_WAIT, EnumSet.of(QueryState.QUERY_KILLED),
QueryEventType.KILL,
QUERY_COMPLETED_TRANSITION)
// Transitions from KILLED state
// ignore-able transitions
.addTransition(QueryState.QUERY_KILLED, QueryState.QUERY_KILLED,
EnumSet.of(QueryEventType.START, QueryEventType.QUERY_COMPLETED,
QueryEventType.KILL, QueryEventType.INTERNAL_ERROR))
.addTransition(QueryState.QUERY_KILLED, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Transitions from FAILED state
.addTransition(QueryState.QUERY_FAILED, QueryState.QUERY_FAILED,
QueryEventType.DIAGNOSTIC_UPDATE,
DIAGNOSTIC_UPDATE_TRANSITION)
.addTransition(QueryState.QUERY_FAILED, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Ignore-able transitions
.addTransition(QueryState.QUERY_FAILED, QueryState.QUERY_FAILED,
QueryEventType.KILL)
// Transitions from ERROR state
.addTransition(QueryState.QUERY_ERROR, QueryState.QUERY_ERROR,
QueryEventType.DIAGNOSTIC_UPDATE,
DIAGNOSTIC_UPDATE_TRANSITION)
.addTransition(QueryState.QUERY_ERROR, QueryState.QUERY_ERROR,
QueryEventType.INTERNAL_ERROR,
INTERNAL_ERROR_TRANSITION)
// Ignore-able transitions
.addTransition(QueryState.QUERY_ERROR, QueryState.QUERY_ERROR,
EnumSet.of(QueryEventType.KILL, QueryEventType.STAGE_COMPLETED))
.installTopology();
public Query(final QueryMasterTask.QueryMasterTaskContext context, final QueryId id,
final long appSubmitTime,
final String queryStr,
final EventHandler eventHandler,
final MasterPlan plan) {
this.context = context;
this.systemConf = context.getConf();
this.id = id;
this.clock = context.getClock();
this.appSubmitTime = appSubmitTime;
this.queryStr = queryStr;
this.stages = Maps.newConcurrentMap();
this.eventHandler = eventHandler;
this.plan = plan;
this.cursor = new ExecutionBlockCursor(plan, true);
StringBuilder sb = new StringBuilder("\n=======================================================");
sb.append("\nThe order of execution: \n");
int order = 1;
for (ExecutionBlock currentEB : cursor) {
sb.append("\n").append(order).append(": ").append(currentEB.getId());
order++;
}
sb.append("\n=======================================================");
LOG.info(sb);
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
this.readLock = readWriteLock.readLock();
this.writeLock = readWriteLock.writeLock();
stateMachine = stateMachineFactory.make(this);
queryState = stateMachine.getCurrentState();
}
public float getProgress() {
QueryState state = getState();
if (state == QueryState.QUERY_SUCCEEDED) {
return 1.0f;
} else {
int idx = 0;
List<Stage> tempStages = new ArrayList<>();
synchronized(stages) {
tempStages.addAll(stages.values());
}
float [] subProgresses = new float[tempStages.size()];
for (Stage stage: tempStages) {
if (stage.getState() != StageState.NEW) {
subProgresses[idx] = stage.getProgress();
} else {
subProgresses[idx] = 0.0f;
}
idx++;
}
float totalProgress = 0.0f;
float proportion = 1.0f / (float)(getExecutionBlockCursor().size() - 1); // minus one is due to
for (float subProgress : subProgresses) {
totalProgress += subProgress * proportion;
}
return totalProgress;
}
}
public long getAppSubmitTime() {
return this.appSubmitTime;
}
public long getStartTime() {
return startTime;
}
public void setStartTime() {
startTime = clock.getTime();
}
public long getFinishTime() {
return finishTime;
}
public void setFinishTime() {
finishTime = clock.getTime();
}
public QueryHistory getQueryHistory() {
QueryHistory queryHistory = makeQueryHistory();
queryHistory.setStageHistories(makeStageHistories());
return queryHistory;
}
private List<StageHistory> makeStageHistories() {
List<StageHistory> stageHistories = new ArrayList<>();
for(Stage eachStage : getStages()) {
stageHistories.add(eachStage.getStageHistory());
}
return stageHistories;
}
private QueryHistory makeQueryHistory() {
QueryHistory queryHistory = new QueryHistory();
queryHistory.setQueryId(getId().toString());
queryHistory.setQueryMaster(context.getQueryMasterContext().getWorkerContext().getWorkerName());
queryHistory.setHttpPort(context.getQueryMasterContext().getWorkerContext().getConnectionInfo().getHttpInfoPort());
queryHistory.setLogicalPlan(plan.getLogicalPlan().toString());
queryHistory.setDistributedPlan(plan.toString());
List<String[]> sessionVariables = new ArrayList<>();
for(Map.Entry<String,String> entry: plan.getContext().getAllKeyValus().entrySet()) {
if (SessionVars.exists(entry.getKey()) && SessionVars.isPublic(SessionVars.get(entry.getKey()))) {
sessionVariables.add(new String[]{entry.getKey(), entry.getValue()});
}
}
queryHistory.setSessionVariables(sessionVariables);
return queryHistory;
}
public List<PartitionDescProto> getPartitions() {
Set<PartitionDescProto> partitions = new HashSet<>();
for(Stage eachStage : getStages()) {
partitions.addAll(eachStage.getPartitions());
}
return Lists.newArrayList(partitions);
}
public void clearPartitions() {
for(Stage eachStage : getStages()) {
eachStage.clearPartitions();
}
}
public SerializedException getFailureReason() {
return failureReason;
}
public List<String> getDiagnostics() {
readLock.lock();
try {
return diagnostics;
} finally {
readLock.unlock();
}
}
protected void addDiagnostic(String diag) {
diagnostics.add(diag);
}
public TableDesc getResultDesc() {
return resultDesc;
}
public void setResultDesc(TableDesc desc) {
resultDesc = desc;
}
public MasterPlan getPlan() {
return plan;
}
public StateMachine<QueryState, QueryEventType, QueryEvent> getStateMachine() {
return stateMachine;
}
public void addStage(Stage stage) {
stages.put(stage.getId(), stage);
}
public QueryId getId() {
return this.id;
}
public Stage getStage(ExecutionBlockId id) {
return this.stages.get(id);
}
public Collection<Stage> getStages() {
return this.stages.values();
}
public QueryState getSynchronizedState() {
readLock.lock();
try {
return stateMachine.getCurrentState();
} finally {
readLock.unlock();
}
}
public boolean hasUnionPlan() throws Exception {
boolean result = false;
// In case of UNION statement or UNION ALL statement, the terminal block has two more child blocks.
ExecutionBlock terminalBlock = plan.getTerminalBlock();
if (plan.getChilds(terminalBlock.getId()).size() >= 2) {
result = true;
}
return result;
}
public TableStats aggregateTableStatsOfTerminalBlock() throws Exception {
TableStats aggregated = new TableStats();
ExecutionBlock terminalBlock = plan.getTerminalBlock();
List<ExecutionBlock> childBlocks = plan.getChilds(terminalBlock.getId());
for(ExecutionBlock childBlock : childBlocks) {
Stage childStage = getStage(childBlock.getId());
StatisticsUtil.aggregateTableStat(aggregated, childStage.getResultStats());
}
return aggregated;
}
/* non-blocking call for client API */
public QueryState getState() {
return queryState;
}
public ExecutionBlockCursor getExecutionBlockCursor() {
return cursor;
}
public ExecutionQueue newExecutionQueue() {
return execution = cursor.newCursor();
}
public ExecutionQueue getExecutionQueue() {
return execution;
}
public static class StartTransition
implements SingleArcTransition<Query, QueryEvent> {
@Override
public void transition(Query query, QueryEvent queryEvent) {
query.setStartTime();
ExecutionQueue executionQueue = query.newExecutionQueue();
for (ExecutionBlock executionBlock : executionQueue.first()) {
Stage stage = new Stage(query.context, query.getPlan(), executionBlock);
stage.setPriority(query.priority--);
query.addStage(stage);
stage.getEventHandler().handle(new StageEvent(stage.getId(), StageEventType.SQ_INIT));
LOG.debug("Schedule unit plan: \n" + stage.getBlock().getPlan());
}
}
}
public static class QueryCompletedTransition implements MultipleArcTransition<Query, QueryEvent, QueryState> {
@Override
public QueryState transition(Query query, QueryEvent queryEvent) {
if (!(queryEvent instanceof QueryCompletedEvent)) {
throw new IllegalArgumentException("queryEvent should be a QueryCompletedEvent type.");
}
QueryCompletedEvent stageEvent = (QueryCompletedEvent) queryEvent;
QueryState finalState;
if (stageEvent.getState() == StageState.SUCCEEDED) {
finalState = finalizeQuery(query, stageEvent);
} else if (stageEvent.getState() == StageState.FAILED) {
finalState = QueryState.QUERY_FAILED;
} else if (stageEvent.getState() == StageState.KILLED) {
finalState = QueryState.QUERY_KILLED;
} else {
finalState = QueryState.QUERY_ERROR;
}
// When a query is failed
if (finalState != QueryState.QUERY_SUCCEEDED) {
Stage lastStage = query.getStage(stageEvent.getExecutionBlockId());
handleQueryFailure(query, lastStage);
}
query.eventHandler.handle(new QueryMasterQueryCompletedEvent(query.getId()));
query.setFinishTime();
return finalState;
}
// handle query failures
private void handleQueryFailure(Query query, Stage lastStage) {
QueryContext context = query.context.getQueryContext();
if (lastStage != null && context.hasOutputTableUri()) {
Tablespace space = TablespaceManager.get(context.getOutputTableUri());
try {
LogicalRootNode rootNode = lastStage.getMasterPlan().getLogicalPlan().getRootBlock().getRoot();
space.rollbackTable(rootNode.getChild());
} catch (Throwable e) {
LOG.warn(query.getId() + ", failed processing cleanup storage when query failed:" + e.getMessage(), e);
}
}
}
private QueryState finalizeQuery(Query query, QueryCompletedEvent event) {
Stage lastStage = query.getStage(event.getExecutionBlockId());
try {
LogicalRootNode rootNode = lastStage.getMasterPlan().getLogicalPlan().getRootBlock().getRoot();
CatalogService catalog = lastStage.getContext().getQueryMasterContext().getWorkerContext().getCatalog();
TableDesc tableDesc = PlannerUtil.getTableDesc(catalog, rootNode.getChild());
QueryContext queryContext = query.context.getQueryContext();
// If there is not tabledesc, it is a select query without insert or ctas.
// In this case, we should use default tablespace.
Tablespace space = TablespaceManager.get(queryContext.get(QueryVars.OUTPUT_TABLE_URI, ""));
Path finalOutputDir = space.commitTable(
query.context.getQueryContext(),
lastStage.getId(),
lastStage.getMasterPlan().getLogicalPlan(),
lastStage.getOutSchema(),
tableDesc);
QueryHookExecutor hookExecutor = new QueryHookExecutor(query.context.getQueryMasterContext());
hookExecutor.execute(query.context.getQueryContext(), query, event.getExecutionBlockId(), finalOutputDir);
// Add dynamic partitions to catalog for partition table.
if (queryContext.hasOutputTableUri() && queryContext.hasPartition()) {
List<PartitionDescProto> partitions = query.getPartitions();
if (partitions != null) {
// Set contents length and file count to PartitionDescProto by listing final output directories.
List<PartitionDescProto> finalPartitions = getPartitionsWithContentsSummary(query.systemConf,
finalOutputDir, partitions);
String databaseName, simpleTableName;
if (IdentifierUtil.isFQTableName(tableDesc.getName())) {
String[] split = IdentifierUtil.splitFQTableName(tableDesc.getName());
databaseName = split[0];
simpleTableName = split[1];
} else {
databaseName = queryContext.getCurrentDatabase();
simpleTableName = tableDesc.getName();
}
// Store partitions to CatalogStore using alter table statement.
catalog.addPartitions(databaseName, simpleTableName, finalPartitions, true);
LOG.info("Added partitions to catalog (total=" + partitions.size() + ")");
} else {
LOG.info("Can't find partitions for adding.");
}
query.clearPartitions();
}
} catch (Throwable e) {
LOG.fatal(e.getMessage(), e);
query.failureReason = ErrorUtil.convertException(e);
query.eventHandler.handle(new QueryDiagnosticsUpdateEvent(query.id, ExceptionUtils.getStackTrace(e)));
return QueryState.QUERY_ERROR;
}
return QueryState.QUERY_SUCCEEDED;
}
private List<PartitionDescProto> getPartitionsWithContentsSummary(TajoConf conf, Path outputDir,
List<PartitionDescProto> partitions) throws IOException {
List<PartitionDescProto> finalPartitions = new ArrayList<>();
FileSystem fileSystem = outputDir.getFileSystem(conf);
for (PartitionDescProto partition : partitions) {
PartitionDescProto.Builder builder = partition.toBuilder();
Path partitionPath = new Path(outputDir, partition.getPath());
ContentSummary contentSummary = fileSystem.getContentSummary(partitionPath);
builder.setNumBytes(contentSummary.getLength());
finalPartitions.add(builder.build());
}
return finalPartitions;
}
private static interface QueryHook {
boolean isEligible(QueryContext queryContext, Query query, ExecutionBlockId finalExecBlockId, Path finalOutputDir);
void execute(QueryMaster.QueryMasterContext context, QueryContext queryContext, Query query,
ExecutionBlockId finalExecBlockId, Path finalOutputDir) throws Exception;
}
private static class QueryHookExecutor {
private List<QueryHook> hookList = new ArrayList<>();
private QueryMaster.QueryMasterContext context;
public QueryHookExecutor(QueryMaster.QueryMasterContext context) {
this.context = context;
hookList.add(new MaterializedResultHook());
hookList.add(new CreateTableHook());
hookList.add(new InsertTableHook());
hookList.add(new CreateIndexHook());
}
public void execute(QueryContext queryContext, Query query,
ExecutionBlockId finalExecBlockId,
Path finalOutputDir) throws Exception {
for (QueryHook hook : hookList) {
if (hook.isEligible(queryContext, query, finalExecBlockId, finalOutputDir)) {
hook.execute(context, queryContext, query, finalExecBlockId, finalOutputDir);
}
}
}
}
private static class CreateIndexHook implements QueryHook {
@Override
public boolean isEligible(QueryContext queryContext, Query query, ExecutionBlockId finalExecBlockId, Path finalOutputDir) {
Stage lastStage = query.getStage(finalExecBlockId);
return lastStage.getBlock().getPlan().getType() == NodeType.CREATE_INDEX;
}
@Override
public void execute(QueryMaster.QueryMasterContext context, QueryContext queryContext, Query query, ExecutionBlockId finalExecBlockId, Path finalOutputDir) throws Exception {
CatalogService catalog = context.getWorkerContext().getCatalog();
Stage lastStage = query.getStage(finalExecBlockId);
CreateIndexNode createIndexNode = (CreateIndexNode) lastStage.getBlock().getPlan();
String databaseName, simpleIndexName, qualifiedIndexName;
if (IdentifierUtil.isFQTableName(createIndexNode.getIndexName())) {
String [] splits = IdentifierUtil.splitFQTableName(createIndexNode.getIndexName());
databaseName = splits[0];
simpleIndexName = splits[1];
qualifiedIndexName = createIndexNode.getIndexName();
} else {
databaseName = queryContext.getCurrentDatabase();
simpleIndexName = createIndexNode.getIndexName();
qualifiedIndexName = IdentifierUtil.buildFQName(databaseName, simpleIndexName);
}
ScanNode scanNode = PlannerUtil.findTopNode(createIndexNode, NodeType.SCAN);
if (scanNode == null) {
throw new IOException("Cannot find the table of the relation");
}
IndexDesc indexDesc = new IndexDesc(databaseName, IdentifierUtil.extractSimpleName(scanNode.getTableName()),
simpleIndexName, createIndexNode.getIndexPath(),
createIndexNode.getKeySortSpecs(), createIndexNode.getIndexMethod(),
createIndexNode.isUnique(), false, scanNode.getLogicalSchema());
catalog.createIndex(indexDesc);
LOG.info("Index " + qualifiedIndexName + " is created for the table " + scanNode.getTableName() + ".");
}
}
private static class MaterializedResultHook implements QueryHook {
@Override
public boolean isEligible(QueryContext queryContext, Query query, ExecutionBlockId finalExecBlockId,
Path finalOutputDir) {
Stage lastStage = query.getStage(finalExecBlockId);
NodeType type = lastStage.getBlock().getPlan().getType();
return type != NodeType.CREATE_TABLE && type != NodeType.INSERT;
}
@Override
public void execute(QueryMaster.QueryMasterContext context, QueryContext queryContext,
Query query, ExecutionBlockId finalExecBlockId,
Path finalOutputDir) throws Exception {
Stage lastStage = query.getStage(finalExecBlockId);
TableMeta meta = lastStage.getTableMeta();
String nullChar = queryContext.get(SessionVars.NULL_CHAR);
meta.putProperty(StorageConstants.TEXT_NULL, nullChar);
TableStats stats = lastStage.getResultStats();
TableDesc resultTableDesc =
new TableDesc(
query.getId().toString(),
lastStage.getOutSchema(),
meta,
finalOutputDir.toUri());
resultTableDesc.setExternal(true);
if (query.hasUnionPlan()) {
TableStats aggregated = query.aggregateTableStatsOfTerminalBlock();
resultTableDesc.setStats(aggregated);
} else {
stats.setNumBytes(getTableVolume(query.systemConf, finalOutputDir));
resultTableDesc.setStats(stats);
}
query.setResultDesc(resultTableDesc);
}
}
private static class CreateTableHook implements QueryHook {
@Override
public boolean isEligible(QueryContext queryContext, Query query, ExecutionBlockId finalExecBlockId,
Path finalOutputDir) {
Stage lastStage = query.getStage(finalExecBlockId);
return lastStage.getBlock().getPlan().getType() == NodeType.CREATE_TABLE;
}
@Override
public void execute(QueryMaster.QueryMasterContext context, QueryContext queryContext,
Query query, ExecutionBlockId finalExecBlockId, Path finalOutputDir) throws Exception {
CatalogService catalog = context.getWorkerContext().getCatalog();
Stage lastStage = query.getStage(finalExecBlockId);
TableStats stats = lastStage.getResultStats();
CreateTableNode createTableNode = (CreateTableNode) lastStage.getBlock().getPlan();
TableMeta meta = new TableMeta(createTableNode.getStorageType(), createTableNode.getOptions());
TableDesc tableDescTobeCreated =
new TableDesc(
createTableNode.getTableName(),
createTableNode.getTableSchema(),
meta,
finalOutputDir.toUri());
tableDescTobeCreated.setExternal(createTableNode.isExternal());
if (createTableNode.hasPartition()) {
tableDescTobeCreated.setPartitionMethod(createTableNode.getPartitionMethod());
}
if (query.hasUnionPlan()) {
TableStats aggregated = query.aggregateTableStatsOfTerminalBlock();
tableDescTobeCreated.setStats(aggregated);
} else {
stats.setNumBytes(getTableVolume(query.systemConf, finalOutputDir));
tableDescTobeCreated.setStats(stats);
}
query.setResultDesc(tableDescTobeCreated);
catalog.createTable(tableDescTobeCreated);
}
}
private static class InsertTableHook implements QueryHook {
@Override
public boolean isEligible(QueryContext queryContext, Query query, ExecutionBlockId finalExecBlockId,
Path finalOutputDir) {
Stage lastStage = query.getStage(finalExecBlockId);
return lastStage.getBlock().getPlan().getType() == NodeType.INSERT;
}
@Override
public void execute(QueryMaster.QueryMasterContext context, QueryContext queryContext,
Query query, ExecutionBlockId finalExecBlockId, Path finalOutputDir)
throws Exception {
CatalogService catalog = context.getWorkerContext().getCatalog();
Stage lastStage = query.getStage(finalExecBlockId);
TableMeta meta = lastStage.getTableMeta();
TableStats stats = lastStage.getResultStats();
InsertNode insertNode = (InsertNode) lastStage.getBlock().getPlan();
TableDesc finalTable;
if (insertNode.hasTargetTable()) {
String tableName = insertNode.getTableName();
finalTable = catalog.getTableDesc(tableName);
} else {
String tableName = query.getId().toString();
finalTable = new TableDesc(tableName, lastStage.getOutSchema(), meta, finalOutputDir.toUri());
}
if (query.hasUnionPlan()) {
TableStats aggregated = query.aggregateTableStatsOfTerminalBlock();
finalTable.setStats(aggregated);
} else {
long volume = getTableVolume(query.systemConf, finalOutputDir);
stats.setNumBytes(volume);
finalTable.setStats(stats);
}
if (insertNode.hasTargetTable()) {
UpdateTableStatsProto.Builder builder = UpdateTableStatsProto.newBuilder();
builder.setTableName(finalTable.getName());
builder.setStats(finalTable.getStats().getProto());
catalog.updateTableStats(builder.build());
}
query.setResultDesc(finalTable);
}
}
}
public static long getTableVolume(TajoConf systemConf, Path tablePath) throws IOException {
FileSystem fs = tablePath.getFileSystem(systemConf);
ContentSummary directorySummary = fs.getContentSummary(tablePath);
return directorySummary.getLength();
}
public static class StageCompletedTransition implements SingleArcTransition<Query, QueryEvent> {
// return true for terminal
private synchronized boolean executeNextBlock(Query query, ExecutionBlockId blockId) {
ExecutionQueue cursor = query.getExecutionQueue();
ExecutionBlock[] nextBlocks = cursor.next(blockId);
if (nextBlocks == null || nextBlocks.length == 0) {
return nextBlocks == null;
}
boolean terminal = true;
for (ExecutionBlock nextBlock : nextBlocks) {
if (query.getPlan().isTerminal(nextBlock)) {
continue;
}
Stage nextStage = new Stage(query.context, query.getPlan(), nextBlock);
nextStage.setPriority(query.priority--);
query.addStage(nextStage);
nextStage.getEventHandler().handle(new StageEvent(nextStage.getId(), StageEventType.SQ_INIT));
LOG.info("Scheduling Stage:" + nextStage.getId());
if (LOG.isDebugEnabled()) {
LOG.debug("Scheduling Stage's Priority: " + nextStage.getPriority());
LOG.debug("Scheduling Stage's Plan: \n" + nextStage.getBlock().getPlan());
}
terminal = false;
}
return terminal;
}
@Override
public void transition(Query query, QueryEvent event) {
if (!(event instanceof StageCompletedEvent)) {
throw new IllegalArgumentException("event should be a StageCompletedEvent type.");
}
try {
query.completedStagesCount++;
StageCompletedEvent castEvent = (StageCompletedEvent) event;
if (castEvent.getState() == StageState.SUCCEEDED) {
query.succeededStagesCount++;
} else if (castEvent.getState() == StageState.KILLED) {
query.killedStagesCount++;
} else if (castEvent.getState() == StageState.FAILED) {
query.failedStagesCount++;
query.failureReason = query.getStage(castEvent.getExecutionBlockId()).getFailureReason();
} else if (castEvent.getState() == StageState.ERROR) {
query.erroredStagesCount++;
query.failureReason = query.getStage(castEvent.getExecutionBlockId()).getFailureReason();
} else {
LOG.error(String.format("Invalid Stage (%s) State %s at %s",
castEvent.getExecutionBlockId().toString(), castEvent.getState().name(), query.getSynchronizedState().name()));
query.eventHandler.handle(new QueryEvent(event.getQueryId(), QueryEventType.INTERNAL_ERROR));
}
// if a stage is succeeded and a query is running
if (castEvent.getState() == StageState.SUCCEEDED && // latest stage succeeded
query.getSynchronizedState() == QueryState.QUERY_RUNNING && // current state is not in KILL_WAIT, FAILED, or ERROR.
!executeNextBlock(query, castEvent.getExecutionBlockId())) {
return;
}
//wait for stages is completed
if (query.completedStagesCount >= query.stages.size()) {
// if a query is completed due to finished, kill, failure, or error
query.eventHandler.handle(new QueryCompletedEvent(castEvent.getExecutionBlockId(), castEvent.getState()));
}
LOG.info(String.format("Complete Stage[%s], State: %s, %d/%d. ",
castEvent.getExecutionBlockId().toString(),
castEvent.getState().toString(),
query.completedStagesCount,
query.stages.size()));
} catch (Throwable t) {
LOG.error(t.getMessage(), t);
query.eventHandler.handle(new QueryEvent(event.getQueryId(), QueryEventType.INTERNAL_ERROR));
}
}
}
private static class DiagnosticsUpdateTransition implements SingleArcTransition<Query, QueryEvent> {
@Override
public void transition(Query query, QueryEvent event) {
if (!(event instanceof QueryDiagnosticsUpdateEvent)) {
throw new IllegalArgumentException("event should be a QueryDiagnosticsUpdateEvent type.");
}
query.addDiagnostic(((QueryDiagnosticsUpdateEvent) event).getDiagnosticUpdate());
}
}
private static class KillNewQueryTransition implements SingleArcTransition<Query, QueryEvent> {
@Override
public void transition(Query query, QueryEvent event) {
query.setFinishTime();
query.eventHandler.handle(new QueryMasterQueryCompletedEvent(query.getId()));
}
}
private static class KillAllStagesTransition implements SingleArcTransition<Query, QueryEvent> {
@Override
public void transition(Query query, QueryEvent event) {
synchronized (query.stages) {
for (Stage stage : query.stages.values()) {
stage.stopFinalization();
query.eventHandler.handle(new StageEvent(stage.getId(), StageEventType.SQ_KILL));
}
}
}
}
private static class InternalErrorTransition implements SingleArcTransition<Query, QueryEvent> {
@Override
public void transition(Query query, QueryEvent event) {
query.setFinishTime();
query.eventHandler.handle(new QueryMasterQueryCompletedEvent(query.getId()));
}
}
@Override
public void handle(QueryEvent event) {
LOG.info("Processing " + event.getQueryId() + " of type " + event.getType());
try {
writeLock.lock();
QueryState oldState = getSynchronizedState();
try {
getStateMachine().doTransition(event.getType(), event);
queryState = getSynchronizedState();
} catch (InvalidStateTransitonException e) {
LOG.error("Can't handle this event at current state"
+ ", type:" + event
+ ", oldState:" + oldState.name()
+ ", nextState:" + getSynchronizedState().name()
, e);
eventHandler.handle(new QueryEvent(this.id, QueryEventType.INTERNAL_ERROR));
}
//notify the eventhandler of state change
if (oldState != getSynchronizedState()) {
LOG.info(id + " Query Transitioned from " + oldState + " to " + getSynchronizedState());
}
}
finally {
writeLock.unlock();
}
}
}
|
googleapis/google-cloud-java | 37,407 | java-gke-backup/proto-google-cloud-gke-backup-v1/src/main/java/com/google/cloud/gkebackup/v1/CreateBackupRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/gkebackup/v1/gkebackup.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.gkebackup.v1;
/**
*
*
* <pre>
* Request message for CreateBackup.
* </pre>
*
* Protobuf type {@code google.cloud.gkebackup.v1.CreateBackupRequest}
*/
public final class CreateBackupRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.gkebackup.v1.CreateBackupRequest)
CreateBackupRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateBackupRequest.newBuilder() to construct.
private CreateBackupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateBackupRequest() {
parent_ = "";
backupId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateBackupRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.gkebackup.v1.GKEBackupProto
.internal_static_google_cloud_gkebackup_v1_CreateBackupRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.gkebackup.v1.GKEBackupProto
.internal_static_google_cloud_gkebackup_v1_CreateBackupRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.gkebackup.v1.CreateBackupRequest.class,
com.google.cloud.gkebackup.v1.CreateBackupRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </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 BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int BACKUP_FIELD_NUMBER = 2;
private com.google.cloud.gkebackup.v1.Backup backup_;
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the backup field is set.
*/
@java.lang.Override
public boolean hasBackup() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The backup.
*/
@java.lang.Override
public com.google.cloud.gkebackup.v1.Backup getBackup() {
return backup_ == null ? com.google.cloud.gkebackup.v1.Backup.getDefaultInstance() : backup_;
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.gkebackup.v1.BackupOrBuilder getBackupOrBuilder() {
return backup_ == null ? com.google.cloud.gkebackup.v1.Backup.getDefaultInstance() : backup_;
}
public static final int BACKUP_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object backupId_ = "";
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The backupId.
*/
@java.lang.Override
public java.lang.String getBackupId() {
java.lang.Object ref = backupId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
backupId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for backupId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getBackupIdBytes() {
java.lang.Object ref = backupId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
backupId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getBackup());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backupId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, backupId_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBackup());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backupId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, backupId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.gkebackup.v1.CreateBackupRequest)) {
return super.equals(obj);
}
com.google.cloud.gkebackup.v1.CreateBackupRequest other =
(com.google.cloud.gkebackup.v1.CreateBackupRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasBackup() != other.hasBackup()) return false;
if (hasBackup()) {
if (!getBackup().equals(other.getBackup())) return false;
}
if (!getBackupId().equals(other.getBackupId())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
if (hasBackup()) {
hash = (37 * hash) + BACKUP_FIELD_NUMBER;
hash = (53 * hash) + getBackup().hashCode();
}
hash = (37 * hash) + BACKUP_ID_FIELD_NUMBER;
hash = (53 * hash) + getBackupId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.gkebackup.v1.CreateBackupRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for CreateBackup.
* </pre>
*
* Protobuf type {@code google.cloud.gkebackup.v1.CreateBackupRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.gkebackup.v1.CreateBackupRequest)
com.google.cloud.gkebackup.v1.CreateBackupRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.gkebackup.v1.GKEBackupProto
.internal_static_google_cloud_gkebackup_v1_CreateBackupRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.gkebackup.v1.GKEBackupProto
.internal_static_google_cloud_gkebackup_v1_CreateBackupRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.gkebackup.v1.CreateBackupRequest.class,
com.google.cloud.gkebackup.v1.CreateBackupRequest.Builder.class);
}
// Construct using com.google.cloud.gkebackup.v1.CreateBackupRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getBackupFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
backup_ = null;
if (backupBuilder_ != null) {
backupBuilder_.dispose();
backupBuilder_ = null;
}
backupId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.gkebackup.v1.GKEBackupProto
.internal_static_google_cloud_gkebackup_v1_CreateBackupRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.gkebackup.v1.CreateBackupRequest getDefaultInstanceForType() {
return com.google.cloud.gkebackup.v1.CreateBackupRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.gkebackup.v1.CreateBackupRequest build() {
com.google.cloud.gkebackup.v1.CreateBackupRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.gkebackup.v1.CreateBackupRequest buildPartial() {
com.google.cloud.gkebackup.v1.CreateBackupRequest result =
new com.google.cloud.gkebackup.v1.CreateBackupRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.gkebackup.v1.CreateBackupRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.backup_ = backupBuilder_ == null ? backup_ : backupBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.backupId_ = backupId_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.gkebackup.v1.CreateBackupRequest) {
return mergeFrom((com.google.cloud.gkebackup.v1.CreateBackupRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.gkebackup.v1.CreateBackupRequest other) {
if (other == com.google.cloud.gkebackup.v1.CreateBackupRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasBackup()) {
mergeBackup(other.getBackup());
}
if (!other.getBackupId().isEmpty()) {
backupId_ = other.backupId_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getBackupFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
backupId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </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 BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </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 BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </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 BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </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 BackupPlan within which to create the Backup.
* Format: `projects/*/locations/*/backupPlans/*`
* </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.gkebackup.v1.Backup backup_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.gkebackup.v1.Backup,
com.google.cloud.gkebackup.v1.Backup.Builder,
com.google.cloud.gkebackup.v1.BackupOrBuilder>
backupBuilder_;
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the backup field is set.
*/
public boolean hasBackup() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The backup.
*/
public com.google.cloud.gkebackup.v1.Backup getBackup() {
if (backupBuilder_ == null) {
return backup_ == null
? com.google.cloud.gkebackup.v1.Backup.getDefaultInstance()
: backup_;
} else {
return backupBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setBackup(com.google.cloud.gkebackup.v1.Backup value) {
if (backupBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
backup_ = value;
} else {
backupBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setBackup(com.google.cloud.gkebackup.v1.Backup.Builder builderForValue) {
if (backupBuilder_ == null) {
backup_ = builderForValue.build();
} else {
backupBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeBackup(com.google.cloud.gkebackup.v1.Backup value) {
if (backupBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& backup_ != null
&& backup_ != com.google.cloud.gkebackup.v1.Backup.getDefaultInstance()) {
getBackupBuilder().mergeFrom(value);
} else {
backup_ = value;
}
} else {
backupBuilder_.mergeFrom(value);
}
if (backup_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearBackup() {
bitField0_ = (bitField0_ & ~0x00000002);
backup_ = null;
if (backupBuilder_ != null) {
backupBuilder_.dispose();
backupBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.gkebackup.v1.Backup.Builder getBackupBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getBackupFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.gkebackup.v1.BackupOrBuilder getBackupOrBuilder() {
if (backupBuilder_ != null) {
return backupBuilder_.getMessageOrBuilder();
} else {
return backup_ == null
? com.google.cloud.gkebackup.v1.Backup.getDefaultInstance()
: backup_;
}
}
/**
*
*
* <pre>
* Optional. The Backup resource to create.
* </pre>
*
* <code>.google.cloud.gkebackup.v1.Backup backup = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.gkebackup.v1.Backup,
com.google.cloud.gkebackup.v1.Backup.Builder,
com.google.cloud.gkebackup.v1.BackupOrBuilder>
getBackupFieldBuilder() {
if (backupBuilder_ == null) {
backupBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.gkebackup.v1.Backup,
com.google.cloud.gkebackup.v1.Backup.Builder,
com.google.cloud.gkebackup.v1.BackupOrBuilder>(
getBackup(), getParentForChildren(), isClean());
backup_ = null;
}
return backupBuilder_;
}
private java.lang.Object backupId_ = "";
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The backupId.
*/
public java.lang.String getBackupId() {
java.lang.Object ref = backupId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
backupId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for backupId.
*/
public com.google.protobuf.ByteString getBackupIdBytes() {
java.lang.Object ref = backupId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
backupId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The backupId to set.
* @return This builder for chaining.
*/
public Builder setBackupId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
backupId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearBackupId() {
backupId_ = getDefaultInstance().getBackupId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The client-provided short name for the Backup resource.
* This name must:
*
* - be between 1 and 63 characters long (inclusive)
* - consist of only lower-case ASCII letters, numbers, and dashes
* - start with a lower-case letter
* - end with a lower-case letter or number
* - be unique within the set of Backups in this BackupPlan
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for backupId to set.
* @return This builder for chaining.
*/
public Builder setBackupIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
backupId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.gkebackup.v1.CreateBackupRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.gkebackup.v1.CreateBackupRequest)
private static final com.google.cloud.gkebackup.v1.CreateBackupRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.gkebackup.v1.CreateBackupRequest();
}
public static com.google.cloud.gkebackup.v1.CreateBackupRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateBackupRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateBackupRequest>() {
@java.lang.Override
public CreateBackupRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CreateBackupRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateBackupRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.gkebackup.v1.CreateBackupRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,409 | java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/CreateEntryLinkRequest.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/catalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dataplex.v1;
/**
*
*
* <pre>
* Request message for CreateEntryLink.
* </pre>
*
* Protobuf type {@code google.cloud.dataplex.v1.CreateEntryLinkRequest}
*/
public final class CreateEntryLinkRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.CreateEntryLinkRequest)
CreateEntryLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateEntryLinkRequest.newBuilder() to construct.
private CreateEntryLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateEntryLinkRequest() {
parent_ = "";
entryLinkId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateEntryLinkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataplex.v1.CatalogProto
.internal_static_google_cloud_dataplex_v1_CreateEntryLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataplex.v1.CatalogProto
.internal_static_google_cloud_dataplex_v1_CreateEntryLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataplex.v1.CreateEntryLinkRequest.class,
com.google.cloud.dataplex.v1.CreateEntryLinkRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_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 ENTRY_LINK_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object entryLinkId_ = "";
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The entryLinkId.
*/
@java.lang.Override
public java.lang.String getEntryLinkId() {
java.lang.Object ref = entryLinkId_;
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();
entryLinkId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for entryLinkId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEntryLinkIdBytes() {
java.lang.Object ref = entryLinkId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
entryLinkId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ENTRY_LINK_FIELD_NUMBER = 3;
private com.google.cloud.dataplex.v1.EntryLink entryLink_;
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the entryLink field is set.
*/
@java.lang.Override
public boolean hasEntryLink() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The entryLink.
*/
@java.lang.Override
public com.google.cloud.dataplex.v1.EntryLink getEntryLink() {
return entryLink_ == null
? com.google.cloud.dataplex.v1.EntryLink.getDefaultInstance()
: entryLink_;
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataplex.v1.EntryLinkOrBuilder getEntryLinkOrBuilder() {
return entryLink_ == null
? com.google.cloud.dataplex.v1.EntryLink.getDefaultInstance()
: entryLink_;
}
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(entryLinkId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, entryLinkId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getEntryLink());
}
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(entryLinkId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, entryLinkId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEntryLink());
}
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.CreateEntryLinkRequest)) {
return super.equals(obj);
}
com.google.cloud.dataplex.v1.CreateEntryLinkRequest other =
(com.google.cloud.dataplex.v1.CreateEntryLinkRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getEntryLinkId().equals(other.getEntryLinkId())) return false;
if (hasEntryLink() != other.hasEntryLink()) return false;
if (hasEntryLink()) {
if (!getEntryLink().equals(other.getEntryLink())) 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) + ENTRY_LINK_ID_FIELD_NUMBER;
hash = (53 * hash) + getEntryLinkId().hashCode();
if (hasEntryLink()) {
hash = (37 * hash) + ENTRY_LINK_FIELD_NUMBER;
hash = (53 * hash) + getEntryLink().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest 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.CreateEntryLinkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest 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.CreateEntryLinkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest 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.CreateEntryLinkRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest 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.CreateEntryLinkRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest 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.CreateEntryLinkRequest 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.CreateEntryLinkRequest 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.CreateEntryLinkRequest 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 CreateEntryLink.
* </pre>
*
* Protobuf type {@code google.cloud.dataplex.v1.CreateEntryLinkRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.CreateEntryLinkRequest)
com.google.cloud.dataplex.v1.CreateEntryLinkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataplex.v1.CatalogProto
.internal_static_google_cloud_dataplex_v1_CreateEntryLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataplex.v1.CatalogProto
.internal_static_google_cloud_dataplex_v1_CreateEntryLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataplex.v1.CreateEntryLinkRequest.class,
com.google.cloud.dataplex.v1.CreateEntryLinkRequest.Builder.class);
}
// Construct using com.google.cloud.dataplex.v1.CreateEntryLinkRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEntryLinkFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
entryLinkId_ = "";
entryLink_ = null;
if (entryLinkBuilder_ != null) {
entryLinkBuilder_.dispose();
entryLinkBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dataplex.v1.CatalogProto
.internal_static_google_cloud_dataplex_v1_CreateEntryLinkRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dataplex.v1.CreateEntryLinkRequest getDefaultInstanceForType() {
return com.google.cloud.dataplex.v1.CreateEntryLinkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dataplex.v1.CreateEntryLinkRequest build() {
com.google.cloud.dataplex.v1.CreateEntryLinkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dataplex.v1.CreateEntryLinkRequest buildPartial() {
com.google.cloud.dataplex.v1.CreateEntryLinkRequest result =
new com.google.cloud.dataplex.v1.CreateEntryLinkRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dataplex.v1.CreateEntryLinkRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.entryLinkId_ = entryLinkId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.entryLink_ = entryLinkBuilder_ == null ? entryLink_ : entryLinkBuilder_.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.dataplex.v1.CreateEntryLinkRequest) {
return mergeFrom((com.google.cloud.dataplex.v1.CreateEntryLinkRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataplex.v1.CreateEntryLinkRequest other) {
if (other == com.google.cloud.dataplex.v1.CreateEntryLinkRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getEntryLinkId().isEmpty()) {
entryLinkId_ = other.entryLinkId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasEntryLink()) {
mergeEntryLink(other.getEntryLink());
}
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:
{
entryLinkId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getEntryLinkFieldBuilder().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 resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the parent Entry Group:
* `projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_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 entryLinkId_ = "";
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The entryLinkId.
*/
public java.lang.String getEntryLinkId() {
java.lang.Object ref = entryLinkId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
entryLinkId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for entryLinkId.
*/
public com.google.protobuf.ByteString getEntryLinkIdBytes() {
java.lang.Object ref = entryLinkId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
entryLinkId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The entryLinkId to set.
* @return This builder for chaining.
*/
public Builder setEntryLinkId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
entryLinkId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearEntryLinkId() {
entryLinkId_ = getDefaultInstance().getEntryLinkId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Entry Link identifier
* * Must contain only lowercase letters, numbers and hyphens.
* * Must start with a letter.
* * Must be between 1-63 characters.
* * Must end with a number or a letter.
* * Must be unique within the EntryGroup.
* </pre>
*
* <code>string entry_link_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for entryLinkId to set.
* @return This builder for chaining.
*/
public Builder setEntryLinkIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
entryLinkId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.dataplex.v1.EntryLink entryLink_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataplex.v1.EntryLink,
com.google.cloud.dataplex.v1.EntryLink.Builder,
com.google.cloud.dataplex.v1.EntryLinkOrBuilder>
entryLinkBuilder_;
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the entryLink field is set.
*/
public boolean hasEntryLink() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The entryLink.
*/
public com.google.cloud.dataplex.v1.EntryLink getEntryLink() {
if (entryLinkBuilder_ == null) {
return entryLink_ == null
? com.google.cloud.dataplex.v1.EntryLink.getDefaultInstance()
: entryLink_;
} else {
return entryLinkBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEntryLink(com.google.cloud.dataplex.v1.EntryLink value) {
if (entryLinkBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
entryLink_ = value;
} else {
entryLinkBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEntryLink(com.google.cloud.dataplex.v1.EntryLink.Builder builderForValue) {
if (entryLinkBuilder_ == null) {
entryLink_ = builderForValue.build();
} else {
entryLinkBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeEntryLink(com.google.cloud.dataplex.v1.EntryLink value) {
if (entryLinkBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& entryLink_ != null
&& entryLink_ != com.google.cloud.dataplex.v1.EntryLink.getDefaultInstance()) {
getEntryLinkBuilder().mergeFrom(value);
} else {
entryLink_ = value;
}
} else {
entryLinkBuilder_.mergeFrom(value);
}
if (entryLink_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearEntryLink() {
bitField0_ = (bitField0_ & ~0x00000004);
entryLink_ = null;
if (entryLinkBuilder_ != null) {
entryLinkBuilder_.dispose();
entryLinkBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dataplex.v1.EntryLink.Builder getEntryLinkBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getEntryLinkFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dataplex.v1.EntryLinkOrBuilder getEntryLinkOrBuilder() {
if (entryLinkBuilder_ != null) {
return entryLinkBuilder_.getMessageOrBuilder();
} else {
return entryLink_ == null
? com.google.cloud.dataplex.v1.EntryLink.getDefaultInstance()
: entryLink_;
}
}
/**
*
*
* <pre>
* Required. Entry Link resource.
* </pre>
*
* <code>
* .google.cloud.dataplex.v1.EntryLink entry_link = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataplex.v1.EntryLink,
com.google.cloud.dataplex.v1.EntryLink.Builder,
com.google.cloud.dataplex.v1.EntryLinkOrBuilder>
getEntryLinkFieldBuilder() {
if (entryLinkBuilder_ == null) {
entryLinkBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataplex.v1.EntryLink,
com.google.cloud.dataplex.v1.EntryLink.Builder,
com.google.cloud.dataplex.v1.EntryLinkOrBuilder>(
getEntryLink(), getParentForChildren(), isClean());
entryLink_ = null;
}
return entryLinkBuilder_;
}
@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.CreateEntryLinkRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.CreateEntryLinkRequest)
private static final com.google.cloud.dataplex.v1.CreateEntryLinkRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.CreateEntryLinkRequest();
}
public static com.google.cloud.dataplex.v1.CreateEntryLinkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateEntryLinkRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateEntryLinkRequest>() {
@java.lang.Override
public CreateEntryLinkRequest 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<CreateEntryLinkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateEntryLinkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dataplex.v1.CreateEntryLinkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,432 | java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/ListKnowledgeBasesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2/knowledge_base.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* Response message for
* [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.ListKnowledgeBasesResponse}
*/
public final class ListKnowledgeBasesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.ListKnowledgeBasesResponse)
ListKnowledgeBasesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListKnowledgeBasesResponse.newBuilder() to construct.
private ListKnowledgeBasesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListKnowledgeBasesResponse() {
knowledgeBases_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListKnowledgeBasesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.KnowledgeBaseProto
.internal_static_google_cloud_dialogflow_v2_ListKnowledgeBasesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.KnowledgeBaseProto
.internal_static_google_cloud_dialogflow_v2_ListKnowledgeBasesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.class,
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.Builder.class);
}
public static final int KNOWLEDGE_BASES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.dialogflow.v2.KnowledgeBase> knowledgeBases_;
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.v2.KnowledgeBase> getKnowledgeBasesList() {
return knowledgeBases_;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder>
getKnowledgeBasesOrBuilderList() {
return knowledgeBases_;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
@java.lang.Override
public int getKnowledgeBasesCount() {
return knowledgeBases_.size();
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.KnowledgeBase getKnowledgeBases(int index) {
return knowledgeBases_.get(index);
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder getKnowledgeBasesOrBuilder(
int index) {
return knowledgeBases_.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 < knowledgeBases_.size(); i++) {
output.writeMessage(1, knowledgeBases_.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 < knowledgeBases_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, knowledgeBases_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse other =
(com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse) obj;
if (!getKnowledgeBasesList().equals(other.getKnowledgeBasesList())) 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 (getKnowledgeBasesCount() > 0) {
hash = (37 * hash) + KNOWLEDGE_BASES_FIELD_NUMBER;
hash = (53 * hash) + getKnowledgeBasesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse 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
* [KnowledgeBases.ListKnowledgeBases][google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.ListKnowledgeBasesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.ListKnowledgeBasesResponse)
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.KnowledgeBaseProto
.internal_static_google_cloud_dialogflow_v2_ListKnowledgeBasesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.KnowledgeBaseProto
.internal_static_google_cloud_dialogflow_v2_ListKnowledgeBasesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.class,
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (knowledgeBasesBuilder_ == null) {
knowledgeBases_ = java.util.Collections.emptyList();
} else {
knowledgeBases_ = null;
knowledgeBasesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.KnowledgeBaseProto
.internal_static_google_cloud_dialogflow_v2_ListKnowledgeBasesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse build() {
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse buildPartial() {
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse result =
new com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse result) {
if (knowledgeBasesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
knowledgeBases_ = java.util.Collections.unmodifiableList(knowledgeBases_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.knowledgeBases_ = knowledgeBases_;
} else {
result.knowledgeBases_ = knowledgeBasesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse) {
return mergeFrom((com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse other) {
if (other == com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse.getDefaultInstance())
return this;
if (knowledgeBasesBuilder_ == null) {
if (!other.knowledgeBases_.isEmpty()) {
if (knowledgeBases_.isEmpty()) {
knowledgeBases_ = other.knowledgeBases_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureKnowledgeBasesIsMutable();
knowledgeBases_.addAll(other.knowledgeBases_);
}
onChanged();
}
} else {
if (!other.knowledgeBases_.isEmpty()) {
if (knowledgeBasesBuilder_.isEmpty()) {
knowledgeBasesBuilder_.dispose();
knowledgeBasesBuilder_ = null;
knowledgeBases_ = other.knowledgeBases_;
bitField0_ = (bitField0_ & ~0x00000001);
knowledgeBasesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getKnowledgeBasesFieldBuilder()
: null;
} else {
knowledgeBasesBuilder_.addAllMessages(other.knowledgeBases_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.dialogflow.v2.KnowledgeBase m =
input.readMessage(
com.google.cloud.dialogflow.v2.KnowledgeBase.parser(), extensionRegistry);
if (knowledgeBasesBuilder_ == null) {
ensureKnowledgeBasesIsMutable();
knowledgeBases_.add(m);
} else {
knowledgeBasesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.dialogflow.v2.KnowledgeBase> knowledgeBases_ =
java.util.Collections.emptyList();
private void ensureKnowledgeBasesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
knowledgeBases_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2.KnowledgeBase>(knowledgeBases_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.KnowledgeBase,
com.google.cloud.dialogflow.v2.KnowledgeBase.Builder,
com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder>
knowledgeBasesBuilder_;
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.v2.KnowledgeBase> getKnowledgeBasesList() {
if (knowledgeBasesBuilder_ == null) {
return java.util.Collections.unmodifiableList(knowledgeBases_);
} else {
return knowledgeBasesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public int getKnowledgeBasesCount() {
if (knowledgeBasesBuilder_ == null) {
return knowledgeBases_.size();
} else {
return knowledgeBasesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public com.google.cloud.dialogflow.v2.KnowledgeBase getKnowledgeBases(int index) {
if (knowledgeBasesBuilder_ == null) {
return knowledgeBases_.get(index);
} else {
return knowledgeBasesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder setKnowledgeBases(
int index, com.google.cloud.dialogflow.v2.KnowledgeBase value) {
if (knowledgeBasesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureKnowledgeBasesIsMutable();
knowledgeBases_.set(index, value);
onChanged();
} else {
knowledgeBasesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder setKnowledgeBases(
int index, com.google.cloud.dialogflow.v2.KnowledgeBase.Builder builderForValue) {
if (knowledgeBasesBuilder_ == null) {
ensureKnowledgeBasesIsMutable();
knowledgeBases_.set(index, builderForValue.build());
onChanged();
} else {
knowledgeBasesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder addKnowledgeBases(com.google.cloud.dialogflow.v2.KnowledgeBase value) {
if (knowledgeBasesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureKnowledgeBasesIsMutable();
knowledgeBases_.add(value);
onChanged();
} else {
knowledgeBasesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder addKnowledgeBases(
int index, com.google.cloud.dialogflow.v2.KnowledgeBase value) {
if (knowledgeBasesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureKnowledgeBasesIsMutable();
knowledgeBases_.add(index, value);
onChanged();
} else {
knowledgeBasesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder addKnowledgeBases(
com.google.cloud.dialogflow.v2.KnowledgeBase.Builder builderForValue) {
if (knowledgeBasesBuilder_ == null) {
ensureKnowledgeBasesIsMutable();
knowledgeBases_.add(builderForValue.build());
onChanged();
} else {
knowledgeBasesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder addKnowledgeBases(
int index, com.google.cloud.dialogflow.v2.KnowledgeBase.Builder builderForValue) {
if (knowledgeBasesBuilder_ == null) {
ensureKnowledgeBasesIsMutable();
knowledgeBases_.add(index, builderForValue.build());
onChanged();
} else {
knowledgeBasesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder addAllKnowledgeBases(
java.lang.Iterable<? extends com.google.cloud.dialogflow.v2.KnowledgeBase> values) {
if (knowledgeBasesBuilder_ == null) {
ensureKnowledgeBasesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, knowledgeBases_);
onChanged();
} else {
knowledgeBasesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder clearKnowledgeBases() {
if (knowledgeBasesBuilder_ == null) {
knowledgeBases_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
knowledgeBasesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public Builder removeKnowledgeBases(int index) {
if (knowledgeBasesBuilder_ == null) {
ensureKnowledgeBasesIsMutable();
knowledgeBases_.remove(index);
onChanged();
} else {
knowledgeBasesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public com.google.cloud.dialogflow.v2.KnowledgeBase.Builder getKnowledgeBasesBuilder(
int index) {
return getKnowledgeBasesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder getKnowledgeBasesOrBuilder(
int index) {
if (knowledgeBasesBuilder_ == null) {
return knowledgeBases_.get(index);
} else {
return knowledgeBasesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder>
getKnowledgeBasesOrBuilderList() {
if (knowledgeBasesBuilder_ != null) {
return knowledgeBasesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(knowledgeBases_);
}
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public com.google.cloud.dialogflow.v2.KnowledgeBase.Builder addKnowledgeBasesBuilder() {
return getKnowledgeBasesFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.v2.KnowledgeBase.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public com.google.cloud.dialogflow.v2.KnowledgeBase.Builder addKnowledgeBasesBuilder(
int index) {
return getKnowledgeBasesFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.v2.KnowledgeBase.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of knowledge bases.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.KnowledgeBase knowledge_bases = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.v2.KnowledgeBase.Builder>
getKnowledgeBasesBuilderList() {
return getKnowledgeBasesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.KnowledgeBase,
com.google.cloud.dialogflow.v2.KnowledgeBase.Builder,
com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder>
getKnowledgeBasesFieldBuilder() {
if (knowledgeBasesBuilder_ == null) {
knowledgeBasesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.KnowledgeBase,
com.google.cloud.dialogflow.v2.KnowledgeBase.Builder,
com.google.cloud.dialogflow.v2.KnowledgeBaseOrBuilder>(
knowledgeBases_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
knowledgeBases_ = null;
}
return knowledgeBasesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.ListKnowledgeBasesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.ListKnowledgeBasesResponse)
private static final com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse();
}
public static com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListKnowledgeBasesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListKnowledgeBasesResponse>() {
@java.lang.Override
public ListKnowledgeBasesResponse 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<ListKnowledgeBasesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListKnowledgeBasesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.ListKnowledgeBasesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/coherence | 37,471 | prj/coherence-core-components/src/main/java/com/tangosol/coherence/component/net/management/model/localModel/ConnectionManagerModel.java |
/*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
// ---- class: com.tangosol.coherence.component.net.management.model.localModel.ConnectionManagerModel
package com.tangosol.coherence.component.net.management.model.localModel;
import com.tangosol.coherence.component.util.Queue;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.Acceptor;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.GrpcAcceptor;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.HttpAcceptor;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.MemcachedAcceptor;
import com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor;
import com.tangosol.io.MultiBufferWriteBuffer;
import com.tangosol.net.internal.SocketAddressHelper;
import com.tangosol.util.Base;
import com.tangosol.util.ClassHelper;
import java.net.SocketAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* The status throughput and connection information for Proxy hosts.
*/
@SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"})
public class ConnectionManagerModel
extends com.tangosol.coherence.component.net.management.model.LocalModel
{
// ---- Fields declarations ----
/**
* Property _Acceptor
*
*/
private com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.Acceptor __m__Acceptor;
/**
* Property _CreateTime
*
*/
private transient java.util.Date __m__CreateTime;
/**
* Property HostIP
*
* The IP address and port of the Proxy host.
*/
private transient String __m_HostIP;
/**
* Property MessagingDebug
*
* Debug flag. When true and the node's logging level is 6 or higher, sent
* and received messages will be logged for all the connections under this
* service.
*/
private transient boolean __m_MessagingDebug;
// Default constructor
public ConnectionManagerModel()
{
this(null, null, true);
}
// Initializing constructor
public ConnectionManagerModel(String sName, com.tangosol.coherence.Component compParent, boolean fInit)
{
super(sName, compParent, false);
if (fInit)
{
__init();
}
}
// Main initializer
public void __init()
{
// private initialization
__initPrivate();
// state initialization: public and protected properties
try
{
set_SnapshotMap(new java.util.HashMap());
}
catch (java.lang.Exception e)
{
// re-throw as a runtime exception
throw new com.tangosol.util.WrapperException(e);
}
// signal the end of the initialization
set_Constructed(true);
}
// Private initializer
protected void __initPrivate()
{
super.__initPrivate();
}
//++ getter for static property _Instance
/**
* Getter for property _Instance.<p>
* Auto generated
*/
public static com.tangosol.coherence.Component get_Instance()
{
return new com.tangosol.coherence.component.net.management.model.localModel.ConnectionManagerModel();
}
//++ getter for static property _CLASS
/**
* Getter for property _CLASS.<p>
* Property with auto-generated accessor that returns the Class object for a
* given component.
*/
public static Class get_CLASS()
{
Class clz;
try
{
clz = Class.forName("com.tangosol.coherence/component/net/management/model/localModel/ConnectionManagerModel".replace('/', '.'));
}
catch (ClassNotFoundException e)
{
throw new NoClassDefFoundError(e.getMessage());
}
return clz;
}
//++ getter for autogen property _Module
/**
* This is an auto-generated method that returns the global [design time]
* parent component.
*
* Note: the class generator will ignore any custom implementation for this
* behavior.
*/
private com.tangosol.coherence.Component get_Module()
{
return this;
}
// Accessor for the property "_Acceptor"
/**
* Getter for property _Acceptor.<p>
*/
public com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.Acceptor get_Acceptor()
{
return __m__Acceptor;
}
// Accessor for the property "_CreateTime"
/**
* Getter for property _CreateTime.<p>
*/
public java.util.Date get_CreateTime()
{
return __m__CreateTime;
}
// Accessor for the property "AverageRequestTime"
/**
* Getter for property AverageRequestTime.<p>
* The average processing time in milliseconds for HTTP requests.
*/
public float getAverageRequestTime()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatsFloat((HttpAcceptor) acceptor, "getAverageRequestTime");
}
else
{
return -1.0f;
}
}
// Accessor for the property "ConnectionCount"
/**
* Getter for property ConnectionCount.<p>
* The number of client connections.
*/
public int getConnectionCount()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import java.util.Set;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
Set setConn = ((TcpAcceptor) acceptor).getConnectionSet();
return setConn == null ? 0 : setConn.size();
}
else
{
return -1;
}
}
// Accessor for the property "HostIP"
/**
* Getter for property HostIP.<p>
* The IP address and port of the Proxy host.
*/
public String getHostIP()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
// import com.tangosol.net.internal.SocketAddressHelper;
// import java.net.SocketAddress;
String sAddr = __m_HostIP;
if (sAddr == null)
{
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
SocketAddress address = ((TcpAcceptor) acceptor).getLocalAddress();
if (address != null)
{
sAddr = SocketAddressHelper.toString(address);
setHostIP(sAddr);
}
}
else if (acceptor instanceof HttpAcceptor)
{
HttpAcceptor httpAcceptor = (HttpAcceptor) acceptor;
return httpAcceptor.getLocalAddress() + ':' + httpAcceptor.getListenPort();
}
}
return sAddr;
}
// Accessor for the property "HttpServerType"
/**
* Getter for property HttpServerType.<p>
* The type of HTTP server or n/a if not using HTTP protocol.
*/
public String getHttpServerType()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Object oServer = null;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
oServer = ((HttpAcceptor) acceptor).getHttpServer();
}
return oServer == null ? "n/a" : oServer.getClass().getName();
}
/**
* Return the value of a statistics from the HttpServer from a HttpAcceptor
* as an Object.
* This must be done via reflection as coherence-rest is not guaranteed to
* be in the classpath.
*/
protected Object getHttpStats(com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.HttpAcceptor httpAcceptor, String sMethod)
{
return getHttpStats(httpAcceptor, sMethod, new Object[0]);
}
/**
* Return the value of a statistics from the HttpServer from a HttpAcceptor
* as an Object.
* This must be done via reflection as coherence-rest is not guaranteed to
* be in the classpath.
*/
protected Object getHttpStats(com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.HttpAcceptor httpAcceptor, String sMethod, Object[] oaArgs)
{
// import com.tangosol.util.Base;
// import com.tangosol.util.ClassHelper;
Object oServer = httpAcceptor.getHttpServer();
_assert(oServer != null);
try
{
return ClassHelper.invoke(oServer, sMethod, oaArgs);
}
catch (Exception e)
{
_trace("Unable to call method " + sMethod + " on " + oServer,1);
throw Base.ensureRuntimeException(e);
}
}
/**
* Return the value of a statistics from the HttpServer from a HttpAcceptor
* as a Float.
*/
protected float getHttpStatsFloat(com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.HttpAcceptor httpAcceptor, String sMethod)
{
Float fValue = (Float) getHttpStats(httpAcceptor, sMethod);
return fValue instanceof Float ? fValue.floatValue() : 0L;
}
/**
* Return the value of a statistics from the HttpServer from a HttpAcceptor
* as an Long.
*/
protected long getHttpStatsLong(com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.HttpAcceptor httpAcceptor, String sMethod)
{
Long lValue = (Long) getHttpStats(httpAcceptor, sMethod);
return lValue instanceof Long ? lValue.longValue() : 0L;
}
/**
* Return the value of a status count from the HttpServer from a
* HttpAcceptor as an Long.
*/
protected long getHttpStatusCount(com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.HttpAcceptor httpAcceptor, int nPrefix)
{
Long lValue = (Long) getHttpStats(httpAcceptor, "getHttpStatusCount",
new Object[] { Integer.valueOf(nPrefix) });
return lValue instanceof Long ? lValue.longValue() : 0L;
}
// Accessor for the property "IncomingBufferPoolCapacity"
/**
* Getter for property IncomingBufferPoolCapacity.<p>
*/
public long getIncomingBufferPoolCapacity()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor$BufferPool as com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool pool = ((TcpAcceptor) acceptor).getBufferPoolIn();
return pool == null ? 0l : pool.getMaximumCapacity();
}
else
{
return -1L;
}
}
// Accessor for the property "IncomingBufferPoolSize"
/**
* Getter for property IncomingBufferPoolSize.<p>
*/
public long getIncomingBufferPoolSize()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor$BufferPool as com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool pool = ((TcpAcceptor) acceptor).getBufferPoolIn();
return pool == null ? 0l : pool.getSize() * pool.getBufferSize();
}
else
{
return -1L;
}
}
// Accessor for the property "OutgoingBufferPoolCapacity"
/**
* Getter for property OutgoingBufferPoolCapacity.<p>
*/
public long getOutgoingBufferPoolCapacity()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor$BufferPool as com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool pool = ((TcpAcceptor) acceptor).getBufferPoolOut();
return pool == null ? 0 : pool.getMaximumCapacity();
}
else
{
return -1L;
}
}
// Accessor for the property "OutgoingBufferPoolSize"
/**
* Getter for property OutgoingBufferPoolSize.<p>
*/
public long getOutgoingBufferPoolSize()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor$BufferPool as com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.BufferPool pool = ((TcpAcceptor) acceptor).getBufferPoolOut();
return pool == null ? 0l : pool.getSize() * pool.getBufferSize();
}
else
{
return -1L;
}
}
// Accessor for the property "OutgoingByteBacklog"
/**
* Getter for property OutgoingByteBacklog.<p>
*/
public long getOutgoingByteBacklog()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor$TcpConnection as com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.TcpConnection;
// import Component.Util.Queue;
// import com.tangosol.io.MultiBufferWriteBuffer;
// import java.util.Iterator;
// import java.util.Set;
long cBacklog = 0l;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
Set setConn = ((TcpAcceptor) acceptor).getConnectionSet();
if (setConn != null)
{
for (Iterator iterConn = setConn.iterator(); iterConn.hasNext(); )
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.TcpConnection conn = (com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.TcpConnection) iterConn.next();
if (conn != null)
{
Queue q = conn.getOutgoingQueue();
for (Iterator iterBuff = q.iterator(); iterBuff.hasNext();)
{
MultiBufferWriteBuffer buff = (MultiBufferWriteBuffer) iterBuff.next();
cBacklog += buff.length();
}
}
}
}
}
return cBacklog;
}
// Accessor for the property "OutgoingMessageBacklog"
/**
* Getter for property OutgoingMessageBacklog.<p>
*/
public long getOutgoingMessageBacklog()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor$TcpConnection as com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.TcpConnection;
// import java.util.Set;
// import java.util.Iterator;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
Set setConn = ((TcpAcceptor) acceptor).getConnectionSet();
if (setConn != null)
{
long cBacklog = 0l;
for (Iterator iter = setConn.iterator(); iter.hasNext(); )
{
com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.TcpConnection conn = (com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.acceptor.TcpAcceptor.TcpConnection) iter.next();
if (conn != null)
{
cBacklog += conn.getOutgoingQueue().size();
}
}
return cBacklog;
}
}
return 0l;
}
// Accessor for the property "Protocol"
/**
* Getter for property Protocol.<p>
* Protocol associated with this ConnectionManagerMBean. Valid values are
* tcp or http.
*/
public String getProtocol()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.GrpcAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.MemcachedAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
Acceptor acceptor = get_Acceptor();
return acceptor instanceof TcpAcceptor ? "tcp" :
(acceptor instanceof HttpAcceptor ? "http" :
acceptor instanceof MemcachedAcceptor ? "memcached" :
acceptor instanceof GrpcAcceptor ? "grpc" : "n/a");
}
// Accessor for the property "RequestsPerSecond"
/**
* Getter for property RequestsPerSecond.<p>
* The number of HTTP requests per second since the statistics were reset.
*/
public float getRequestsPerSecond()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatsFloat((HttpAcceptor) acceptor, "getRequestsPerSecond");
}
else
{
return -1.0f;
}
}
// Accessor for the property "ResponseCount1xx"
/**
* Getter for property ResponseCount1xx.<p>
* The number of HTTP responses in the 100-199 range.
*/
public long getResponseCount1xx()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatusCount((HttpAcceptor) acceptor, 1);
}
else
{
return -1L;
}
}
// Accessor for the property "ResponseCount2xx"
/**
* Getter for property ResponseCount2xx.<p>
* The number of HTTP responses in the 200-299 range.
*/
public long getResponseCount2xx()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatusCount((HttpAcceptor) acceptor, 2);
}
else
{
return -1L;
}
}
// Accessor for the property "ResponseCount3xx"
/**
* Getter for property ResponseCount3xx.<p>
* The number of HTTP responses in the 300-399 range.
*/
public long getResponseCount3xx()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatusCount((HttpAcceptor) acceptor, 3);
}
else
{
return -1L;
}
}
// Accessor for the property "ResponseCount4xx"
/**
* Getter for property ResponseCount4xx.<p>
* The number of HTTP responses in the 400-499 range.
*/
public long getResponseCount4xx()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatusCount((HttpAcceptor) acceptor, 4);
}
else
{
return -1L;
}
}
// Accessor for the property "ResponseCount5xx"
/**
* Getter for property ResponseCount5xx.<p>
* The number of HTTP responses in the 500-599 range.
*/
public long getResponseCount5xx()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatusCount((HttpAcceptor) acceptor, 5);
}
else
{
return -1L;
}
}
// Accessor for the property "TotalBytesReceived"
/**
* Getter for property TotalBytesReceived.<p>
*/
public long getTotalBytesReceived()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
return ((TcpAcceptor) acceptor).getStatsBytesReceived();
}
else
{
return -1;
}
}
// Accessor for the property "TotalBytesSent"
/**
* Getter for property TotalBytesSent.<p>
*/
public long getTotalBytesSent()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
return ((TcpAcceptor) acceptor).getStatsBytesSent();
}
else
{
return -1;
}
}
// Accessor for the property "TotalErrorCount"
/**
* Getter for property TotalErrorCount.<p>
* The number of HTTP requests that caused errors.
*/
public long getTotalErrorCount()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatsLong((HttpAcceptor) acceptor, "getErrorCount");
}
else
{
return -1L;
}
}
// Accessor for the property "TotalMessagesReceived"
/**
* Getter for property TotalMessagesReceived.<p>
*/
public long getTotalMessagesReceived()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
return ((TcpAcceptor) acceptor).getStatsReceived();
}
else
{
return -1;
}
}
// Accessor for the property "TotalMessagesSent"
/**
* Getter for property TotalMessagesSent.<p>
*/
public long getTotalMessagesSent()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
return ((TcpAcceptor) acceptor).getStatsSent();
}
else
{
return -1L;
}
}
// Accessor for the property "TotalRequestCount"
/**
* Getter for property TotalRequestCount.<p>
* The number of requests serviced since the HTTP server was started or the
* statistics were reset.
*/
public long getTotalRequestCount()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.HttpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof HttpAcceptor)
{
return getHttpStatsLong((HttpAcceptor) acceptor, "getRequestCount");
}
else
{
return -1L;
}
}
// Accessor for the property "UnauthorizedConnectionAttempts"
/**
* Getter for property UnauthorizedConnectionAttempts.<p>
* The number of connection attempts from unauthorized hosts.
*/
public long getUnauthorizedConnectionAttempts()
{
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor;
// import Component.Util.Daemon.QueueProcessor.Service.Peer.Acceptor.TcpAcceptor;
Acceptor acceptor = get_Acceptor();
if (acceptor instanceof TcpAcceptor)
{
return ((TcpAcceptor) acceptor).getStatsUnauthorizedConnectionAttempts();
}
else
{
return -1;
}
}
// Accessor for the property "MessagingDebug"
/**
* Getter for property MessagingDebug.<p>
* Debug flag. When true and the node's logging level is 6 or higher, sent
* and received messages will be logged for all the connections under this
* service.
*/
public boolean isMessagingDebug()
{
return get_Acceptor().isDEBUG();
}
// Declared at the super level
/**
* Must be supplemented at each specific Model implementation.
*/
public void readExternal(java.io.DataInput in)
throws java.io.IOException
{
// import com.tangosol.util.Base;
// import com.tangosol.util.ExternalizableHelper as com.tangosol.util.ExternalizableHelper;
// import java.util.Map;
super.readExternal(in);
Map mapSnapshot = get_SnapshotMap();
mapSnapshot.put("ConnectionCount", Integer.valueOf(com.tangosol.util.ExternalizableHelper.readInt(in)));
mapSnapshot.put("HostIP", com.tangosol.util.ExternalizableHelper.readUTF(in));
mapSnapshot.put("IncomingBufferPoolCapacity", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("IncomingBufferPoolSize", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("OutgoingBufferPoolCapacity", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("OutgoingBufferPoolSize", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("OutgoingByteBacklog", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("OutgoingMessageBacklog", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("TotalBytesReceived", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("TotalBytesSent", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("TotalMessagesReceived", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("TotalMessagesSent", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("UnauthorizedConnectionAttempts", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
if (com.tangosol.util.ExternalizableHelper.isVersionCompatible(in, 12, 2, 1, 1, 0))
{
mapSnapshot.put("AverageRequestTime", Float.valueOf(in.readFloat()));
mapSnapshot.put("HttpServerType", com.tangosol.util.ExternalizableHelper.readUTF(in));
mapSnapshot.put("Protocol", com.tangosol.util.ExternalizableHelper.readUTF(in));
mapSnapshot.put("ResponseCount1xx", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("ResponseCount2xx", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("ResponseCount3xx", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("ResponseCount4xx", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("ResponseCount5xx", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("RequestsPerSecond", Float.valueOf(in.readFloat()));
mapSnapshot.put("TotalErrorCount", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
mapSnapshot.put("TotalRequestCount", Long.valueOf(com.tangosol.util.ExternalizableHelper.readLong(in)));
}
else
{
mapSnapshot.put("AverageRequestTime", Float.valueOf(-1.0f));
mapSnapshot.put("HttpServerType", "n/a");
mapSnapshot.put("Protocol", "n/a");
mapSnapshot.put("ResponseCount1xx", Long.valueOf(-1L));
mapSnapshot.put("ResponseCount2xx", Long.valueOf(-1L));
mapSnapshot.put("ResponseCount3xx", Long.valueOf(-1L));
mapSnapshot.put("ResponseCount4xx", Long.valueOf(-1L));
mapSnapshot.put("ResponseCount5xx", Long.valueOf(-1L));
mapSnapshot.put("RequestsPerSecond", Float.valueOf(-1.0f));
mapSnapshot.put("TotalErrorCount", Long.valueOf(-1L));
mapSnapshot.put("TotalRequestCount", Long.valueOf(-1L));
}
}
public void resetStatistics()
{
get_Acceptor().resetStats();
}
// Accessor for the property "_Acceptor"
/**
* Setter for property _Acceptor.<p>
*/
public void set_Acceptor(com.tangosol.coherence.component.util.daemon.queueProcessor.service.peer.Acceptor acceptor)
{
__m__Acceptor = acceptor;
}
// Accessor for the property "_CreateTime"
/**
* Setter for property _CreateTime.<p>
*/
public void set_CreateTime(java.util.Date p_CreateTime)
{
__m__CreateTime = p_CreateTime;
}
// Accessor for the property "HostIP"
/**
* Setter for property HostIP.<p>
* The IP address and port of the Proxy host.
*/
protected void setHostIP(String sAddress)
{
__m_HostIP = sAddress;
}
// Accessor for the property "MessagingDebug"
/**
* Setter for property MessagingDebug.<p>
* Debug flag. When true and the node's logging level is 6 or higher, sent
* and received messages will be logged for all the connections under this
* service.
*/
public void setMessagingDebug(boolean fMessagingDebug)
{
get_Acceptor().setDEBUG(fMessagingDebug);
}
// Declared at the super level
/**
* Must be supplemented at each specific Model implementation.
*/
public void writeExternal(java.io.DataOutput out)
throws java.io.IOException
{
// import com.tangosol.util.Base;
// import com.tangosol.util.ExternalizableHelper as com.tangosol.util.ExternalizableHelper;
// import java.util.Map;
super.writeExternal(out);
Map mapSnapshot = get_SnapshotMap();
com.tangosol.util.ExternalizableHelper.writeInt (out, getConnectionCount());
com.tangosol.util.ExternalizableHelper.writeUTF (out, getHostIP());
com.tangosol.util.ExternalizableHelper.writeLong(out, getIncomingBufferPoolCapacity());
com.tangosol.util.ExternalizableHelper.writeLong(out, getIncomingBufferPoolSize());
com.tangosol.util.ExternalizableHelper.writeLong(out, getOutgoingBufferPoolCapacity());
com.tangosol.util.ExternalizableHelper.writeLong(out, getOutgoingBufferPoolSize());
com.tangosol.util.ExternalizableHelper.writeLong(out, getOutgoingByteBacklog());
com.tangosol.util.ExternalizableHelper.writeLong(out, getOutgoingMessageBacklog());
com.tangosol.util.ExternalizableHelper.writeLong(out, getTotalBytesReceived());
com.tangosol.util.ExternalizableHelper.writeLong(out, getTotalBytesSent());
com.tangosol.util.ExternalizableHelper.writeLong(out, getTotalMessagesReceived());
com.tangosol.util.ExternalizableHelper.writeLong(out, getTotalMessagesSent());
com.tangosol.util.ExternalizableHelper.writeLong(out, getUnauthorizedConnectionAttempts());
if (com.tangosol.util.ExternalizableHelper.isVersionCompatible(out, 12, 2, 1, 1, 0))
{
out.writeFloat(getAverageRequestTime());
com.tangosol.util.ExternalizableHelper.writeUTF (out, getHttpServerType());
com.tangosol.util.ExternalizableHelper.writeUTF (out, getProtocol());
com.tangosol.util.ExternalizableHelper.writeLong(out, getResponseCount1xx());
com.tangosol.util.ExternalizableHelper.writeLong(out, getResponseCount2xx());
com.tangosol.util.ExternalizableHelper.writeLong(out, getResponseCount3xx());
com.tangosol.util.ExternalizableHelper.writeLong(out, getResponseCount4xx());
com.tangosol.util.ExternalizableHelper.writeLong(out, getResponseCount5xx());
out.writeFloat(getRequestsPerSecond());
com.tangosol.util.ExternalizableHelper.writeLong(out, getTotalErrorCount());
com.tangosol.util.ExternalizableHelper.writeLong(out, getTotalRequestCount());
}
}
}
|
apache/storm | 37,852 | storm-client/src/jvm/org/apache/storm/topology/TopologyBuilder.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.topology;
import static org.apache.storm.spout.CheckpointSpout.CHECKPOINT_COMPONENT_ID;
import static org.apache.storm.spout.CheckpointSpout.CHECKPOINT_STREAM_ID;
import static org.apache.storm.utils.Utils.parseJson;
import java.io.NotSerializableException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.storm.Config;
import org.apache.storm.generated.Bolt;
import org.apache.storm.generated.ComponentCommon;
import org.apache.storm.generated.ComponentObject;
import org.apache.storm.generated.GlobalStreamId;
import org.apache.storm.generated.Grouping;
import org.apache.storm.generated.NullStruct;
import org.apache.storm.generated.SharedMemory;
import org.apache.storm.generated.SpoutSpec;
import org.apache.storm.generated.StateSpoutSpec;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.grouping.CustomStreamGrouping;
import org.apache.storm.grouping.PartialKeyGrouping;
import org.apache.storm.hooks.IWorkerHook;
import org.apache.storm.lambda.LambdaBiConsumerBolt;
import org.apache.storm.lambda.LambdaConsumerBolt;
import org.apache.storm.lambda.LambdaSpout;
import org.apache.storm.lambda.SerializableBiConsumer;
import org.apache.storm.lambda.SerializableConsumer;
import org.apache.storm.lambda.SerializableSupplier;
import org.apache.storm.shade.net.minidev.json.JSONValue;
import org.apache.storm.spout.CheckpointSpout;
import org.apache.storm.state.State;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.utils.Utils;
import org.apache.storm.windowing.TupleWindow;
/**
* TopologyBuilder exposes the Java API for specifying a topology for Storm to execute. Topologies are Thrift structures in the end, but
* since the Thrift API is so verbose, TopologyBuilder greatly eases the process of creating topologies. The template for creating and
* submitting a topology looks something like:
*
* <p>```java TopologyBuilder builder = new TopologyBuilder();
*
* <p>builder.setSpout("1", new TestWordSpout(true), 5); builder.setSpout("2", new TestWordSpout(true), 3); builder.setBolt("3", new
* TestWordCounter(), 3) .fieldsGrouping("1", new Fields("word")) .fieldsGrouping("2", new Fields("word")); builder.setBolt("4", new
* TestGlobalCount()) .globalGrouping("1");
*
* <p>Map<String, Object> conf = new HashMap(); conf.put(Config.TOPOLOGY_WORKERS, 4);
*
* <p>StormSubmitter.submitTopology("mytopology", conf, builder.createTopology()); ```
*
* <p>Running the exact same topology in local mode (in process), and configuring it to log all tuples emitted, looks
* like the following. Note that it lets the topology run for 10 seconds before shutting down the local cluster.
*
* <p>```java TopologyBuilder builder = new TopologyBuilder();
*
* <p>builder.setSpout("1", new TestWordSpout(true), 5); builder.setSpout("2", new TestWordSpout(true), 3); builder.setBolt("3", new
* TestWordCounter(), 3) .fieldsGrouping("1", new Fields("word")) .fieldsGrouping("2", new Fields("word")); builder.setBolt("4", new
* TestGlobalCount()) .globalGrouping("1");
*
* <p>Map<String, Object> conf = new HashMap(); conf.put(Config.TOPOLOGY_WORKERS, 4); conf.put(Config.TOPOLOGY_DEBUG, true);
*
* <p>try (LocalCluster cluster = new LocalCluster(); LocalTopology topo = cluster.submitTopology("mytopology", conf,
* builder.createTopology());){ Utils.sleep(10000); } ```
*
* <p>The pattern for `TopologyBuilder` is to map component ids to components using the setSpout and setBolt methods. Those methods return
* objects that are then used to declare the inputs for that component.
*/
public class TopologyBuilder {
private final Map<String, IRichBolt> bolts = new HashMap<>();
private final Map<String, IRichSpout> spouts = new HashMap<>();
private final Map<String, ComponentCommon> commons = new HashMap<>();
private final Map<String, Set<String>> componentToSharedMemory = new HashMap<>();
private final Map<String, SharedMemory> sharedMemory = new HashMap<>();
private boolean hasStatefulBolt = false;
private Map<String, StateSpoutSpec> stateSpouts = new HashMap<>();
private List<ByteBuffer> workerHooks = new ArrayList<>();
private static String mergeIntoJson(Map<String, Object> into, Map<String, Object> newMap) {
Map<String, Object> res = new HashMap<>(into);
res.putAll(newMap);
return JSONValue.toJSONString(res);
}
public StormTopology createTopology() {
Map<String, Bolt> boltSpecs = new HashMap<>();
Map<String, SpoutSpec> spoutSpecs = new HashMap<>();
maybeAddCheckpointSpout();
for (String boltId : bolts.keySet()) {
IRichBolt bolt = bolts.get(boltId);
bolt = maybeAddCheckpointTupleForwarder(bolt);
ComponentCommon common = getComponentCommon(boltId, bolt);
try {
maybeAddCheckpointInputs(common);
boltSpecs.put(boltId, new Bolt(ComponentObject.serialized_java(Utils.javaSerialize(bolt)), common));
} catch (RuntimeException wrapperCause) {
if (wrapperCause.getCause() != null && NotSerializableException.class.equals(wrapperCause.getCause().getClass())) {
throw new IllegalStateException("Bolt '" + boltId + "' contains a non-serializable field of type "
+ wrapperCause.getCause().getMessage() + ", "
+ "which was instantiated prior to topology creation. "
+ wrapperCause.getCause().getMessage()
+ " "
+ "should be instantiated within the prepare method of '"
+ boltId
+ " at the earliest.",
wrapperCause);
}
throw wrapperCause;
}
}
for (String spoutId : spouts.keySet()) {
IRichSpout spout = spouts.get(spoutId);
ComponentCommon common = getComponentCommon(spoutId, spout);
try {
spoutSpecs.put(spoutId, new SpoutSpec(ComponentObject.serialized_java(Utils.javaSerialize(spout)), common));
} catch (RuntimeException wrapperCause) {
if (wrapperCause.getCause() != null && NotSerializableException.class.equals(wrapperCause.getCause().getClass())) {
throw new IllegalStateException(
"Spout '" + spoutId + "' contains a non-serializable field of type "
+ wrapperCause.getCause().getMessage()
+ ", which was instantiated prior to topology creation. "
+ wrapperCause.getCause().getMessage()
+ " should be instantiated within the open method of '"
+ spoutId
+ " at the earliest.",
wrapperCause);
}
throw wrapperCause;
}
}
StormTopology stormTopology = new StormTopology(spoutSpecs,
boltSpecs,
new HashMap<>());
stormTopology.set_worker_hooks(workerHooks);
if (!componentToSharedMemory.isEmpty()) {
stormTopology.set_component_to_shared_memory(componentToSharedMemory);
stormTopology.set_shared_memory(sharedMemory);
}
return Utils.addVersions(stormTopology);
}
/**
* Define a new bolt in this topology with parallelism of just one thread.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param bolt the bolt
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, IRichBolt bolt) throws IllegalArgumentException {
return setBolt(id, bolt, null);
}
/**
* Define a new bolt in this topology with the specified amount of parallelism.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param bolt the bolt
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somewhere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, IRichBolt bolt, Number parallelismHint) throws IllegalArgumentException {
validateUnusedId(id);
initCommon(id, bolt, parallelismHint);
bolts.put(id, bolt);
return new BoltGetter(id);
}
/**
* Define a new bolt in this topology. This defines a basic bolt, which is a simpler to use but more restricted kind of bolt. Basic
* bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in the
* topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param bolt the basic bolt
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, IBasicBolt bolt) throws IllegalArgumentException {
return setBolt(id, bolt, null);
}
/**
* Define a new bolt in this topology. This defines a basic bolt, which is a simpler to use but more restricted kind of bolt. Basic
* bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in the
* topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param bolt the basic bolt
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somewhere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, IBasicBolt bolt, Number parallelismHint) throws IllegalArgumentException {
return setBolt(id, new BasicBoltExecutor(bolt), parallelismHint);
}
/**
* Define a new bolt in this topology. This defines a windowed bolt, intended for windowing operations. The {@link
* IWindowedBolt#execute(TupleWindow)} method is triggered for each window interval with the list of current events in the window.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param bolt the windowed bolt
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, IWindowedBolt bolt) throws IllegalArgumentException {
return setBolt(id, bolt, null);
}
/**
* Define a new bolt in this topology. This defines a windowed bolt, intended for windowing operations. The {@link
* IWindowedBolt#execute(TupleWindow)} method is triggered for each window interval with the list of current events in the window.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param bolt the windowed bolt
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somwehere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, IWindowedBolt bolt, Number parallelismHint) throws IllegalArgumentException {
return setBolt(id, new WindowedBoltExecutor(bolt), parallelismHint);
}
/**
* Define a new bolt in this topology. This defines a stateful bolt, that requires its state (of computation) to be saved. When this
* bolt is initialized, the {@link IStatefulBolt#initState(State)} method is invoked after {@link IStatefulBolt#prepare(Map,
* TopologyContext, OutputCollector)} but before {@link IStatefulBolt#execute(Tuple)} with its previously saved state.
* <p>
* The framework provides at-least once guarantee for the state updates. Bolts (both stateful and non-stateful) in a stateful topology
* are expected to anchor the tuples while emitting and ack the input tuples once its processed.
* </p>
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param bolt the stateful bolt
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public <T extends State> BoltDeclarer setBolt(String id, IStatefulBolt<T> bolt) throws IllegalArgumentException {
return setBolt(id, bolt, null);
}
/**
* Define a new bolt in this topology. This defines a stateful bolt, that requires its state (of computation) to be saved. When this
* bolt is initialized, the {@link IStatefulBolt#initState(State)} method is invoked after {@link IStatefulBolt#prepare(Map,
* TopologyContext, OutputCollector)} but before {@link IStatefulBolt#execute(Tuple)} with its previously saved state.
* <p>
* The framework provides at-least once guarantee for the state updates. Bolts (both stateful and non-stateful) in a stateful topology
* are expected to anchor the tuples while emitting and ack the input tuples once its processed.
* </p>
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param bolt the stateful bolt
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somwehere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public <T extends State> BoltDeclarer setBolt(String id, IStatefulBolt<T> bolt, Number parallelismHint) throws
IllegalArgumentException {
hasStatefulBolt = true;
return setBolt(id, new StatefulBoltExecutor<T>(bolt), parallelismHint);
}
/**
* Define a new bolt in this topology. This defines a stateful windowed bolt, intended for stateful windowing operations. The {@link
* IStatefulWindowedBolt#execute(TupleWindow)} method is triggered for each window interval with the list of current events in the
* window. During initialization of this bolt {@link IStatefulWindowedBolt#initState(State)} is invoked with its previously saved
* state.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param bolt the stateful windowed bolt
* @param <T> the type of the state (e.g. {@link org.apache.storm.state.KeyValueState})
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public <T extends State> BoltDeclarer setBolt(String id, IStatefulWindowedBolt<T> bolt) throws IllegalArgumentException {
return setBolt(id, bolt, null);
}
/**
* Define a new bolt in this topology. This defines a stateful windowed bolt, intended for stateful windowing operations. The {@link
* IStatefulWindowedBolt#execute(TupleWindow)} method is triggered for each window interval with the list of current events in the
* window. During initialization of this bolt {@link IStatefulWindowedBolt#initState(State)} is invoked with its previously saved
* state.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param bolt the stateful windowed bolt
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somewhere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public <T extends State> BoltDeclarer setBolt(String id, IStatefulWindowedBolt<T> bolt, Number parallelismHint) throws
IllegalArgumentException {
hasStatefulBolt = true;
IStatefulBolt<T> executor;
if (bolt.isPersistent()) {
executor = new PersistentWindowedBoltExecutor<>(bolt);
} else {
executor = new StatefulWindowedBoltExecutor<T>(bolt);
}
return setBolt(id, new StatefulBoltExecutor<T>(executor), parallelismHint);
}
/**
* Define a new bolt in this topology. This defines a lambda basic bolt, which is a simpler to use but more restricted kind of bolt.
* Basic bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in
* the topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param biConsumer lambda expression that implements tuple processing for this bolt
* @param fields fields for tuple that should be emitted to downstream bolts
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, SerializableBiConsumer<Tuple, BasicOutputCollector> biConsumer, String... fields) throws
IllegalArgumentException {
return setBolt(id, biConsumer, null, fields);
}
/**
* Define a new bolt in this topology. This defines a lambda basic bolt, which is a simpler to use but more restricted kind of bolt.
* Basic bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in
* the topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param biConsumer lambda expression that implements tuple processing for this bolt
* @param fields fields for tuple that should be emitted to downstream bolts
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somewhere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, SerializableBiConsumer<Tuple, BasicOutputCollector> biConsumer, Number parallelismHint,
String... fields) throws IllegalArgumentException {
return setBolt(id, new LambdaBiConsumerBolt(biConsumer, fields), parallelismHint);
}
/**
* Define a new bolt in this topology. This defines a lambda basic bolt, which is a simpler to use but more restricted kind of bolt.
* Basic bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in
* the topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs.
* @param consumer lambda expression that implements tuple processing for this bolt
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, SerializableConsumer<Tuple> consumer) throws IllegalArgumentException {
return setBolt(id, consumer, null);
}
/**
* Define a new bolt in this topology. This defines a lambda basic bolt, which is a simpler to use but more restricted kind of bolt.
* Basic bolts are intended for non-aggregation processing and automate the anchoring/acking process to achieve proper reliability in
* the topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this bolt's
* outputs.
* @param consumer lambda expression that implements tuple processing for this bolt
* @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process
* somewhere around the cluster.
* @return use the returned object to declare the inputs to this component
*
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public BoltDeclarer setBolt(String id, SerializableConsumer<Tuple> consumer, Number parallelismHint) throws IllegalArgumentException {
return setBolt(id, new LambdaConsumerBolt(consumer), parallelismHint);
}
/**
* Define a new spout in this topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this spout's outputs.
* @param spout the spout
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public SpoutDeclarer setSpout(String id, IRichSpout spout) throws IllegalArgumentException {
return setSpout(id, spout, null);
}
/**
* Define a new spout in this topology with the specified parallelism. If the spout declares itself as non-distributed, the
* parallelism_hint will be ignored and only one task will be allocated to this component.
*
* @param id the id of this component. This id is referenced by other components that want to consume this spout's
* outputs.
* @param parallelismHint the number of tasks that should be assigned to execute this spout. Each task will run on a thread in a
* process somewhere around the cluster.
* @param spout the spout
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public SpoutDeclarer setSpout(String id, IRichSpout spout, Number parallelismHint) throws IllegalArgumentException {
validateUnusedId(id);
initCommon(id, spout, parallelismHint);
spouts.put(id, spout);
return new SpoutGetter(id);
}
/**
* Define a new spout in this topology.
*
* @param id the id of this component. This id is referenced by other components that want to consume this spout's outputs.
* @param supplier lambda expression that implements tuple generating for this spout
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public SpoutDeclarer setSpout(String id, SerializableSupplier<?> supplier) throws IllegalArgumentException {
return setSpout(id, supplier, null);
}
/**
* Define a new spout in this topology with the specified parallelism. If the spout declares itself as non-distributed, the
* parallelism_hint will be ignored and only one task will be allocated to this component.
*
* @param id the id of this component. This id is referenced by other components that want to consume this spout's
* outputs.
* @param parallelismHint the number of tasks that should be assigned to execute this spout. Each task will run on a thread in a
* process somewhere around the cluster.
* @param supplier lambda expression that implements tuple generating for this spout
* @throws IllegalArgumentException if {@code parallelism_hint} is not positive
*/
public SpoutDeclarer setSpout(String id, SerializableSupplier<?> supplier, Number parallelismHint) throws IllegalArgumentException {
return setSpout(id, new LambdaSpout(supplier), parallelismHint);
}
/**
* Add a new worker lifecycle hook.
*
* @param workerHook the lifecycle hook to add
*/
public void addWorkerHook(IWorkerHook workerHook) {
if (null == workerHook) {
throw new IllegalArgumentException("WorkerHook must not be null.");
}
workerHooks.add(ByteBuffer.wrap(Utils.javaSerialize(workerHook)));
}
private void validateUnusedId(String id) {
if (bolts.containsKey(id)) {
throw new IllegalArgumentException("Bolt has already been declared for id " + id);
}
if (spouts.containsKey(id)) {
throw new IllegalArgumentException("Spout has already been declared for id " + id);
}
if (stateSpouts.containsKey(id)) {
throw new IllegalArgumentException("State spout has already been declared for id " + id);
}
}
/**
* If the topology has at least one stateful bolt add a {@link CheckpointSpout} component to the topology.
*/
private void maybeAddCheckpointSpout() {
if (hasStatefulBolt) {
setSpout(CHECKPOINT_COMPONENT_ID, new CheckpointSpout(), 1);
}
}
private void maybeAddCheckpointInputs(ComponentCommon common) {
if (hasStatefulBolt) {
addCheckPointInputs(common);
}
}
/**
* If the topology has at least one stateful bolt all the non-stateful bolts are wrapped in {@link CheckpointTupleForwarder} so that the
* checkpoint tuples can flow through the topology.
*/
private IRichBolt maybeAddCheckpointTupleForwarder(IRichBolt bolt) {
if (hasStatefulBolt && !(bolt instanceof StatefulBoltExecutor)) {
bolt = new CheckpointTupleForwarder(bolt);
}
return bolt;
}
/**
* For bolts that has incoming streams from spouts (the root bolts), add checkpoint stream from checkpoint spout to its input. For other
* bolts, add checkpoint stream from the previous bolt to its input.
*/
private void addCheckPointInputs(ComponentCommon component) {
Set<GlobalStreamId> checkPointInputs = new HashSet<>();
for (GlobalStreamId inputStream : component.get_inputs().keySet()) {
String sourceId = inputStream.get_componentId();
if (spouts.containsKey(sourceId)) {
checkPointInputs.add(new GlobalStreamId(CHECKPOINT_COMPONENT_ID, CHECKPOINT_STREAM_ID));
} else {
checkPointInputs.add(new GlobalStreamId(sourceId, CHECKPOINT_STREAM_ID));
}
}
for (GlobalStreamId streamId : checkPointInputs) {
component.put_to_inputs(streamId, Grouping.all(new NullStruct()));
}
}
private ComponentCommon getComponentCommon(String id, IComponent component) {
ComponentCommon ret = new ComponentCommon(commons.get(id));
OutputFieldsGetter getter = new OutputFieldsGetter();
component.declareOutputFields(getter);
ret.set_streams(getter.getFieldsDeclaration());
return ret;
}
private void initCommon(String id, IComponent component, Number parallelism) throws IllegalArgumentException {
ComponentCommon common = new ComponentCommon();
common.set_inputs(new HashMap<GlobalStreamId, Grouping>());
if (parallelism != null) {
int dop = parallelism.intValue();
if (dop < 1) {
throw new IllegalArgumentException("Parallelism must be positive.");
}
common.set_parallelism_hint(dop);
}
Map<String, Object> conf = component.getComponentConfiguration();
if (conf != null) {
common.set_json_conf(JSONValue.toJSONString(conf));
}
commons.put(id, common);
}
protected class ConfigGetter<T extends ComponentConfigurationDeclarer> extends BaseConfigurationDeclarer<T> {
String id;
public ConfigGetter(String id) {
this.id = id;
}
@SuppressWarnings("unchecked")
@Override
public T addConfigurations(Map<String, Object> conf) {
if (conf != null) {
if (conf.containsKey(Config.TOPOLOGY_KRYO_REGISTER)) {
throw new IllegalArgumentException("Cannot set serializations for a component using fluent API");
}
if (!conf.isEmpty()) {
String currConf = commons.get(id).get_json_conf();
commons.get(id).set_json_conf(mergeIntoJson(parseJson(currConf), conf));
}
}
return (T) this;
}
/**
* return the current component configuration.
*
* @return the current configuration.
*/
@Override
public Map<String, Object> getComponentConfiguration() {
return parseJson(commons.get(id).get_json_conf());
}
@Override
public T addResources(Map<String, Double> resources) {
if (resources != null && !resources.isEmpty()) {
String currConf = commons.get(id).get_json_conf();
Map<String, Object> conf = parseJson(currConf);
Map<String, Double> currentResources =
(Map<String, Double>) conf.computeIfAbsent(Config.TOPOLOGY_COMPONENT_RESOURCES_MAP, (k) -> new HashMap<>());
currentResources.putAll(resources);
commons.get(id).set_json_conf(JSONValue.toJSONString(conf));
}
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T addResource(String resourceName, Number resourceValue) {
Map<String, Object> componentConf = parseJson(commons.get(id).get_json_conf());
Map<String, Double> resourcesMap = (Map<String, Double>) componentConf.computeIfAbsent(
Config.TOPOLOGY_COMPONENT_RESOURCES_MAP, (k) -> new HashMap<>());
resourcesMap.put(resourceName, resourceValue.doubleValue());
return addConfiguration(Config.TOPOLOGY_COMPONENT_RESOURCES_MAP, resourcesMap);
}
@SuppressWarnings("unchecked")
@Override
public T addSharedMemory(SharedMemory request) {
SharedMemory found = sharedMemory.get(request.get_name());
if (found != null && !found.equals(request)) {
throw new IllegalArgumentException("Cannot have multiple different shared memory regions with the same name");
}
sharedMemory.put(request.get_name(), request);
Set<String> mems = componentToSharedMemory.computeIfAbsent(id, (k) -> new HashSet<>());
mems.add(request.get_name());
return (T) this;
}
}
protected class SpoutGetter extends ConfigGetter<SpoutDeclarer> implements SpoutDeclarer {
public SpoutGetter(String id) {
super(id);
}
}
protected class BoltGetter extends ConfigGetter<BoltDeclarer> implements BoltDeclarer {
private String boltId;
public BoltGetter(String boltId) {
super(boltId);
this.boltId = boltId;
}
@Override
public BoltDeclarer fieldsGrouping(String componentId, Fields fields) {
return fieldsGrouping(componentId, Utils.DEFAULT_STREAM_ID, fields);
}
@Override
public BoltDeclarer fieldsGrouping(String componentId, String streamId, Fields fields) {
return grouping(componentId, streamId, Grouping.fields(fields.toList()));
}
@Override
public BoltDeclarer globalGrouping(String componentId) {
return globalGrouping(componentId, Utils.DEFAULT_STREAM_ID);
}
@Override
public BoltDeclarer globalGrouping(String componentId, String streamId) {
return grouping(componentId, streamId, Grouping.fields(new ArrayList<String>()));
}
@Override
public BoltDeclarer shuffleGrouping(String componentId) {
return shuffleGrouping(componentId, Utils.DEFAULT_STREAM_ID);
}
@Override
public BoltDeclarer shuffleGrouping(String componentId, String streamId) {
return grouping(componentId, streamId, Grouping.shuffle(new NullStruct()));
}
@Override
public BoltDeclarer localOrShuffleGrouping(String componentId) {
return localOrShuffleGrouping(componentId, Utils.DEFAULT_STREAM_ID);
}
@Override
public BoltDeclarer localOrShuffleGrouping(String componentId, String streamId) {
return grouping(componentId, streamId, Grouping.local_or_shuffle(new NullStruct()));
}
@Override
public BoltDeclarer noneGrouping(String componentId) {
return noneGrouping(componentId, Utils.DEFAULT_STREAM_ID);
}
@Override
public BoltDeclarer noneGrouping(String componentId, String streamId) {
return grouping(componentId, streamId, Grouping.none(new NullStruct()));
}
@Override
public BoltDeclarer allGrouping(String componentId) {
return allGrouping(componentId, Utils.DEFAULT_STREAM_ID);
}
@Override
public BoltDeclarer allGrouping(String componentId, String streamId) {
return grouping(componentId, streamId, Grouping.all(new NullStruct()));
}
@Override
public BoltDeclarer directGrouping(String componentId) {
return directGrouping(componentId, Utils.DEFAULT_STREAM_ID);
}
@Override
public BoltDeclarer directGrouping(String componentId, String streamId) {
return grouping(componentId, streamId, Grouping.direct(new NullStruct()));
}
private BoltDeclarer grouping(String componentId, String streamId, Grouping grouping) {
commons.get(boltId).put_to_inputs(new GlobalStreamId(componentId, streamId), grouping);
return this;
}
@Override
public BoltDeclarer grouping(GlobalStreamId id, Grouping grouping) {
return grouping(id.get_componentId(), id.get_streamId(), grouping);
}
@Override
public BoltDeclarer partialKeyGrouping(String componentId, Fields fields) {
return customGrouping(componentId, new PartialKeyGrouping(fields));
}
@Override
public BoltDeclarer partialKeyGrouping(String componentId, String streamId, Fields fields) {
return customGrouping(componentId, streamId, new PartialKeyGrouping(fields));
}
@Override
public BoltDeclarer customGrouping(String componentId, CustomStreamGrouping grouping) {
return customGrouping(componentId, Utils.DEFAULT_STREAM_ID, grouping);
}
@Override
public BoltDeclarer customGrouping(String componentId, String streamId, CustomStreamGrouping grouping) {
return grouping(componentId, streamId, Grouping.custom_serialized(Utils.javaSerialize(grouping)));
}
}
}
|
googleapis/google-api-java-client-services | 37,634 | clients/google-api-services-bigquery/v2/2.0.0/com/google/api/services/bigquery/model/ExternalDataConfiguration.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.bigquery.model;
/**
* Model definition for ExternalDataConfiguration.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the BigQuery API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ExternalDataConfiguration extends com.google.api.client.json.GenericJson {
/**
* Try to detect schema and format options automatically. Any option specified explicitly will be
* honored.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean autodetect;
/**
* Optional. Additional properties to set if sourceFormat is set to AVRO.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private AvroOptions avroOptions;
/**
* Optional. Additional options if sourceFormat is set to BIGTABLE.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BigtableOptions bigtableOptions;
/**
* Optional. The compression type of the data source. Possible values include GZIP and NONE. The
* default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud
* Datastore backups, Avro, ORC and Parquet formats. An empty string is an invalid value.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compression;
/**
* Optional. The connection specifying the credentials to be used to read external storage, such
* as Azure Blob, Cloud Storage, or S3. The connection_id can have the form
* `{project_id}.{location_id};{connection_id}` or
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String connectionId;
/**
* Optional. Additional properties to set if sourceFormat is set to CSV.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CsvOptions csvOptions;
/**
* Optional. Format used to parse DATE values. Supports C-style and SQL-style values.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String dateFormat;
/**
* Optional. Format used to parse DATETIME values. Supports C-style and SQL-style values.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String datetimeFormat;
/**
* Defines the list of possible SQL data types to which the source decimal values are converted.
* This list and the precision and the scale parameters of the decimal field determine the target
* type. In the order of NUMERIC, BIGNUMERIC, and STRING, a type is picked if it is in the
* specified list and if it supports the precision and the scale. STRING supports all precision
* and scale values. If none of the listed types supports the precision and the scale, the type
* supporting the widest range in the specified list is picked, and if a value exceeds the
* supported range when reading the data, an error will be thrown. Example: Suppose the value of
* this field is ["NUMERIC", "BIGNUMERIC"]. If (precision,scale) is: * (38,9) -> NUMERIC; * (39,9)
* -> BIGNUMERIC (NUMERIC cannot hold 30 integer digits); * (38,10) -> BIGNUMERIC (NUMERIC cannot
* hold 10 fractional digits); * (76,38) -> BIGNUMERIC; * (77,38) -> BIGNUMERIC (error if value
* exceeds supported range). This field cannot contain duplicate types. The order of the types in
* this field is ignored. For example, ["BIGNUMERIC", "NUMERIC"] is the same as ["NUMERIC",
* "BIGNUMERIC"] and NUMERIC always takes precedence over BIGNUMERIC. Defaults to ["NUMERIC",
* "STRING"] for ORC and ["NUMERIC"] for the other file formats.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> decimalTargetTypes;
/**
* Optional. Specifies how source URIs are interpreted for constructing the file set to load. By
* default source URIs are expanded against the underlying storage. Other options include
* specifying manifest files. Only applicable to object storage systems.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String fileSetSpecType;
/**
* Optional. Additional options if sourceFormat is set to GOOGLE_SHEETS.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleSheetsOptions googleSheetsOptions;
/**
* Optional. When set, configures hive partitioning support. Not all storage formats support hive
* partitioning -- requesting hive partitioning on an unsupported format will lead to an error, as
* will providing an invalid specification.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private HivePartitioningOptions hivePartitioningOptions;
/**
* Optional. Indicates if BigQuery should allow extra values that are not represented in the table
* schema. If true, the extra values are ignored. If false, records with extra columns are treated
* as bad records, and if there are too many bad records, an invalid error is returned in the job
* result. The default value is false. The sourceFormat property determines what BigQuery treats
* as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names
* Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is
* ignored. Avro: This setting is ignored. ORC: This setting is ignored. Parquet: This setting is
* ignored.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean ignoreUnknownValues;
/**
* Optional. Load option to be used together with source_format newline-delimited JSON to indicate
* that a variant of JSON is being loaded. To load newline-delimited GeoJSON, specify GEOJSON (and
* source_format must be set to NEWLINE_DELIMITED_JSON).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String jsonExtension;
/**
* Optional. Additional properties to set if sourceFormat is set to JSON.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private JsonOptions jsonOptions;
/**
* Optional. The maximum number of bad records that BigQuery can ignore when reading data. If the
* number of bad records exceeds this value, an invalid error is returned in the job result. The
* default value is 0, which requires that all records are valid. This setting is ignored for
* Google Cloud Bigtable, Google Cloud Datastore backups, Avro, ORC and Parquet formats.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer maxBadRecords;
/**
* Optional. Metadata Cache Mode for the table. Set this to enable caching of metadata from
* external data source.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String metadataCacheMode;
/**
* Optional. ObjectMetadata is used to create Object Tables. Object Tables contain a listing of
* objects (with their metadata) found at the source_uris. If ObjectMetadata is set, source_format
* should be omitted. Currently SIMPLE is the only supported Object Metadata type.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String objectMetadata;
/**
* Optional. Additional properties to set if sourceFormat is set to PARQUET.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ParquetOptions parquetOptions;
/**
* Optional. When creating an external table, the user can provide a reference file with the table
* schema. This is enabled for the following formats: AVRO, PARQUET, ORC.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String referenceFileSchemaUri;
/**
* Optional. The schema for the data. Schema is required for CSV and JSON formats if autodetect is
* not on. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, Avro, ORC and
* Parquet formats.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TableSchema schema;
/**
* [Required] The data format. For CSV files, specify "CSV". For Google sheets, specify
* "GOOGLE_SHEETS". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro files,
* specify "AVRO". For Google Cloud Datastore backups, specify "DATASTORE_BACKUP". For Apache
* Iceberg tables, specify "ICEBERG". For ORC files, specify "ORC". For Parquet files, specify
* "PARQUET". [Beta] For Google Cloud Bigtable, specify "BIGTABLE".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceFormat;
/**
* [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud
* Storage URIs: Each URI can contain one '*' wildcard character and it must come after the
* 'bucket' name. Size limits related to load jobs apply to external data sources. For Google
* Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid
* HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one
* URI can be specified. Also, the '*' wildcard character is not allowed.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sourceUris;
/**
* Optional. Format used to parse TIME values. Supports C-style and SQL-style values.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String timeFormat;
/**
* Optional. Time zone used when parsing timestamp values that do not have specific time zone
* information (e.g. 2024-04-20 12:34:56). The expected format is a IANA timezone string (e.g.
* America/Los_Angeles).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String timeZone;
/**
* Optional. Format used to parse TIMESTAMP values. Supports C-style and SQL-style values.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String timestampFormat;
/**
* Precisions (maximum number of total digits in base 10) for seconds of TIMESTAMP types that are
* allowed to the destination table for autodetection mode. Available for the formats: CSV. For
* the CSV Format, Possible values include: Not Specified, [], or [6]: timestamp(6) for all auto
* detected TIMESTAMP columns [6, 12]: timestamp(6) for all auto detected TIMESTAMP columns that
* have less than 6 digits of subseconds. timestamp(12) for all auto detected TIMESTAMP columns
* that have more than 6 digits of subseconds. [12]: timestamp(12) for all auto detected TIMESTAMP
* columns. The order of the elements in this array is ignored. Inputs that have higher precision
* than the highest target precision in this array will be truncated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.Integer> timestampTargetPrecision;
/**
* Try to detect schema and format options automatically. Any option specified explicitly will be
* honored.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAutodetect() {
return autodetect;
}
/**
* Try to detect schema and format options automatically. Any option specified explicitly will be
* honored.
* @param autodetect autodetect or {@code null} for none
*/
public ExternalDataConfiguration setAutodetect(java.lang.Boolean autodetect) {
this.autodetect = autodetect;
return this;
}
/**
* Optional. Additional properties to set if sourceFormat is set to AVRO.
* @return value or {@code null} for none
*/
public AvroOptions getAvroOptions() {
return avroOptions;
}
/**
* Optional. Additional properties to set if sourceFormat is set to AVRO.
* @param avroOptions avroOptions or {@code null} for none
*/
public ExternalDataConfiguration setAvroOptions(AvroOptions avroOptions) {
this.avroOptions = avroOptions;
return this;
}
/**
* Optional. Additional options if sourceFormat is set to BIGTABLE.
* @return value or {@code null} for none
*/
public BigtableOptions getBigtableOptions() {
return bigtableOptions;
}
/**
* Optional. Additional options if sourceFormat is set to BIGTABLE.
* @param bigtableOptions bigtableOptions or {@code null} for none
*/
public ExternalDataConfiguration setBigtableOptions(BigtableOptions bigtableOptions) {
this.bigtableOptions = bigtableOptions;
return this;
}
/**
* Optional. The compression type of the data source. Possible values include GZIP and NONE. The
* default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud
* Datastore backups, Avro, ORC and Parquet formats. An empty string is an invalid value.
* @return value or {@code null} for none
*/
public java.lang.String getCompression() {
return compression;
}
/**
* Optional. The compression type of the data source. Possible values include GZIP and NONE. The
* default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud
* Datastore backups, Avro, ORC and Parquet formats. An empty string is an invalid value.
* @param compression compression or {@code null} for none
*/
public ExternalDataConfiguration setCompression(java.lang.String compression) {
this.compression = compression;
return this;
}
/**
* Optional. The connection specifying the credentials to be used to read external storage, such
* as Azure Blob, Cloud Storage, or S3. The connection_id can have the form
* `{project_id}.{location_id};{connection_id}` or
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`.
* @return value or {@code null} for none
*/
public java.lang.String getConnectionId() {
return connectionId;
}
/**
* Optional. The connection specifying the credentials to be used to read external storage, such
* as Azure Blob, Cloud Storage, or S3. The connection_id can have the form
* `{project_id}.{location_id};{connection_id}` or
* `projects/{project_id}/locations/{location_id}/connections/{connection_id}`.
* @param connectionId connectionId or {@code null} for none
*/
public ExternalDataConfiguration setConnectionId(java.lang.String connectionId) {
this.connectionId = connectionId;
return this;
}
/**
* Optional. Additional properties to set if sourceFormat is set to CSV.
* @return value or {@code null} for none
*/
public CsvOptions getCsvOptions() {
return csvOptions;
}
/**
* Optional. Additional properties to set if sourceFormat is set to CSV.
* @param csvOptions csvOptions or {@code null} for none
*/
public ExternalDataConfiguration setCsvOptions(CsvOptions csvOptions) {
this.csvOptions = csvOptions;
return this;
}
/**
* Optional. Format used to parse DATE values. Supports C-style and SQL-style values.
* @return value or {@code null} for none
*/
public java.lang.String getDateFormat() {
return dateFormat;
}
/**
* Optional. Format used to parse DATE values. Supports C-style and SQL-style values.
* @param dateFormat dateFormat or {@code null} for none
*/
public ExternalDataConfiguration setDateFormat(java.lang.String dateFormat) {
this.dateFormat = dateFormat;
return this;
}
/**
* Optional. Format used to parse DATETIME values. Supports C-style and SQL-style values.
* @return value or {@code null} for none
*/
public java.lang.String getDatetimeFormat() {
return datetimeFormat;
}
/**
* Optional. Format used to parse DATETIME values. Supports C-style and SQL-style values.
* @param datetimeFormat datetimeFormat or {@code null} for none
*/
public ExternalDataConfiguration setDatetimeFormat(java.lang.String datetimeFormat) {
this.datetimeFormat = datetimeFormat;
return this;
}
/**
* Defines the list of possible SQL data types to which the source decimal values are converted.
* This list and the precision and the scale parameters of the decimal field determine the target
* type. In the order of NUMERIC, BIGNUMERIC, and STRING, a type is picked if it is in the
* specified list and if it supports the precision and the scale. STRING supports all precision
* and scale values. If none of the listed types supports the precision and the scale, the type
* supporting the widest range in the specified list is picked, and if a value exceeds the
* supported range when reading the data, an error will be thrown. Example: Suppose the value of
* this field is ["NUMERIC", "BIGNUMERIC"]. If (precision,scale) is: * (38,9) -> NUMERIC; * (39,9)
* -> BIGNUMERIC (NUMERIC cannot hold 30 integer digits); * (38,10) -> BIGNUMERIC (NUMERIC cannot
* hold 10 fractional digits); * (76,38) -> BIGNUMERIC; * (77,38) -> BIGNUMERIC (error if value
* exceeds supported range). This field cannot contain duplicate types. The order of the types in
* this field is ignored. For example, ["BIGNUMERIC", "NUMERIC"] is the same as ["NUMERIC",
* "BIGNUMERIC"] and NUMERIC always takes precedence over BIGNUMERIC. Defaults to ["NUMERIC",
* "STRING"] for ORC and ["NUMERIC"] for the other file formats.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getDecimalTargetTypes() {
return decimalTargetTypes;
}
/**
* Defines the list of possible SQL data types to which the source decimal values are converted.
* This list and the precision and the scale parameters of the decimal field determine the target
* type. In the order of NUMERIC, BIGNUMERIC, and STRING, a type is picked if it is in the
* specified list and if it supports the precision and the scale. STRING supports all precision
* and scale values. If none of the listed types supports the precision and the scale, the type
* supporting the widest range in the specified list is picked, and if a value exceeds the
* supported range when reading the data, an error will be thrown. Example: Suppose the value of
* this field is ["NUMERIC", "BIGNUMERIC"]. If (precision,scale) is: * (38,9) -> NUMERIC; * (39,9)
* -> BIGNUMERIC (NUMERIC cannot hold 30 integer digits); * (38,10) -> BIGNUMERIC (NUMERIC cannot
* hold 10 fractional digits); * (76,38) -> BIGNUMERIC; * (77,38) -> BIGNUMERIC (error if value
* exceeds supported range). This field cannot contain duplicate types. The order of the types in
* this field is ignored. For example, ["BIGNUMERIC", "NUMERIC"] is the same as ["NUMERIC",
* "BIGNUMERIC"] and NUMERIC always takes precedence over BIGNUMERIC. Defaults to ["NUMERIC",
* "STRING"] for ORC and ["NUMERIC"] for the other file formats.
* @param decimalTargetTypes decimalTargetTypes or {@code null} for none
*/
public ExternalDataConfiguration setDecimalTargetTypes(java.util.List<java.lang.String> decimalTargetTypes) {
this.decimalTargetTypes = decimalTargetTypes;
return this;
}
/**
* Optional. Specifies how source URIs are interpreted for constructing the file set to load. By
* default source URIs are expanded against the underlying storage. Other options include
* specifying manifest files. Only applicable to object storage systems.
* @return value or {@code null} for none
*/
public java.lang.String getFileSetSpecType() {
return fileSetSpecType;
}
/**
* Optional. Specifies how source URIs are interpreted for constructing the file set to load. By
* default source URIs are expanded against the underlying storage. Other options include
* specifying manifest files. Only applicable to object storage systems.
* @param fileSetSpecType fileSetSpecType or {@code null} for none
*/
public ExternalDataConfiguration setFileSetSpecType(java.lang.String fileSetSpecType) {
this.fileSetSpecType = fileSetSpecType;
return this;
}
/**
* Optional. Additional options if sourceFormat is set to GOOGLE_SHEETS.
* @return value or {@code null} for none
*/
public GoogleSheetsOptions getGoogleSheetsOptions() {
return googleSheetsOptions;
}
/**
* Optional. Additional options if sourceFormat is set to GOOGLE_SHEETS.
* @param googleSheetsOptions googleSheetsOptions or {@code null} for none
*/
public ExternalDataConfiguration setGoogleSheetsOptions(GoogleSheetsOptions googleSheetsOptions) {
this.googleSheetsOptions = googleSheetsOptions;
return this;
}
/**
* Optional. When set, configures hive partitioning support. Not all storage formats support hive
* partitioning -- requesting hive partitioning on an unsupported format will lead to an error, as
* will providing an invalid specification.
* @return value or {@code null} for none
*/
public HivePartitioningOptions getHivePartitioningOptions() {
return hivePartitioningOptions;
}
/**
* Optional. When set, configures hive partitioning support. Not all storage formats support hive
* partitioning -- requesting hive partitioning on an unsupported format will lead to an error, as
* will providing an invalid specification.
* @param hivePartitioningOptions hivePartitioningOptions or {@code null} for none
*/
public ExternalDataConfiguration setHivePartitioningOptions(HivePartitioningOptions hivePartitioningOptions) {
this.hivePartitioningOptions = hivePartitioningOptions;
return this;
}
/**
* Optional. Indicates if BigQuery should allow extra values that are not represented in the table
* schema. If true, the extra values are ignored. If false, records with extra columns are treated
* as bad records, and if there are too many bad records, an invalid error is returned in the job
* result. The default value is false. The sourceFormat property determines what BigQuery treats
* as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names
* Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is
* ignored. Avro: This setting is ignored. ORC: This setting is ignored. Parquet: This setting is
* ignored.
* @return value or {@code null} for none
*/
public java.lang.Boolean getIgnoreUnknownValues() {
return ignoreUnknownValues;
}
/**
* Optional. Indicates if BigQuery should allow extra values that are not represented in the table
* schema. If true, the extra values are ignored. If false, records with extra columns are treated
* as bad records, and if there are too many bad records, an invalid error is returned in the job
* result. The default value is false. The sourceFormat property determines what BigQuery treats
* as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names
* Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is
* ignored. Avro: This setting is ignored. ORC: This setting is ignored. Parquet: This setting is
* ignored.
* @param ignoreUnknownValues ignoreUnknownValues or {@code null} for none
*/
public ExternalDataConfiguration setIgnoreUnknownValues(java.lang.Boolean ignoreUnknownValues) {
this.ignoreUnknownValues = ignoreUnknownValues;
return this;
}
/**
* Optional. Load option to be used together with source_format newline-delimited JSON to indicate
* that a variant of JSON is being loaded. To load newline-delimited GeoJSON, specify GEOJSON (and
* source_format must be set to NEWLINE_DELIMITED_JSON).
* @return value or {@code null} for none
*/
public java.lang.String getJsonExtension() {
return jsonExtension;
}
/**
* Optional. Load option to be used together with source_format newline-delimited JSON to indicate
* that a variant of JSON is being loaded. To load newline-delimited GeoJSON, specify GEOJSON (and
* source_format must be set to NEWLINE_DELIMITED_JSON).
* @param jsonExtension jsonExtension or {@code null} for none
*/
public ExternalDataConfiguration setJsonExtension(java.lang.String jsonExtension) {
this.jsonExtension = jsonExtension;
return this;
}
/**
* Optional. Additional properties to set if sourceFormat is set to JSON.
* @return value or {@code null} for none
*/
public JsonOptions getJsonOptions() {
return jsonOptions;
}
/**
* Optional. Additional properties to set if sourceFormat is set to JSON.
* @param jsonOptions jsonOptions or {@code null} for none
*/
public ExternalDataConfiguration setJsonOptions(JsonOptions jsonOptions) {
this.jsonOptions = jsonOptions;
return this;
}
/**
* Optional. The maximum number of bad records that BigQuery can ignore when reading data. If the
* number of bad records exceeds this value, an invalid error is returned in the job result. The
* default value is 0, which requires that all records are valid. This setting is ignored for
* Google Cloud Bigtable, Google Cloud Datastore backups, Avro, ORC and Parquet formats.
* @return value or {@code null} for none
*/
public java.lang.Integer getMaxBadRecords() {
return maxBadRecords;
}
/**
* Optional. The maximum number of bad records that BigQuery can ignore when reading data. If the
* number of bad records exceeds this value, an invalid error is returned in the job result. The
* default value is 0, which requires that all records are valid. This setting is ignored for
* Google Cloud Bigtable, Google Cloud Datastore backups, Avro, ORC and Parquet formats.
* @param maxBadRecords maxBadRecords or {@code null} for none
*/
public ExternalDataConfiguration setMaxBadRecords(java.lang.Integer maxBadRecords) {
this.maxBadRecords = maxBadRecords;
return this;
}
/**
* Optional. Metadata Cache Mode for the table. Set this to enable caching of metadata from
* external data source.
* @return value or {@code null} for none
*/
public java.lang.String getMetadataCacheMode() {
return metadataCacheMode;
}
/**
* Optional. Metadata Cache Mode for the table. Set this to enable caching of metadata from
* external data source.
* @param metadataCacheMode metadataCacheMode or {@code null} for none
*/
public ExternalDataConfiguration setMetadataCacheMode(java.lang.String metadataCacheMode) {
this.metadataCacheMode = metadataCacheMode;
return this;
}
/**
* Optional. ObjectMetadata is used to create Object Tables. Object Tables contain a listing of
* objects (with their metadata) found at the source_uris. If ObjectMetadata is set, source_format
* should be omitted. Currently SIMPLE is the only supported Object Metadata type.
* @return value or {@code null} for none
*/
public java.lang.String getObjectMetadata() {
return objectMetadata;
}
/**
* Optional. ObjectMetadata is used to create Object Tables. Object Tables contain a listing of
* objects (with their metadata) found at the source_uris. If ObjectMetadata is set, source_format
* should be omitted. Currently SIMPLE is the only supported Object Metadata type.
* @param objectMetadata objectMetadata or {@code null} for none
*/
public ExternalDataConfiguration setObjectMetadata(java.lang.String objectMetadata) {
this.objectMetadata = objectMetadata;
return this;
}
/**
* Optional. Additional properties to set if sourceFormat is set to PARQUET.
* @return value or {@code null} for none
*/
public ParquetOptions getParquetOptions() {
return parquetOptions;
}
/**
* Optional. Additional properties to set if sourceFormat is set to PARQUET.
* @param parquetOptions parquetOptions or {@code null} for none
*/
public ExternalDataConfiguration setParquetOptions(ParquetOptions parquetOptions) {
this.parquetOptions = parquetOptions;
return this;
}
/**
* Optional. When creating an external table, the user can provide a reference file with the table
* schema. This is enabled for the following formats: AVRO, PARQUET, ORC.
* @return value or {@code null} for none
*/
public java.lang.String getReferenceFileSchemaUri() {
return referenceFileSchemaUri;
}
/**
* Optional. When creating an external table, the user can provide a reference file with the table
* schema. This is enabled for the following formats: AVRO, PARQUET, ORC.
* @param referenceFileSchemaUri referenceFileSchemaUri or {@code null} for none
*/
public ExternalDataConfiguration setReferenceFileSchemaUri(java.lang.String referenceFileSchemaUri) {
this.referenceFileSchemaUri = referenceFileSchemaUri;
return this;
}
/**
* Optional. The schema for the data. Schema is required for CSV and JSON formats if autodetect is
* not on. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, Avro, ORC and
* Parquet formats.
* @return value or {@code null} for none
*/
public TableSchema getSchema() {
return schema;
}
/**
* Optional. The schema for the data. Schema is required for CSV and JSON formats if autodetect is
* not on. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, Avro, ORC and
* Parquet formats.
* @param schema schema or {@code null} for none
*/
public ExternalDataConfiguration setSchema(TableSchema schema) {
this.schema = schema;
return this;
}
/**
* [Required] The data format. For CSV files, specify "CSV". For Google sheets, specify
* "GOOGLE_SHEETS". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro files,
* specify "AVRO". For Google Cloud Datastore backups, specify "DATASTORE_BACKUP". For Apache
* Iceberg tables, specify "ICEBERG". For ORC files, specify "ORC". For Parquet files, specify
* "PARQUET". [Beta] For Google Cloud Bigtable, specify "BIGTABLE".
* @return value or {@code null} for none
*/
public java.lang.String getSourceFormat() {
return sourceFormat;
}
/**
* [Required] The data format. For CSV files, specify "CSV". For Google sheets, specify
* "GOOGLE_SHEETS". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro files,
* specify "AVRO". For Google Cloud Datastore backups, specify "DATASTORE_BACKUP". For Apache
* Iceberg tables, specify "ICEBERG". For ORC files, specify "ORC". For Parquet files, specify
* "PARQUET". [Beta] For Google Cloud Bigtable, specify "BIGTABLE".
* @param sourceFormat sourceFormat or {@code null} for none
*/
public ExternalDataConfiguration setSourceFormat(java.lang.String sourceFormat) {
this.sourceFormat = sourceFormat;
return this;
}
/**
* [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud
* Storage URIs: Each URI can contain one '*' wildcard character and it must come after the
* 'bucket' name. Size limits related to load jobs apply to external data sources. For Google
* Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid
* HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one
* URI can be specified. Also, the '*' wildcard character is not allowed.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSourceUris() {
return sourceUris;
}
/**
* [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud
* Storage URIs: Each URI can contain one '*' wildcard character and it must come after the
* 'bucket' name. Size limits related to load jobs apply to external data sources. For Google
* Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid
* HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one
* URI can be specified. Also, the '*' wildcard character is not allowed.
* @param sourceUris sourceUris or {@code null} for none
*/
public ExternalDataConfiguration setSourceUris(java.util.List<java.lang.String> sourceUris) {
this.sourceUris = sourceUris;
return this;
}
/**
* Optional. Format used to parse TIME values. Supports C-style and SQL-style values.
* @return value or {@code null} for none
*/
public java.lang.String getTimeFormat() {
return timeFormat;
}
/**
* Optional. Format used to parse TIME values. Supports C-style and SQL-style values.
* @param timeFormat timeFormat or {@code null} for none
*/
public ExternalDataConfiguration setTimeFormat(java.lang.String timeFormat) {
this.timeFormat = timeFormat;
return this;
}
/**
* Optional. Time zone used when parsing timestamp values that do not have specific time zone
* information (e.g. 2024-04-20 12:34:56). The expected format is a IANA timezone string (e.g.
* America/Los_Angeles).
* @return value or {@code null} for none
*/
public java.lang.String getTimeZone() {
return timeZone;
}
/**
* Optional. Time zone used when parsing timestamp values that do not have specific time zone
* information (e.g. 2024-04-20 12:34:56). The expected format is a IANA timezone string (e.g.
* America/Los_Angeles).
* @param timeZone timeZone or {@code null} for none
*/
public ExternalDataConfiguration setTimeZone(java.lang.String timeZone) {
this.timeZone = timeZone;
return this;
}
/**
* Optional. Format used to parse TIMESTAMP values. Supports C-style and SQL-style values.
* @return value or {@code null} for none
*/
public java.lang.String getTimestampFormat() {
return timestampFormat;
}
/**
* Optional. Format used to parse TIMESTAMP values. Supports C-style and SQL-style values.
* @param timestampFormat timestampFormat or {@code null} for none
*/
public ExternalDataConfiguration setTimestampFormat(java.lang.String timestampFormat) {
this.timestampFormat = timestampFormat;
return this;
}
/**
* Precisions (maximum number of total digits in base 10) for seconds of TIMESTAMP types that are
* allowed to the destination table for autodetection mode. Available for the formats: CSV. For
* the CSV Format, Possible values include: Not Specified, [], or [6]: timestamp(6) for all auto
* detected TIMESTAMP columns [6, 12]: timestamp(6) for all auto detected TIMESTAMP columns that
* have less than 6 digits of subseconds. timestamp(12) for all auto detected TIMESTAMP columns
* that have more than 6 digits of subseconds. [12]: timestamp(12) for all auto detected TIMESTAMP
* columns. The order of the elements in this array is ignored. Inputs that have higher precision
* than the highest target precision in this array will be truncated.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.Integer> getTimestampTargetPrecision() {
return timestampTargetPrecision;
}
/**
* Precisions (maximum number of total digits in base 10) for seconds of TIMESTAMP types that are
* allowed to the destination table for autodetection mode. Available for the formats: CSV. For
* the CSV Format, Possible values include: Not Specified, [], or [6]: timestamp(6) for all auto
* detected TIMESTAMP columns [6, 12]: timestamp(6) for all auto detected TIMESTAMP columns that
* have less than 6 digits of subseconds. timestamp(12) for all auto detected TIMESTAMP columns
* that have more than 6 digits of subseconds. [12]: timestamp(12) for all auto detected TIMESTAMP
* columns. The order of the elements in this array is ignored. Inputs that have higher precision
* than the highest target precision in this array will be truncated.
* @param timestampTargetPrecision timestampTargetPrecision or {@code null} for none
*/
public ExternalDataConfiguration setTimestampTargetPrecision(java.util.List<java.lang.Integer> timestampTargetPrecision) {
this.timestampTargetPrecision = timestampTargetPrecision;
return this;
}
@Override
public ExternalDataConfiguration set(String fieldName, Object value) {
return (ExternalDataConfiguration) super.set(fieldName, value);
}
@Override
public ExternalDataConfiguration clone() {
return (ExternalDataConfiguration) super.clone();
}
}
|
googleapis/google-cloud-java | 37,398 | java-meet/proto-google-cloud-meet-v2/src/main/java/com/google/apps/meet/v2/ListParticipantSessionsRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/apps/meet/v2/service.proto
// Protobuf Java Version: 3.25.8
package com.google.apps.meet.v2;
/**
*
*
* <pre>
* Request to fetch list of participant sessions per conference record, per
* participant.
* </pre>
*
* Protobuf type {@code google.apps.meet.v2.ListParticipantSessionsRequest}
*/
public final class ListParticipantSessionsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.apps.meet.v2.ListParticipantSessionsRequest)
ListParticipantSessionsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListParticipantSessionsRequest.newBuilder() to construct.
private ListParticipantSessionsRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListParticipantSessionsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListParticipantSessionsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.meet.v2.ServiceProto
.internal_static_google_apps_meet_v2_ListParticipantSessionsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.meet.v2.ServiceProto
.internal_static_google_apps_meet_v2_ListParticipantSessionsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.meet.v2.ListParticipantSessionsRequest.class,
com.google.apps.meet.v2.ListParticipantSessionsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. Maximum number of participant sessions to return. The service
* might return fewer than this value. If unspecified, at most 100
* participants are returned. The maximum value is 250; values above 250 are
* coerced to 250. Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.apps.meet.v2.ListParticipantSessionsRequest)) {
return super.equals(obj);
}
com.google.apps.meet.v2.ListParticipantSessionsRequest other =
(com.google.apps.meet.v2.ListParticipantSessionsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.apps.meet.v2.ListParticipantSessionsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request to fetch list of participant sessions per conference record, per
* participant.
* </pre>
*
* Protobuf type {@code google.apps.meet.v2.ListParticipantSessionsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.apps.meet.v2.ListParticipantSessionsRequest)
com.google.apps.meet.v2.ListParticipantSessionsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.meet.v2.ServiceProto
.internal_static_google_apps_meet_v2_ListParticipantSessionsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.meet.v2.ServiceProto
.internal_static_google_apps_meet_v2_ListParticipantSessionsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.meet.v2.ListParticipantSessionsRequest.class,
com.google.apps.meet.v2.ListParticipantSessionsRequest.Builder.class);
}
// Construct using com.google.apps.meet.v2.ListParticipantSessionsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.apps.meet.v2.ServiceProto
.internal_static_google_apps_meet_v2_ListParticipantSessionsRequest_descriptor;
}
@java.lang.Override
public com.google.apps.meet.v2.ListParticipantSessionsRequest getDefaultInstanceForType() {
return com.google.apps.meet.v2.ListParticipantSessionsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.apps.meet.v2.ListParticipantSessionsRequest build() {
com.google.apps.meet.v2.ListParticipantSessionsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.apps.meet.v2.ListParticipantSessionsRequest buildPartial() {
com.google.apps.meet.v2.ListParticipantSessionsRequest result =
new com.google.apps.meet.v2.ListParticipantSessionsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.apps.meet.v2.ListParticipantSessionsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.apps.meet.v2.ListParticipantSessionsRequest) {
return mergeFrom((com.google.apps.meet.v2.ListParticipantSessionsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.apps.meet.v2.ListParticipantSessionsRequest other) {
if (other == com.google.apps.meet.v2.ListParticipantSessionsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format:
* `conferenceRecords/{conference_record}/participants/{participant}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. Maximum number of participant sessions to return. The service
* might return fewer than this value. If unspecified, at most 100
* participants are returned. The maximum value is 250; values above 250 are
* coerced to 250. Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. Maximum number of participant sessions to return. The service
* might return fewer than this value. If unspecified, at most 100
* participants are returned. The maximum value is 250; values above 250 are
* coerced to 250. Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Maximum number of participant sessions to return. The service
* might return fewer than this value. If unspecified, at most 100
* participants are returned. The maximum value is 250; values above 250 are
* coerced to 250. Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `start_time`
* * `end_time`
*
* For example, `end_time IS NULL` returns active participant sessions in
* the conference record.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.apps.meet.v2.ListParticipantSessionsRequest)
}
// @@protoc_insertion_point(class_scope:google.apps.meet.v2.ListParticipantSessionsRequest)
private static final com.google.apps.meet.v2.ListParticipantSessionsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.apps.meet.v2.ListParticipantSessionsRequest();
}
public static com.google.apps.meet.v2.ListParticipantSessionsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListParticipantSessionsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListParticipantSessionsRequest>() {
@java.lang.Override
public ListParticipantSessionsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListParticipantSessionsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListParticipantSessionsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.apps.meet.v2.ListParticipantSessionsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/gravitino | 37,576 | clients/cli/src/test/java/org/apache/gravitino/cli/TestTagCommands.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.gravitino.cli;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.gravitino.cli.commands.CreateTag;
import org.apache.gravitino.cli.commands.DeleteTag;
import org.apache.gravitino.cli.commands.ListAllTags;
import org.apache.gravitino.cli.commands.ListEntityTags;
import org.apache.gravitino.cli.commands.ListTagProperties;
import org.apache.gravitino.cli.commands.RemoveAllTags;
import org.apache.gravitino.cli.commands.RemoveTagProperty;
import org.apache.gravitino.cli.commands.SetTagProperty;
import org.apache.gravitino.cli.commands.TagDetails;
import org.apache.gravitino.cli.commands.TagEntity;
import org.apache.gravitino.cli.commands.UntagEntity;
import org.apache.gravitino.cli.commands.UpdateTagComment;
import org.apache.gravitino.cli.commands.UpdateTagName;
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 org.mockito.ArgumentMatcher;
class TestTagCommands {
private CommandLine mockCommandLine;
private Options mockOptions;
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@BeforeEach
void setUp() {
mockCommandLine = mock(CommandLine.class);
mockOptions = mock(Options.class);
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@AfterEach
void restoreExitFlg() {
Main.useExit = true;
}
@AfterEach
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
@Test
void testListTagsCommand() {
ListAllTags mockList = mock(ListAllTags.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(CommandEntities.METALAKE)).thenReturn("metalake_demo");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.LIST));
doReturn(mockList)
.when(commandLine)
.newListTags(any(CommandContext.class), eq("metalake_demo"));
doReturn(mockList).when(mockList).validate();
commandLine.handleCommandLine();
verify(mockList).handle();
}
@Test
void testTagDetailsCommand() {
TagDetails mockDetails = mock(TagDetails.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.getOptionValue(GravitinoOptions.TAG)).thenReturn("tagA");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.DETAILS));
doReturn(mockDetails)
.when(commandLine)
.newTagDetails(any(CommandContext.class), eq("metalake_demo"), eq("tagA"));
doReturn(mockDetails).when(mockDetails).validate();
commandLine.handleCommandLine();
verify(mockDetails).handle();
}
@Test
void testTagDetailsCommandWithMultipleTag() {
Main.useExit = false;
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.DETAILS));
assertThrows(RuntimeException.class, commandLine::handleCommandLine);
verify(commandLine, never())
.newTagDetails(any(CommandContext.class), eq("metalake_demo"), any());
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MULTIPLE_TAG_COMMAND_ERROR, output);
}
@Test
void testCreateTagCommand() {
CreateTag mockCreate = mock(CreateTag.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.hasOption(GravitinoOptions.COMMENT)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.COMMENT)).thenReturn("comment");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.CREATE));
doReturn(mockCreate)
.when(commandLine)
.newCreateTags(
any(CommandContext.class),
eq("metalake_demo"),
argThat(argument -> argument.length == 1 && argument[0].equals("tagA")),
eq("comment"));
doReturn(mockCreate).when(mockCreate).validate();
commandLine.handleCommandLine();
verify(mockCreate).handle();
}
@Test
void testCreateCommandWithoutTagOption() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
CreateTag spyCreate = spy(new CreateTag(mockContext, "metalake_demo", null, "comment"));
assertThrows(RuntimeException.class, spyCreate::validate);
verify(spyCreate, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MISSING_TAG, output);
}
@Test
void testCreateTagsCommand() {
CreateTag mockCreate = mock(CreateTag.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.hasOption(GravitinoOptions.COMMENT)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.COMMENT)).thenReturn("comment");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.CREATE));
doReturn(mockCreate)
.when(commandLine)
.newCreateTags(
any(CommandContext.class),
eq("metalake_demo"),
argThat(
argument ->
argument.length == 2
&& argument[0].equals("tagA")
&& argument[1].equals("tagB")),
eq("comment"));
doReturn(mockCreate).when(mockCreate).validate();
commandLine.handleCommandLine();
verify(mockCreate).handle();
}
@Test
void testCreateTagCommandNoComment() {
CreateTag mockCreate = mock(CreateTag.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.CREATE));
doReturn(mockCreate)
.when(commandLine)
.newCreateTags(
any(CommandContext.class),
eq("metalake_demo"),
argThat(argument -> argument.length == 1),
isNull());
doReturn(mockCreate).when(mockCreate).validate();
commandLine.handleCommandLine();
verify(mockCreate).handle();
}
@Test
void testDeleteTagCommand() {
DeleteTag mockDelete = mock(DeleteTag.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.DELETE));
doReturn(mockDelete)
.when(commandLine)
.newDeleteTag(
any(CommandContext.class),
eq("metalake_demo"),
argThat(argument -> argument.length == 1 && argument[0].equals("tagA")));
doReturn(mockDelete).when(mockDelete).validate();
commandLine.handleCommandLine();
verify(mockDelete).handle();
}
@Test
void testDeleteTagsCommand() {
DeleteTag mockDelete = mock(DeleteTag.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.DELETE));
doReturn(mockDelete)
.when(commandLine)
.newDeleteTag(
any(CommandContext.class),
eq("metalake_demo"),
argThat(
argument ->
argument.length == 2
&& argument[0].equals("tagA")
&& argument[1].equals("tagB")));
doReturn(mockDelete).when(mockDelete).validate();
commandLine.handleCommandLine();
verify(mockDelete).handle();
}
@Test
void testDeleteTagForceCommand() {
DeleteTag mockDelete = mock(DeleteTag.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.hasOption(GravitinoOptions.FORCE)).thenReturn(true);
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.DELETE));
doReturn(mockDelete)
.when(commandLine)
.newDeleteTag(
any(CommandContext.class),
eq("metalake_demo"),
argThat(argument -> argument.length == 1 && argument[0].equals("tagA")));
doReturn(mockDelete).when(mockDelete).validate();
commandLine.handleCommandLine();
verify(mockDelete).handle();
}
@Test
void testSetTagPropertyCommand() {
SetTagProperty mockSetProperty = mock(SetTagProperty.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.hasOption(GravitinoOptions.PROPERTY)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.PROPERTY)).thenReturn("property");
when(mockCommandLine.hasOption(GravitinoOptions.VALUE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.VALUE)).thenReturn("value");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.SET));
doReturn(mockSetProperty)
.when(commandLine)
.newSetTagProperty(
any(CommandContext.class),
eq("metalake_demo"),
eq("tagA"),
eq("property"),
eq("value"));
doReturn(mockSetProperty).when(mockSetProperty).validate();
commandLine.handleCommandLine();
verify(mockSetProperty).handle();
}
@Test
void testSetTagPropertyCommandWithoutPropertyAndValue() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
SetTagProperty spySetProperty =
spy(new SetTagProperty(mockContext, "metalake_demo", "tagA", null, null));
assertThrows(RuntimeException.class, spySetProperty::validate);
verify(spySetProperty, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(output, ErrorMessages.MISSING_PROPERTY_AND_VALUE);
}
@Test
void testSetTagPropertyCommandWithoutPropertyOption() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
SetTagProperty spySetProperty =
spy(new SetTagProperty(mockContext, "metalake_demo", "tagA", null, "value"));
assertThrows(RuntimeException.class, spySetProperty::validate);
verify(spySetProperty, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(output, ErrorMessages.MISSING_PROPERTY);
}
@Test
void testSetTagPropertyCommandWithoutValueOption() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
SetTagProperty spySetProperty =
spy(new SetTagProperty(mockContext, "metalake_demo", "tagA", "property", null));
assertThrows(RuntimeException.class, spySetProperty::validate);
verify(spySetProperty, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(output, ErrorMessages.MISSING_VALUE);
}
@Test
void testSetMultipleTagPropertyCommandError() {
Main.useExit = false;
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.hasOption(GravitinoOptions.PROPERTY)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.PROPERTY)).thenReturn("property");
when(mockCommandLine.hasOption(GravitinoOptions.VALUE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.VALUE)).thenReturn("value");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.SET));
Assertions.assertThrows(RuntimeException.class, commandLine::handleCommandLine);
verify(commandLine, never())
.newSetTagProperty(
any(CommandContext.class), eq("metalake_demo"), any(), eq("property"), eq("value"));
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MULTIPLE_TAG_COMMAND_ERROR, output);
}
@Test
void testRemoveTagPropertyCommand() {
RemoveTagProperty mockRemoveProperty = mock(RemoveTagProperty.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.hasOption(GravitinoOptions.PROPERTY)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.PROPERTY)).thenReturn("property");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.REMOVE));
doReturn(mockRemoveProperty)
.when(commandLine)
.newRemoveTagProperty(
any(CommandContext.class), eq("metalake_demo"), eq("tagA"), eq("property"));
doReturn(mockRemoveProperty).when(mockRemoveProperty).validate();
commandLine.handleCommandLine();
verify(mockRemoveProperty).handle();
}
@Test
void testRemoveTagPropertyCommandWithMultipleTags() {
Main.useExit = false;
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.hasOption(GravitinoOptions.PROPERTY)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.PROPERTY)).thenReturn("property");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.REMOVE));
assertThrows(RuntimeException.class, commandLine::handleCommandLine);
verify(commandLine, never())
.newRemoveTagProperty(
any(CommandContext.class), eq("metalake_demo"), any(), eq("property"));
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
Assertions.assertEquals(ErrorMessages.MULTIPLE_TAG_COMMAND_ERROR, output);
}
@Test
void testListTagPropertiesCommand() {
ListTagProperties mockListProperties = mock(ListTagProperties.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.PROPERTIES));
doReturn(mockListProperties)
.when(commandLine)
.newListTagProperties(any(CommandContext.class), eq("metalake_demo"), eq("tagA"));
doReturn(mockListProperties).when(mockListProperties).validate();
commandLine.handleCommandLine();
verify(mockListProperties).handle();
}
@Test
void testDeleteAllTagCommand() {
RemoveAllTags mockRemoveAllTags = mock(RemoveAllTags.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(false);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.FORCE)).thenReturn(true);
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.REMOVE));
doReturn(mockRemoveAllTags)
.when(commandLine)
.newRemoveAllTags(any(CommandContext.class), eq("metalake_demo"), any(FullName.class));
doReturn(mockRemoveAllTags).when(mockRemoveAllTags).validate();
commandLine.handleCommandLine();
verify(mockRemoveAllTags).handle();
}
@Test
void testUpdateTagCommentCommand() {
UpdateTagComment mockUpdateComment = mock(UpdateTagComment.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.COMMENT)).thenReturn(true);
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.getOptionValue(GravitinoOptions.COMMENT)).thenReturn("new comment");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.UPDATE));
doReturn(mockUpdateComment)
.when(commandLine)
.newUpdateTagComment(
any(CommandContext.class), eq("metalake_demo"), eq("tagA"), eq("new comment"));
doReturn(mockUpdateComment).when(mockUpdateComment).validate();
commandLine.handleCommandLine();
verify(mockUpdateComment).handle();
}
@Test
void testUpdateTagCommentCommandWithMultipleTags() {
Main.useExit = false;
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.COMMENT)).thenReturn(true);
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.getOptionValue(GravitinoOptions.COMMENT)).thenReturn("new comment");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.UPDATE));
assertThrows(RuntimeException.class, commandLine::handleCommandLine);
verify(commandLine, never())
.newUpdateTagComment(
any(CommandContext.class), eq("metalake_demo"), any(), eq("new comment"));
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MULTIPLE_TAG_COMMAND_ERROR, output);
}
@Test
void testUpdateTagNameCommand() {
UpdateTagName mockUpdateName = mock(UpdateTagName.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
when(mockCommandLine.hasOption(GravitinoOptions.RENAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.RENAME)).thenReturn("tagB");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.UPDATE));
doReturn(mockUpdateName)
.when(commandLine)
.newUpdateTagName(any(CommandContext.class), eq("metalake_demo"), eq("tagA"), eq("tagB"));
doReturn(mockUpdateName).when(mockUpdateName).validate();
commandLine.handleCommandLine();
verify(mockUpdateName).handle();
}
@Test
void testUpdateTagNameCommandWithMultipleTags() {
Main.useExit = false;
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.hasOption(GravitinoOptions.RENAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.RENAME)).thenReturn("tagC");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.UPDATE));
assertThrows(RuntimeException.class, commandLine::handleCommandLine);
verify(commandLine, never())
.newUpdateTagName(any(CommandContext.class), eq("metalake_demo"), any(), eq("tagC"));
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MULTIPLE_TAG_COMMAND_ERROR, output);
}
@Test
void testListEntityTagsCommand() {
ListEntityTags mockListTags = mock(ListEntityTags.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.LIST));
doReturn(mockListTags)
.when(commandLine)
.newListEntityTags(any(CommandContext.class), eq("metalake_demo"), any(FullName.class));
doReturn(mockListTags).when(mockListTags).validate();
commandLine.handleCommandLine();
verify(mockListTags).handle();
}
@Test
void testTagEntityCommand() {
TagEntity mockTagEntity = mock(TagEntity.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG)).thenReturn(new String[] {"tagA"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.SET));
doReturn(mockTagEntity)
.when(commandLine)
.newTagEntity(
any(CommandContext.class),
eq("metalake_demo"),
any(),
argThat(
new ArgumentMatcher<String[]>() {
@Override
public boolean matches(String[] argument) {
return argument != null && argument.length > 0 && "tagA".equals(argument[0]);
}
}));
doReturn(mockTagEntity).when(mockTagEntity).validate();
commandLine.handleCommandLine();
verify(mockTagEntity).handle();
}
@Test
void testTagEntityCommandWithoutName() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
TagEntity spyTagEntity =
spy(new TagEntity(mockContext, "metalake_demo", null, new String[] {"tagA"}));
assertThrows(RuntimeException.class, spyTagEntity::validate);
verify(spyTagEntity, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MISSING_NAME, output);
}
@Test
void testTagsEntityCommand() {
TagEntity mockTagEntity = mock(TagEntity.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.SET));
doReturn(mockTagEntity)
.when(commandLine)
.newTagEntity(
any(CommandContext.class),
eq("metalake_demo"),
any(),
argThat(
new ArgumentMatcher<String[]>() {
@Override
public boolean matches(String[] argument) {
return argument != null
&& argument.length == 2
&& "tagA".equals(argument[0])
&& "tagB".equals(argument[1]);
}
}));
doReturn(mockTagEntity).when(mockTagEntity).validate();
commandLine.handleCommandLine();
verify(mockTagEntity).handle();
}
@Test
void testUntagEntityCommand() {
UntagEntity mockUntagEntity = mock(UntagEntity.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.hasOption(GravitinoOptions.PROPERTY)).thenReturn(false);
when(mockCommandLine.getOptionValue(GravitinoOptions.PROPERTY)).thenReturn(null);
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.REMOVE));
doReturn(mockUntagEntity)
.when(commandLine)
.newUntagEntity(
any(CommandContext.class),
eq("metalake_demo"),
any(),
argThat(
new ArgumentMatcher<String[]>() {
@Override
public boolean matches(String[] argument) {
return argument != null && argument.length > 0 && "tagA".equals(argument[0]);
}
}));
doReturn(mockUntagEntity).when(mockUntagEntity).validate();
commandLine.handleCommandLine();
verify(mockUntagEntity).handle();
}
@Test
void testUntagEntityCommandWithoutName() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
UntagEntity spyUntagEntity =
spy(new UntagEntity(mockContext, "metalake_demo", null, new String[] {"tagA"}));
assertThrows(RuntimeException.class, spyUntagEntity::validate);
verify(spyUntagEntity, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MISSING_NAME, output);
}
@Test
void testUntagsEntityCommand() {
UntagEntity mockUntagEntity = mock(UntagEntity.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(true);
when(mockCommandLine.getOptionValues(GravitinoOptions.TAG))
.thenReturn(new String[] {"tagA", "tagB"});
when(mockCommandLine.hasOption(GravitinoOptions.PROPERTY)).thenReturn(false);
when(mockCommandLine.getOptionValue(GravitinoOptions.PROPERTY)).thenReturn(null);
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.REMOVE));
doReturn(mockUntagEntity)
.when(commandLine)
.newUntagEntity(
any(CommandContext.class),
eq("metalake_demo"),
any(),
argThat(
new ArgumentMatcher<String[]>() {
@Override
public boolean matches(String[] argument) {
return argument != null
&& argument.length == 2
&& "tagA".equals(argument[0])
&& "tagB".equals(argument[1]);
}
}));
doReturn(mockUntagEntity).when(mockUntagEntity).validate();
commandLine.handleCommandLine();
verify(mockUntagEntity).handle();
}
@Test
void testDeleteTagCommandWithoutTagOption() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
DeleteTag spyDeleteTag = spy(new DeleteTag(mockContext, "metalake", null));
assertThrows(RuntimeException.class, spyDeleteTag::validate);
verify(spyDeleteTag, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MISSING_TAG, output);
}
@Test
void testRemoveAllTagsCommand() {
Main.useExit = false;
RemoveAllTags mockRemoveAllTags = mock(RemoveAllTags.class);
when(mockCommandLine.hasOption(GravitinoOptions.METALAKE)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.METALAKE)).thenReturn("metalake_demo");
when(mockCommandLine.hasOption(GravitinoOptions.TAG)).thenReturn(false);
when(mockCommandLine.hasOption(GravitinoOptions.NAME)).thenReturn(true);
when(mockCommandLine.getOptionValue(GravitinoOptions.NAME)).thenReturn("catalog.schema.table");
when(mockCommandLine.hasOption(GravitinoOptions.FORCE)).thenReturn(true);
GravitinoCommandLine commandLine =
spy(
new GravitinoCommandLine(
mockCommandLine, mockOptions, CommandEntities.TAG, CommandActions.REMOVE));
doReturn(mockRemoveAllTags)
.when(commandLine)
.newRemoveAllTags(
any(CommandContext.class),
eq("metalake_demo"),
argThat(
argument ->
argument != null
&& "catalog".equals(argument.getCatalogName())
&& "schema".equals(argument.getSchemaName())
&& "table".equals(argument.getTableName())));
doReturn(mockRemoveAllTags).when(mockRemoveAllTags).validate();
commandLine.handleCommandLine();
verify(mockRemoveAllTags).handle();
}
@Test
void testRemoveAllTagsCommandWithoutName() {
Main.useExit = false;
CommandContext mockContext = mock(CommandContext.class);
when(mockContext.url()).thenReturn(GravitinoCommandLine.DEFAULT_URL);
RemoveAllTags spyRemoveAllTags = spy(new RemoveAllTags(mockContext, "metalake_demo", null));
assertThrows(RuntimeException.class, spyRemoveAllTags::validate);
verify(spyRemoveAllTags, never()).handle();
String output = new String(errContent.toByteArray(), StandardCharsets.UTF_8).trim();
assertEquals(ErrorMessages.MISSING_NAME, output);
}
}
|
googleapis/google-cloud-java | 37,437 | java-translate/proto-google-cloud-translate-v3beta1/src/main/java/com/google/cloud/translate/v3beta1/ListGlossariesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/translate/v3beta1/translation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.translate.v3beta1;
/**
*
*
* <pre>
* Response message for ListGlossaries.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3beta1.ListGlossariesResponse}
*/
public final class ListGlossariesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.translation.v3beta1.ListGlossariesResponse)
ListGlossariesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListGlossariesResponse.newBuilder() to construct.
private ListGlossariesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListGlossariesResponse() {
glossaries_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListGlossariesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_ListGlossariesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_ListGlossariesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3beta1.ListGlossariesResponse.class,
com.google.cloud.translate.v3beta1.ListGlossariesResponse.Builder.class);
}
public static final int GLOSSARIES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.translate.v3beta1.Glossary> glossaries_;
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.translate.v3beta1.Glossary> getGlossariesList() {
return glossaries_;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.translate.v3beta1.GlossaryOrBuilder>
getGlossariesOrBuilderList() {
return glossaries_;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
@java.lang.Override
public int getGlossariesCount() {
return glossaries_.size();
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3beta1.Glossary getGlossaries(int index) {
return glossaries_.get(index);
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3beta1.GlossaryOrBuilder getGlossariesOrBuilder(int index) {
return glossaries_.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 a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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>
* A token to retrieve a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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 < glossaries_.size(); i++) {
output.writeMessage(1, glossaries_.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 < glossaries_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, glossaries_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.translate.v3beta1.ListGlossariesResponse)) {
return super.equals(obj);
}
com.google.cloud.translate.v3beta1.ListGlossariesResponse other =
(com.google.cloud.translate.v3beta1.ListGlossariesResponse) obj;
if (!getGlossariesList().equals(other.getGlossariesList())) 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 (getGlossariesCount() > 0) {
hash = (37 * hash) + GLOSSARIES_FIELD_NUMBER;
hash = (53 * hash) + getGlossariesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.translate.v3beta1.ListGlossariesResponse 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 ListGlossaries.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3beta1.ListGlossariesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.translation.v3beta1.ListGlossariesResponse)
com.google.cloud.translate.v3beta1.ListGlossariesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_ListGlossariesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_ListGlossariesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3beta1.ListGlossariesResponse.class,
com.google.cloud.translate.v3beta1.ListGlossariesResponse.Builder.class);
}
// Construct using com.google.cloud.translate.v3beta1.ListGlossariesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (glossariesBuilder_ == null) {
glossaries_ = java.util.Collections.emptyList();
} else {
glossaries_ = null;
glossariesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_ListGlossariesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.ListGlossariesResponse getDefaultInstanceForType() {
return com.google.cloud.translate.v3beta1.ListGlossariesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.ListGlossariesResponse build() {
com.google.cloud.translate.v3beta1.ListGlossariesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.ListGlossariesResponse buildPartial() {
com.google.cloud.translate.v3beta1.ListGlossariesResponse result =
new com.google.cloud.translate.v3beta1.ListGlossariesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.translate.v3beta1.ListGlossariesResponse result) {
if (glossariesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
glossaries_ = java.util.Collections.unmodifiableList(glossaries_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.glossaries_ = glossaries_;
} else {
result.glossaries_ = glossariesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.translate.v3beta1.ListGlossariesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.translate.v3beta1.ListGlossariesResponse) {
return mergeFrom((com.google.cloud.translate.v3beta1.ListGlossariesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.translate.v3beta1.ListGlossariesResponse other) {
if (other == com.google.cloud.translate.v3beta1.ListGlossariesResponse.getDefaultInstance())
return this;
if (glossariesBuilder_ == null) {
if (!other.glossaries_.isEmpty()) {
if (glossaries_.isEmpty()) {
glossaries_ = other.glossaries_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureGlossariesIsMutable();
glossaries_.addAll(other.glossaries_);
}
onChanged();
}
} else {
if (!other.glossaries_.isEmpty()) {
if (glossariesBuilder_.isEmpty()) {
glossariesBuilder_.dispose();
glossariesBuilder_ = null;
glossaries_ = other.glossaries_;
bitField0_ = (bitField0_ & ~0x00000001);
glossariesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getGlossariesFieldBuilder()
: null;
} else {
glossariesBuilder_.addAllMessages(other.glossaries_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.translate.v3beta1.Glossary m =
input.readMessage(
com.google.cloud.translate.v3beta1.Glossary.parser(), extensionRegistry);
if (glossariesBuilder_ == null) {
ensureGlossariesIsMutable();
glossaries_.add(m);
} else {
glossariesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.translate.v3beta1.Glossary> glossaries_ =
java.util.Collections.emptyList();
private void ensureGlossariesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
glossaries_ =
new java.util.ArrayList<com.google.cloud.translate.v3beta1.Glossary>(glossaries_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.translate.v3beta1.Glossary,
com.google.cloud.translate.v3beta1.Glossary.Builder,
com.google.cloud.translate.v3beta1.GlossaryOrBuilder>
glossariesBuilder_;
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public java.util.List<com.google.cloud.translate.v3beta1.Glossary> getGlossariesList() {
if (glossariesBuilder_ == null) {
return java.util.Collections.unmodifiableList(glossaries_);
} else {
return glossariesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public int getGlossariesCount() {
if (glossariesBuilder_ == null) {
return glossaries_.size();
} else {
return glossariesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public com.google.cloud.translate.v3beta1.Glossary getGlossaries(int index) {
if (glossariesBuilder_ == null) {
return glossaries_.get(index);
} else {
return glossariesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder setGlossaries(int index, com.google.cloud.translate.v3beta1.Glossary value) {
if (glossariesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureGlossariesIsMutable();
glossaries_.set(index, value);
onChanged();
} else {
glossariesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder setGlossaries(
int index, com.google.cloud.translate.v3beta1.Glossary.Builder builderForValue) {
if (glossariesBuilder_ == null) {
ensureGlossariesIsMutable();
glossaries_.set(index, builderForValue.build());
onChanged();
} else {
glossariesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder addGlossaries(com.google.cloud.translate.v3beta1.Glossary value) {
if (glossariesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureGlossariesIsMutable();
glossaries_.add(value);
onChanged();
} else {
glossariesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder addGlossaries(int index, com.google.cloud.translate.v3beta1.Glossary value) {
if (glossariesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureGlossariesIsMutable();
glossaries_.add(index, value);
onChanged();
} else {
glossariesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder addGlossaries(
com.google.cloud.translate.v3beta1.Glossary.Builder builderForValue) {
if (glossariesBuilder_ == null) {
ensureGlossariesIsMutable();
glossaries_.add(builderForValue.build());
onChanged();
} else {
glossariesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder addGlossaries(
int index, com.google.cloud.translate.v3beta1.Glossary.Builder builderForValue) {
if (glossariesBuilder_ == null) {
ensureGlossariesIsMutable();
glossaries_.add(index, builderForValue.build());
onChanged();
} else {
glossariesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder addAllGlossaries(
java.lang.Iterable<? extends com.google.cloud.translate.v3beta1.Glossary> values) {
if (glossariesBuilder_ == null) {
ensureGlossariesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, glossaries_);
onChanged();
} else {
glossariesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder clearGlossaries() {
if (glossariesBuilder_ == null) {
glossaries_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
glossariesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public Builder removeGlossaries(int index) {
if (glossariesBuilder_ == null) {
ensureGlossariesIsMutable();
glossaries_.remove(index);
onChanged();
} else {
glossariesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public com.google.cloud.translate.v3beta1.Glossary.Builder getGlossariesBuilder(int index) {
return getGlossariesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public com.google.cloud.translate.v3beta1.GlossaryOrBuilder getGlossariesOrBuilder(int index) {
if (glossariesBuilder_ == null) {
return glossaries_.get(index);
} else {
return glossariesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public java.util.List<? extends com.google.cloud.translate.v3beta1.GlossaryOrBuilder>
getGlossariesOrBuilderList() {
if (glossariesBuilder_ != null) {
return glossariesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(glossaries_);
}
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public com.google.cloud.translate.v3beta1.Glossary.Builder addGlossariesBuilder() {
return getGlossariesFieldBuilder()
.addBuilder(com.google.cloud.translate.v3beta1.Glossary.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public com.google.cloud.translate.v3beta1.Glossary.Builder addGlossariesBuilder(int index) {
return getGlossariesFieldBuilder()
.addBuilder(index, com.google.cloud.translate.v3beta1.Glossary.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of glossaries for a project.
* </pre>
*
* <code>repeated .google.cloud.translation.v3beta1.Glossary glossaries = 1;</code>
*/
public java.util.List<com.google.cloud.translate.v3beta1.Glossary.Builder>
getGlossariesBuilderList() {
return getGlossariesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.translate.v3beta1.Glossary,
com.google.cloud.translate.v3beta1.Glossary.Builder,
com.google.cloud.translate.v3beta1.GlossaryOrBuilder>
getGlossariesFieldBuilder() {
if (glossariesBuilder_ == null) {
glossariesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.translate.v3beta1.Glossary,
com.google.cloud.translate.v3beta1.Glossary.Builder,
com.google.cloud.translate.v3beta1.GlossaryOrBuilder>(
glossaries_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
glossaries_ = null;
}
return glossariesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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>
* A token to retrieve a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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>
* A token to retrieve a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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>
* A token to retrieve a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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>
* A token to retrieve a page of results. Pass this value in the
* [ListGlossariesRequest.page_token] field in the subsequent call to
* `ListGlossaries` method to retrieve 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.cloud.translation.v3beta1.ListGlossariesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.ListGlossariesResponse)
private static final com.google.cloud.translate.v3beta1.ListGlossariesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.translate.v3beta1.ListGlossariesResponse();
}
public static com.google.cloud.translate.v3beta1.ListGlossariesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListGlossariesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListGlossariesResponse>() {
@java.lang.Override
public ListGlossariesResponse 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<ListGlossariesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListGlossariesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.ListGlossariesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/plc4x | 37,926 | plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/protocol/KnxNetIpProtocolLogic.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
*
* 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 org.apache.plc4x.java.knxnetip.protocol;
import io.netty.channel.socket.DatagramChannel;
import org.apache.commons.codec.binary.Hex;
import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
import org.apache.plc4x.java.api.messages.*;
import org.apache.plc4x.java.api.model.PlcConsumerRegistration;
import org.apache.plc4x.java.api.model.PlcSubscriptionHandle;
import org.apache.plc4x.java.api.types.PlcResponseCode;
import org.apache.plc4x.java.api.value.PlcValue;
import org.apache.plc4x.java.knxnetip.context.KnxNetIpDriverContext;
import org.apache.plc4x.java.knxnetip.ets.model.EtsModel;
import org.apache.plc4x.java.knxnetip.ets.model.GroupAddress;
import org.apache.plc4x.java.knxnetip.model.KnxNetIpSubscriptionHandle;
import org.apache.plc4x.java.knxnetip.readwrite.*;
import org.apache.plc4x.java.knxnetip.tag.KnxNetIpTag;
import org.apache.plc4x.java.knxnetip.tag.KnxNetIpTagHandler;
import org.apache.plc4x.java.spi.ConversationContext;
import org.apache.plc4x.java.spi.Plc4xProtocolBase;
import org.apache.plc4x.java.spi.connection.PlcTagHandler;
import org.apache.plc4x.java.spi.context.DriverContext;
import org.apache.plc4x.java.spi.generation.*;
import org.apache.plc4x.java.spi.messages.*;
import org.apache.plc4x.java.spi.messages.utils.DefaultPlcResponseItem;
import org.apache.plc4x.java.spi.messages.utils.PlcResponseItem;
import org.apache.plc4x.java.spi.model.DefaultPlcConsumerRegistration;
import org.apache.plc4x.java.spi.model.DefaultPlcSubscriptionTag;
import org.apache.plc4x.java.spi.transaction.RequestTransactionManager;
import org.apache.plc4x.java.spi.values.PlcSTRING;
import org.apache.plc4x.java.spi.values.PlcStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
public class KnxNetIpProtocolLogic extends Plc4xProtocolBase<KnxNetIpMessage> implements PlcSubscriber {
private static final Logger LOGGER = LoggerFactory.getLogger(KnxNetIpProtocolLogic.class);
public static final Duration REQUEST_TIMEOUT = Duration.ofMillis(10000);
private KnxNetIpDriverContext knxNetIpDriverContext;
private Timer connectionStateTimer;
private static final AtomicInteger sequenceCounter = new AtomicInteger(0);
private RequestTransactionManager tm;
private final Map<DefaultPlcConsumerRegistration, Consumer<PlcSubscriptionEvent>> consumers = new ConcurrentHashMap<>();
@Override
public void setDriverContext(DriverContext driverContext) {
super.setDriverContext(driverContext);
this.knxNetIpDriverContext = (KnxNetIpDriverContext) driverContext;
// Initialize Transaction Manager.
// Until the number of concurrent requests is successfully negotiated we set it to a
// maximum of only one request being able to be sent at a time. During the login process
// No concurrent requests can be sent anyway. It will be updated when receiving the
// S7ParameterSetupCommunication response.
this.tm = new RequestTransactionManager(1);
}
@Override
public PlcTagHandler getTagHandler() {
return new KnxNetIpTagHandler();
}
@Override
public void close(ConversationContext<KnxNetIpMessage> context) {
tm.shutdown();
}
@Override
public void onConnect(ConversationContext<KnxNetIpMessage> context) {
// Only the UDP transport supports login.
if (!context.isPassive()) {
LOGGER.info("KNX Driver running in ACTIVE mode.");
knxNetIpDriverContext.setPassiveMode(false);
DatagramChannel channel = (DatagramChannel) context.getChannel();
final InetSocketAddress localSocketAddress = channel.localAddress();
knxNetIpDriverContext.setLocalIPAddress(new IPAddress(localSocketAddress.getAddress().getAddress()));
knxNetIpDriverContext.setLocalPort(localSocketAddress.getPort());
// First send out a search request
// REMARK: This might be optional ... usually we would send a search request to ip 224.0.23.12
// Any KNX Gateway will respond with a search response. We're currently directly sending to the
// known gateway address, so it's sort of pointless, but at least only one device will respond.
LOGGER.info("Sending KNXnet/IP Search Request.");
SearchRequest searchRequest = new SearchRequest(
new HPAIDiscoveryEndpoint(HostProtocolCode.IPV4_UDP,
knxNetIpDriverContext.getLocalIPAddress(), knxNetIpDriverContext.getLocalPort()));
context.sendRequest(searchRequest)
.expectResponse(KnxNetIpMessage.class, Duration.ofMillis(1000))
.only(SearchResponse.class)
.handle(searchResponse -> {
LOGGER.info("Got KNXnet/IP Search Response.");
// Check if this device supports tunneling services.
final ServiceId tunnelingService = searchResponse.getDibSuppSvcFamilies().getServiceIds().stream().filter(serviceId -> serviceId instanceof KnxNetIpTunneling).findFirst().orElse(null);
// If this device supports this type of service, tell the driver, we found a suitable device.
if (tunnelingService != null) {
// Extract the required information form the search request.
knxNetIpDriverContext.setGatewayAddress(searchResponse.getDibDeviceInfo().getKnxAddress());
knxNetIpDriverContext.setGatewayName(new String(searchResponse.getDibDeviceInfo().getDeviceFriendlyName()).trim());
LOGGER.info(String.format("Found KNXnet/IP Gateway '%s' with KNX address '%d.%d.%d'",
knxNetIpDriverContext.getGatewayName(),
knxNetIpDriverContext.getGatewayAddress().getMainGroup(),
knxNetIpDriverContext.getGatewayAddress().getMiddleGroup(),
knxNetIpDriverContext.getGatewayAddress().getSubGroup()));
// Next send a connection request to the gateway.
ConnectionRequest connectionRequest = new ConnectionRequest(
new HPAIDiscoveryEndpoint(HostProtocolCode.IPV4_UDP,
knxNetIpDriverContext.getLocalIPAddress(), knxNetIpDriverContext.getLocalPort()),
new HPAIDataEndpoint(HostProtocolCode.IPV4_UDP,
knxNetIpDriverContext.getLocalIPAddress(), knxNetIpDriverContext.getLocalPort()),
new ConnectionRequestInformationTunnelConnection(
knxNetIpDriverContext.getTunnelConnectionType()));
LOGGER.info("Sending KNXnet/IP Connection Request.");
context.sendRequest(connectionRequest)
.expectResponse(KnxNetIpMessage.class, Duration.ofMillis(1000))
.only(ConnectionResponse.class)
.handle(connectionResponse -> {
// Remember the communication channel id.
knxNetIpDriverContext.setCommunicationChannelId(
connectionResponse.getCommunicationChannelId());
LOGGER.info(String.format("Received KNXnet/IP Connection Response (Connection Id %s)",
knxNetIpDriverContext.getCommunicationChannelId()));
// Check if everything went well.
Status status = connectionResponse.getStatus();
if (status == Status.NO_ERROR) {
final ConnectionResponseDataBlockTunnelConnection tunnelConnectionDataBlock =
(ConnectionResponseDataBlockTunnelConnection) connectionResponse.getConnectionResponseDataBlock();
// Save the KNX Address the Gateway assigned to this connection.
knxNetIpDriverContext.setClientKnxAddress(tunnelConnectionDataBlock.getKnxAddress());
final KnxAddress gatewayAddress = knxNetIpDriverContext.getGatewayAddress();
final KnxAddress clientKnxAddress = knxNetIpDriverContext.getClientKnxAddress();
LOGGER.info(String.format("Successfully connected to KNXnet/IP Gateway '%s' with KNX address '%d.%d.%d' got assigned client KNX address '%d.%d.%d'",
knxNetIpDriverContext.getGatewayName(),
gatewayAddress.getMainGroup(), gatewayAddress.getMiddleGroup(),
gatewayAddress.getSubGroup(), clientKnxAddress.getMainGroup(),
clientKnxAddress.getMiddleGroup(), clientKnxAddress.getSubGroup()));
// Send an event that connection setup is complete.
context.fireConnected();
// Start a timer to check the connection state every 60 seconds.
// This keeps the connection open if no data is transported.
// Otherwise the gateway will terminate the connection.
connectionStateTimer = new Timer();
connectionStateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
ConnectionStateRequest connectionStateRequest =
new ConnectionStateRequest(
knxNetIpDriverContext.getCommunicationChannelId(),
new HPAIControlEndpoint(HostProtocolCode.IPV4_UDP,
knxNetIpDriverContext.getLocalIPAddress(),
knxNetIpDriverContext.getLocalPort()));
context.sendRequest(connectionStateRequest)
.expectResponse(KnxNetIpMessage.class, Duration.ofMillis(1000))
.only(ConnectionStateResponse.class)
.handle(connectionStateResponse -> {
if (connectionStateResponse.getStatus() != Status.NO_ERROR) {
if (connectionStateResponse.getStatus() != null) {
LOGGER.error(String.format("Connection state problems. Got %s",
connectionStateResponse.getStatus().name()));
} else {
LOGGER.error("Connection state problems. Got no status information.");
}
// Stop the timer.
connectionStateTimer.cancel();
}
});
}
}, 60000, 60000);
} else {
// The connection request wasn't successful.
LOGGER.error(String.format(
"Not connected to KNXnet/IP Gateway '%s' with KNX address '%d.%d.%d' got status: '%s'",
knxNetIpDriverContext.getGatewayName(),
knxNetIpDriverContext.getGatewayAddress().getMainGroup(),
knxNetIpDriverContext.getGatewayAddress().getMiddleGroup(),
knxNetIpDriverContext.getGatewayAddress().getSubGroup(), status.toString()));
// TODO: Actively disconnect
}
});
} else {
// This device doesn't support tunneling ... do some error handling.
LOGGER.error("Not connected to KNCnet/IP Gateway. The device doesn't support Tunneling.");
// TODO: Actively disconnect
}
});
}
// This usually when we're running a passive mode river.
else {
LOGGER.info("KNX Driver running in PASSIVE mode.");
knxNetIpDriverContext.setPassiveMode(true);
// No login required, just confirm that we're connected.
context.fireConnected();
}
}
@Override
public void onDisconnect(ConversationContext<KnxNetIpMessage> context) {
// Cancel the timer for sending connection state requests.
connectionStateTimer.cancel();
// Just send out the disconnect request message, in most cases the remote will not respond.
// So in this case we'll just fire out the message and treat the connection as closed.
DisconnectRequest disconnectRequest = new DisconnectRequest(knxNetIpDriverContext.getCommunicationChannelId(),
new HPAIControlEndpoint(HostProtocolCode.IPV4_UDP,
knxNetIpDriverContext.getLocalIPAddress(), knxNetIpDriverContext.getLocalPort()));
context.sendToWire(disconnectRequest);
// In general, we should probably check if the disconnect was successful, but in
// the end we couldn't do much if the disconnect would fail.
final String gatewayName = knxNetIpDriverContext.getGatewayName();
final KnxAddress gatewayAddress = knxNetIpDriverContext.getGatewayAddress();
LOGGER.info("Disconnected from KNX Gateway '{}' with KNX address '{}.{}.{}'",
gatewayName, gatewayAddress.getMainGroup(), gatewayAddress.getMiddleGroup(), gatewayAddress.getSubGroup());
// Send an event that connection disconnect is complete.
context.fireDisconnected();
LOGGER.debug("Disconnected event fired from KNX protocol");
}
@Override
public CompletableFuture<PlcPingResponse> ping(PlcPingRequest pingRequest) {
CompletableFuture<PlcPingResponse> future = new CompletableFuture<>();
// We're using the connection-state-request as Ping operation as that's
// what the protocol generally uses anyway.
ConnectionStateRequest connectionStateRequest =
new ConnectionStateRequest(
knxNetIpDriverContext.getCommunicationChannelId(),
new HPAIControlEndpoint(HostProtocolCode.IPV4_UDP,
knxNetIpDriverContext.getLocalIPAddress(),
knxNetIpDriverContext.getLocalPort()));
conversationContext.sendRequest(connectionStateRequest)
.expectResponse(KnxNetIpMessage.class, Duration.ofMillis(1000))
.only(ConnectionStateResponse.class)
.handle(connectionStateResponse -> {
if (connectionStateResponse.getStatus() == Status.NO_ERROR) {
future.complete(new DefaultPlcPingResponse(pingRequest, PlcResponseCode.OK));
} else {
future.complete(new DefaultPlcPingResponse(pingRequest, PlcResponseCode.REMOTE_ERROR));
}
});
return future;
}
@Override
public CompletableFuture<PlcWriteResponse> write(PlcWriteRequest writeRequest) {
CompletableFuture<PlcWriteResponse> future = new CompletableFuture<>();
DefaultPlcWriteRequest request = (DefaultPlcWriteRequest) writeRequest;
// As the KNX driver is using the SingleTagOptimizer, each request here will have
// only one item.
final Optional<String> first = request.getTagNames().stream().findFirst();
if (first.isPresent()) {
String tagName = first.get();
final KnxNetIpTag tag = (KnxNetIpTag) request.getTag(tagName);
byte[] destinationAddress = toKnxAddressData(tag);
if (sequenceCounter.get() == Short.MAX_VALUE) {
sequenceCounter.set(0);
}
// Convert the PlcValue to byte data.
final PlcValue value = request.getPlcValue(tagName);
byte dataFirstByte = 0;
byte[] data = null;
final EtsModel etsModel = knxNetIpDriverContext.getEtsModel();
if (etsModel != null) {
final String destinationAddressString = etsModel.parseGroupAddress(destinationAddress);
final GroupAddress groupAddress = etsModel.getGroupAddresses().get(destinationAddressString);
if ((groupAddress == null) || (groupAddress.getType() == null)) {
future.completeExceptionally(new PlcRuntimeException(
"ETS5 model didn't specify group address '" + destinationAddressString +
"' or didn't define a type for it."));
return future;
}
// Use the data in the ets model to correctly check and serialize the PlcValue
try {
final WriteBufferByteBased writeBuffer = new WriteBufferByteBased(KnxDatapoint.getLengthInBytes(value, groupAddress.getType()));
KnxDatapoint.staticSerialize(writeBuffer, value, groupAddress.getType());
final byte[] serialized = writeBuffer.getBytes();
dataFirstByte = serialized[0];
data = new byte[serialized.length - 1];
System.arraycopy(serialized, 1, data, 0, serialized.length - 1);
} catch (SerializationException e) {
future.completeExceptionally(new PlcRuntimeException("Error serializing PlcValue.", e));
return future;
}
} else {
if (value.isByte()) {
if ((value.getByte() > 63) || (value.getByte() < 0)) {
future.completeExceptionally(new PlcRuntimeException(
"If no ETS5 model is provided, value of the first byte must be between 0 and 63."));
return future;
}
dataFirstByte = value.getByte();
} else if (value.isList()) {
// Check each item of the list, if it's also a byte.
List<? extends PlcValue> list = value.getList();
// TODO: This could cause an exception.
data = new byte[list.size() - 1];
boolean allValuesAreBytes = !list.isEmpty();
int numByte = 0;
for (PlcValue plcValue : list) {
if (numByte == 0) {
if (!plcValue.isByte() && (plcValue.getByte() > 63) || (plcValue.getByte() < 0)) {
allValuesAreBytes = false;
break;
}
dataFirstByte = plcValue.getByte();
} else {
if (!plcValue.isByte()) {
allValuesAreBytes = false;
break;
}
data[numByte - 1] = plcValue.getByte();
}
numByte++;
}
if (!allValuesAreBytes) {
future.completeExceptionally(new PlcRuntimeException("If no ETS5 model is provided, the only supported type for writing data is writing of single byte or list of bytes and the value of the first byte must be between 0 and 63."));
return future;
}
} else {
future.completeExceptionally(new PlcRuntimeException("If no ETS5 model is provided, the only supported type for writing data is writing of single byte or list of bytes."));
return future;
}
}
final short communicationChannelId = knxNetIpDriverContext.getCommunicationChannelId();
// Prepare the knx request message.
TunnelingRequest knxRequest = new TunnelingRequest(
new TunnelingRequestDataBlock(communicationChannelId,
(short) sequenceCounter.getAndIncrement()),
new LDataReq(
(short) 0,
new ArrayList<>(0),
new LDataExtended(false, false, CEMIPriority.LOW, false, false,
true, (byte) 6, (byte) 0, knxNetIpDriverContext.getClientKnxAddress(), destinationAddress,
new ApduDataContainer(true, (byte) 0, new ApduDataGroupValueWrite(dataFirstByte, data))
)
)
);
// Start a new request-transaction (Is ended in the response-handler)
RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
// Start a new request-transaction (Is ended in the response-handler)
transaction.submit(() -> conversationContext.sendRequest(knxRequest)
.expectResponse(KnxNetIpMessage.class, REQUEST_TIMEOUT)
.onTimeout(future::completeExceptionally)
.onError((tr, e) -> future.completeExceptionally(e))
.only(TunnelingResponse.class)
.check(tr -> tr.getTunnelingResponseDataBlock().getCommunicationChannelId() == knxRequest.getTunnelingRequestDataBlock().getCommunicationChannelId())
.check(tr -> tr.getTunnelingResponseDataBlock().getSequenceCounter() == knxRequest.getTunnelingRequestDataBlock().getSequenceCounter())
.handle(tr -> {
PlcResponseCode responseCode;
// In this case all went well.
if (tr.getTunnelingResponseDataBlock().getStatus() == Status.NO_ERROR) {
responseCode = PlcResponseCode.OK;
}
// TODO: Should probably differentiate a bit on this and not treat everything as internal error.
else {
responseCode = PlcResponseCode.INTERNAL_ERROR;
}
// Prepare the response.
PlcWriteResponse response = new DefaultPlcWriteResponse(request,
Collections.singletonMap(tagName, responseCode));
future.complete(response);
// Finish the request-transaction.
transaction.endRequest();
}));
}
return future;
}
@Override
protected void decode(ConversationContext<KnxNetIpMessage> context, KnxNetIpMessage msg) throws Exception {
// Handle a normal tunneling request, which is delivering KNX data.
if (msg instanceof TunnelingRequest) {
TunnelingRequest tunnelingRequest = (TunnelingRequest) msg;
final short curCommunicationChannelId =
tunnelingRequest.getTunnelingRequestDataBlock().getCommunicationChannelId();
// Only if the communication channel id match, do anything with the request.
// In case of a passive-mode driver we'll simply accept all communication ids.
if (knxNetIpDriverContext.isPassiveMode() ||
(curCommunicationChannelId == knxNetIpDriverContext.getCommunicationChannelId())) {
// Data packets received from a link layer tunneling connection.
if (tunnelingRequest.getCemi() instanceof LDataInd) {
LDataInd dataInd = (LDataInd) tunnelingRequest.getCemi();
final LDataFrame lDataFrame = dataInd.getDataFrame();
if (lDataFrame instanceof LDataExtended) {
LDataExtended lDataFrameDataExt = (LDataExtended) lDataFrame;
Apdu apdu = lDataFrameDataExt.getApdu();
if (apdu instanceof ApduDataContainer) {
ApduDataContainer apduDataContainer = (ApduDataContainer) apdu;
ApduData dataApdu = apduDataContainer.getDataApdu();
if (dataApdu instanceof ApduDataGroupValueWrite) {
ApduDataGroupValueWrite groupWrite = (ApduDataGroupValueWrite) dataApdu;
processCemiData(lDataFrameDataExt.getSourceAddress(), lDataFrameDataExt.getDestinationAddress(),
groupWrite.getDataFirstByte(), groupWrite.getData());
}
}
}
}
// Data packets received from a busmonitor tunneling connection.
/*else if (tunnelingRequest.getCemi() instanceof LBusmonInd) {
LBusmonInd busmonInd = (LBusmonInd) tunnelingRequest.getCemi();
if (busmonInd.getDataFrame() != null) {
final LDataFrame lDataFrame = busmonInd.getDataFrame();
if (lDataFrame instanceof LDataFrameData) {
LDataFrameData lDataFrameData = (LDataFrameData) lDataFrame;
processCemiData(lDataFrameData.getSourceAddress(), lDataFrameData.getDestinationAddress(),
lDataFrameData.getDataFirstByte(), lDataFrameData.getData());
} else if (lDataFrame instanceof LDataFrameDataExt) {
LDataFrameDataExt lDataFrameDataExt = (LDataFrameDataExt) lDataFrame;
processCemiData(lDataFrameDataExt.getSourceAddress(), lDataFrameDataExt.getDestinationAddress(),
lDataFrameDataExt.getDataFirstByte(), lDataFrameDataExt.getData());
}
}
}*/
// Confirm receipt of the request.
final short sequenceCounter = tunnelingRequest.getTunnelingRequestDataBlock().getSequenceCounter();
TunnelingResponse tunnelingResponse = new TunnelingResponse(
new TunnelingResponseDataBlock(knxNetIpDriverContext.getCommunicationChannelId(), sequenceCounter,
Status.NO_ERROR));
context.sendToWire(tunnelingResponse);
}
} else if (msg instanceof TunnelingResponse) {
// This is just handling of all the Ack messages that might come in for any read- or
// write requests. Usually this is just OK (I haven't managed to fake a message to cause
// something else than an OK)
}
}
protected void processCemiData(KnxAddress sourceAddress, byte[] destinationGroupAddress,
byte firstByte, byte[] restBytes) throws ParseException {
// The first byte is actually just 6 bit long, but we'll treat it as a full one.
// So here we create a byte array containing the first and all the following bytes.
byte[] payload = new byte[1 + restBytes.length];
payload[0] = firstByte;
System.arraycopy(restBytes, 0, payload, 1, restBytes.length);
// Decode the group address depending on the project settings.
ReadBuffer addressBuffer = new ReadBufferByteBased(destinationGroupAddress);
final KnxGroupAddress knxGroupAddress =
KnxGroupAddress.staticParse(addressBuffer, knxNetIpDriverContext.getGroupAddressType());
final String destinationAddress = toString(knxGroupAddress);
// If there is an ETS model provided, continue decoding the payload.
if (knxNetIpDriverContext.getEtsModel() != null) {
final EtsModel etsModel = knxNetIpDriverContext.getEtsModel();
final GroupAddress groupAddress = etsModel.getGroupAddresses().get(destinationAddress);
final String areaName = etsModel.getTopologyName(destinationAddress.substring(
0, destinationAddress.indexOf('/')));
final String lineName = etsModel.getTopologyName(destinationAddress.substring(
0, destinationAddress.indexOf('/', destinationAddress.indexOf('/') + 1)));
if ((groupAddress != null) && (groupAddress.getType() != null)) {
LOGGER.trace(String.format("Message from: '%s' to: '%s'",
toString(sourceAddress), destinationAddress));
// Parse the payload depending on the type of the group-address.
ReadBuffer rawDataReader = new ReadBufferByteBased(payload);
final PlcValue value = KnxDatapoint.staticParse(rawDataReader,
groupAddress.getType());
LOGGER.trace("Incoming message {} with payload {} decoded to {}",
groupAddress, Hex.encodeHexString(payload), (value != null) ? value.toString() : "");
// Assemble the plc4x return data-structure.
Map<String, PlcValue> dataPointMap = new HashMap<>();
dataPointMap.put("sourceAddress", new PlcSTRING(toString(sourceAddress)));
dataPointMap.put("targetAddress", new PlcSTRING(groupAddress.getGroupAddress()));
if (groupAddress.getFunction() != null) {
dataPointMap.put("location", new PlcSTRING(groupAddress.getFunction().getSpaceName()));
dataPointMap.put("function", new PlcSTRING(groupAddress.getFunction().getName()));
} else {
dataPointMap.put("location", null);
dataPointMap.put("function", null);
}
if (areaName != null) {
dataPointMap.put("area", new PlcSTRING(areaName));
}
if (lineName != null) {
dataPointMap.put("line", new PlcSTRING(lineName));
}
dataPointMap.put("description", new PlcSTRING(groupAddress.getName()));
dataPointMap.put("unitOfMeasurement", new PlcSTRING(groupAddress.getType().getName()));
dataPointMap.put("value", value);
final PlcStruct dataPoint = new PlcStruct(dataPointMap);
// Send the data-structure.
publishEvent(groupAddress, dataPoint);
} else {
LOGGER.warn(
String.format("Message from: '%s' to unknown group address: '%s'%n payload: '%s'",
toString(sourceAddress), destinationAddress, Hex.encodeHexString(payload)));
}
}
// Else just output the raw payload.
else {
LOGGER.info(String.format("Raw Message: '%s' to: '%s'%n payload: '%s'",
KnxNetIpProtocolLogic.toString(sourceAddress), destinationAddress,
Hex.encodeHexString(payload))
);
}
}
@Override
public CompletableFuture<PlcSubscriptionResponse> subscribe(PlcSubscriptionRequest subscriptionRequest) {
Map<String, PlcResponseItem<PlcSubscriptionHandle>> values = new HashMap<>();
for (String tagName : subscriptionRequest.getTagNames()) {
final DefaultPlcSubscriptionTag tag = (DefaultPlcSubscriptionTag) subscriptionRequest.getTag(tagName);
if (!(tag.getTag() instanceof KnxNetIpTag)) {
values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.INVALID_ADDRESS, null));
} else {
values.put(tagName, new DefaultPlcResponseItem<>(PlcResponseCode.OK,
new KnxNetIpSubscriptionHandle(this, (KnxNetIpTag) tag.getTag())));
}
}
return CompletableFuture.completedFuture(
new DefaultPlcSubscriptionResponse(subscriptionRequest, values));
}
@Override
public PlcConsumerRegistration register(Consumer<PlcSubscriptionEvent> consumer, Collection<PlcSubscriptionHandle> collection) {
final DefaultPlcConsumerRegistration consumerRegistration =
new DefaultPlcConsumerRegistration(this, consumer, collection.toArray(new PlcSubscriptionHandle[0]));
consumers.put(consumerRegistration, consumer);
return consumerRegistration;
}
@Override
public void unregister(PlcConsumerRegistration plcConsumerRegistration) {
DefaultPlcConsumerRegistration consumerRegistration = (DefaultPlcConsumerRegistration) plcConsumerRegistration;
consumers.remove(consumerRegistration);
}
protected void publishEvent(GroupAddress groupAddress, PlcValue plcValue) {
// Create a subscription event from the input.
// TODO: Check this ... this is sort of not really right ...
final PlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(),
Collections.singletonMap("knxData", new DefaultPlcResponseItem<>(PlcResponseCode.OK, plcValue)));
// Try sending the subscription event to all listeners.
for (Map.Entry<DefaultPlcConsumerRegistration, Consumer<PlcSubscriptionEvent>> entry : consumers.entrySet()) {
final DefaultPlcConsumerRegistration registration = entry.getKey();
final Consumer<PlcSubscriptionEvent> consumer = entry.getValue();
// Only if the current data point matches the subscription, publish the event to it.
for (PlcSubscriptionHandle handle : registration.getSubscriptionHandles()) {
if (handle instanceof KnxNetIpSubscriptionHandle) {
KnxNetIpSubscriptionHandle subscriptionHandle = (KnxNetIpSubscriptionHandle) handle;
// Check if the subscription matches this current event.
if (subscriptionHandle.getTag().matchesGroupAddress(groupAddress)) {
consumer.accept(event);
}
}
}
}
}
protected byte[] toKnxAddressData(KnxNetIpTag tag) {
WriteBufferByteBased address = new WriteBufferByteBased(2);
try {
switch (knxNetIpDriverContext.getGroupAddressType()) {
case 3:
address.writeUnsignedShort(5, Short.parseShort(tag.getMainGroup()));
address.writeUnsignedByte(3, Byte.parseByte(tag.getMiddleGroup()));
address.writeUnsignedShort(8, Short.parseShort(tag.getSubGroup()));
break;
case 2:
address.writeUnsignedShort(5, Short.parseShort(tag.getMainGroup()));
address.writeUnsignedShort(11, Short.parseShort(tag.getSubGroup()));
break;
case 1:
address.writeUnsignedShort(16, Short.parseShort(tag.getSubGroup()));
break;
}
} catch (Exception e) {
throw new PlcRuntimeException("Error converting tag into knx address data.", e);
}
return address.getBytes();
}
protected static String toString(KnxAddress knxAddress) {
return knxAddress.getMainGroup() + "." + knxAddress.getMiddleGroup() + "." + knxAddress.getSubGroup();
}
protected static String toString(KnxGroupAddress groupAddress) {
if (groupAddress instanceof KnxGroupAddress3Level) {
KnxGroupAddress3Level level3 = (KnxGroupAddress3Level) groupAddress;
return level3.getMainGroup() + "/" + level3.getMiddleGroup() + "/" + level3.getSubGroup();
} else if (groupAddress instanceof KnxGroupAddress2Level) {
KnxGroupAddress2Level level2 = (KnxGroupAddress2Level) groupAddress;
return level2.getMainGroup() + "/" + level2.getSubGroup();
} else if (groupAddress instanceof KnxGroupAddressFreeLevel) {
KnxGroupAddressFreeLevel free = (KnxGroupAddressFreeLevel) groupAddress;
return free.getSubGroup() + "";
}
throw new PlcRuntimeException("Unsupported Group Address Type " + groupAddress.getClass().getName());
}
}
|
google/j2objc | 36,966 | jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/text/SpoofCheckerTest.java | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 2009-2015, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
package android.icu.dev.test.text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.BitSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import android.icu.dev.test.TestFmwk;
import android.icu.dev.test.TestUtil;
import android.icu.dev.test.TestUtil.JavaVendor;
import android.icu.impl.Utility;
import android.icu.lang.UScript;
import android.icu.text.Normalizer2;
import android.icu.text.SpoofChecker;
import android.icu.text.SpoofChecker.CheckResult;
import android.icu.text.SpoofChecker.RestrictionLevel;
import android.icu.text.UnicodeSet;
import android.icu.util.ULocale;
public class SpoofCheckerTest extends TestFmwk {
/*
* Identifiers for verifying that spoof checking is minimally alive and working.
*/
char[] goodLatinChars = { (char) 0x75, (char) 0x7a };
String goodLatin = new String(goodLatinChars); /* "uz", all ASCII */
/* (not confusable) */
char[] scMixedChars = { (char) 0x73, (char) 0x0441 };
String scMixed = new String(scMixedChars); /* "sc", with Cyrillic 'c' */
/* (mixed script, confusable */
String scLatin = "sc"; /* "sc", plain ascii. */
String goodCyrl = "\u0438\u043B"; // "Cyrillic small letter i and el" Plain lower case Cyrillic letters, no latin confusables
String goodGreek = "\u03c0\u03c6"; // "Greek small letter pi and phi" Plain lower case Greek letters
// Various 1 l I look-alikes
String lll_Latin_a = "lI1"; // small letter l, cap I, digit 1, all ASCII
// "\uFF29\u217C\u0196" Full-width I, Small Roman Numeral fifty, Latin Cap Letter IOTA
String lll_Latin_b = "\uff29\u217c\u0196";
String lll_Cyrl = "\u0406\u04C0\u0031"; // "\u0406\u04C01"
/* The skeleton transform for all of the 'lll' lookalikes is ascii lower case letter l. */
String lll_Skel = "lll";
String han_Hiragana = "\u3086\u308A \u77F3\u7530"; // Hiragana, space, Han
/*
* Test basic constructor.
*/
@Test
public void TestUSpoof() {
SpoofChecker sc = new SpoofChecker.Builder().build();
if (sc == null) {
errln("FAIL: null SpoofChecker");
}
}
/*
* Test build from source rules.
*/
@Test
public void TestOpenFromSourceRules() {
if (TestUtil.getJavaVendor() == JavaVendor.IBM && TestUtil.getJavaVersion() == 5) {
// Note: IBM Java 5 has a bug reading a large UTF-8 text contents
logln("Skip this test case because of the IBM Java 5 bug");
return;
}
String fileName;
Reader confusables;
try {
SpoofChecker rsc = null;
fileName = "unicode/confusables.txt";
confusables = TestUtil.getDataReader(fileName, "UTF-8");
try {
rsc = new SpoofChecker.Builder().setData(confusables).build();
} finally {
confusables.close();
}
if (rsc == null) {
errln("FAIL: null SpoofChecker");
return;
}
// Check that newly built-from-rules SpoofChecker is able to function.
checkSkeleton(rsc, "TestOpenFromSourceRules");
SpoofChecker.CheckResult result = new SpoofChecker.CheckResult();
rsc.failsChecks("Hello", result);
// The checker we just built from source rules should be equivalent to the
// default checker created from prebuilt rules baked into the ICU data.
SpoofChecker defaultChecker = new SpoofChecker.Builder().build();
assertEquals("Checker built from rules equals default", defaultChecker, rsc);
assertEquals("Checker built from rules has same hash code as default", defaultChecker.hashCode(), rsc.hashCode());
SpoofChecker optionChecker = new SpoofChecker.Builder().
setRestrictionLevel(RestrictionLevel.UNRESTRICTIVE).build();
assertFalse("", optionChecker.equals(rsc));
String stubConfusables =
"# Stub confusables data\n" +
"05AD ; 0596 ; MA # ( ֭ → ֖ ) HEBREW ACCENT DEHI → HEBREW ACCENT TIPEHA #\n";
// Verify that re-using a builder doesn't alter SpoofCheckers that were
// previously created by that builder. (The builder could modify data
// being used by the existing checker)
SpoofChecker.Builder builder = new SpoofChecker.Builder();
SpoofChecker testChecker1 = builder.build();
assertTrue("", testChecker1.equals(defaultChecker));
builder.setData(new StringReader(stubConfusables));
builder.setRestrictionLevel(RestrictionLevel.UNRESTRICTIVE);
builder.setChecks(SpoofChecker.SINGLE_SCRIPT_CONFUSABLE);
Set<ULocale>allowedLocales = new HashSet<ULocale>();
allowedLocales.add(ULocale.JAPANESE);
allowedLocales.add(ULocale.FRENCH);
builder.setAllowedLocales(allowedLocales);
SpoofChecker testChecker2 = builder.build();
SpoofChecker testChecker3 = builder.build();
assertTrue("", testChecker1.equals(defaultChecker));
assertFalse("", testChecker2.equals(defaultChecker));
assertTrue("", testChecker2.equals(testChecker3));
} catch (java.io.IOException e) {
errln(e.toString());
} catch (ParseException e) {
errln(e.toString());
}
}
/*
* Set & Get Check Flags
*/
@Test
public void TestGetSetChecks1() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.ALL_CHECKS).build();
int t;
t = sc.getChecks();
assertEquals("", SpoofChecker.ALL_CHECKS, t);
sc = new SpoofChecker.Builder().setChecks(0).build();
t = sc.getChecks();
assertEquals("", 0, t);
int checks = SpoofChecker.WHOLE_SCRIPT_CONFUSABLE | SpoofChecker.MIXED_SCRIPT_CONFUSABLE
| SpoofChecker.ANY_CASE;
sc = new SpoofChecker.Builder().setChecks(checks).build();
t = sc.getChecks();
assertEquals("", checks, t);
}
/*
* get & setAllowedChars
*/
@Test
public void TestGetSetAllowedChars() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).build();
UnicodeSet us;
UnicodeSet uset;
uset = sc.getAllowedChars();
assertTrue("", uset.isFrozen());
us = new UnicodeSet(0x41, 0x5A); /* [A-Z] */
sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).setAllowedChars(us).build();
assertEquals("", us, sc.getAllowedChars());
}
/*
* get & set Checks
*/
@Test
public void TestGetSetChecks() {
SpoofChecker sc = new SpoofChecker.Builder().build();
int checks;
int checks2;
boolean checkResults;
checks = sc.getChecks();
assertEquals("", SpoofChecker.ALL_CHECKS, checks);
checks &= ~(SpoofChecker.SINGLE_SCRIPT | SpoofChecker.MIXED_SCRIPT_CONFUSABLE);
sc = new SpoofChecker.Builder().setChecks(checks).build();
checks2 = sc.getChecks();
assertEquals("", checks, checks2);
/*
* The checks that were disabled just above are the same ones that the "scMixed" test fails. So with those tests
* gone checking that Identifier should now succeed
*/
checkResults = sc.failsChecks(scMixed);
assertFalse("", checkResults);
}
/*
* AllowedLocales
*/
@Test
public void TestAllowedLocales() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).build();
Set<ULocale> allowedLocales = null;
Set<Locale> allowedJavaLocales = null;
boolean checkResults;
/* Default allowed locales list should be empty */
allowedLocales = sc.getAllowedLocales();
assertTrue("Empty allowed locales", allowedLocales.isEmpty());
allowedJavaLocales = sc.getAllowedJavaLocales();
assertTrue("Empty allowed Java locales", allowedJavaLocales.isEmpty());
/* Allow en and ru, which should enable Latin and Cyrillic only to pass */
ULocale enloc = new ULocale("en");
ULocale ruloc = new ULocale("ru_RU");
allowedLocales = new HashSet<ULocale>();
allowedLocales.add(enloc);
allowedLocales.add(ruloc);
sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).setAllowedLocales(allowedLocales).build();
allowedLocales = sc.getAllowedLocales();
assertTrue("en in allowed locales", allowedLocales.contains(enloc));
assertTrue("ru_RU in allowed locales", allowedLocales.contains(ruloc));
Locale frlocJ = new Locale("fr");
allowedJavaLocales = new HashSet<Locale>();
allowedJavaLocales.add(frlocJ);
sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).setAllowedJavaLocales(allowedJavaLocales).build();
assertFalse("no en in allowed Java locales", allowedJavaLocales.contains(new Locale("en")));
assertTrue("fr in allowed Java locales", allowedJavaLocales.contains(frlocJ));
sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).setAllowedLocales(allowedLocales).build();
SpoofChecker.CheckResult result = new SpoofChecker.CheckResult();
checkResults = sc.failsChecks(goodLatin);
assertFalse("", checkResults);
checkResults = sc.failsChecks(goodGreek, result);
assertEquals("", SpoofChecker.CHAR_LIMIT, result.checks);
checkResults = sc.failsChecks(goodCyrl);
assertFalse("", checkResults);
/* Reset with an empty locale list, which should allow all characters to pass */
allowedLocales = new LinkedHashSet<ULocale>();
sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).setAllowedLocales(allowedLocales).build();
checkResults = sc.failsChecks(goodGreek);
assertFalse("", checkResults);
}
/*
* AllowedChars set/get the UnicodeSet of allowed characters.
*/
@Test
public void TestAllowedChars() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).build();
UnicodeSet set;
UnicodeSet tmpSet;
boolean checkResults;
/* By default, we should see no restriction; the UnicodeSet should allow all characters. */
set = sc.getAllowedChars();
tmpSet = new UnicodeSet(0, 0x10ffff);
assertEquals("", tmpSet, set);
/* Remove a character that is in our good Latin test identifier from the allowed chars set. */
tmpSet.remove(goodLatin.charAt(1));
sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CHAR_LIMIT).setAllowedChars(tmpSet).build();
/* Latin Identifier should now fail; other non-latin test cases should still be OK */
SpoofChecker.CheckResult result = new SpoofChecker.CheckResult();
checkResults = sc.failsChecks(goodLatin, result);
assertTrue("", checkResults);
assertEquals("", SpoofChecker.CHAR_LIMIT, result.checks);
}
@Test
public void TestCheck() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.ALL_CHECKS).build();
SpoofChecker.CheckResult result = new SpoofChecker.CheckResult();
boolean checkResults;
result.position = 666;
checkResults = sc.failsChecks(goodLatin, result);
assertFalse("", checkResults);
assertEquals("", 0, result.checks);
checkResults = sc.failsChecks(goodCyrl, result);
assertFalse("", checkResults);
assertEquals("", 0, result.checks);
result.position = 666;
checkResults = sc.failsChecks(scMixed, result);
assertTrue("", checkResults);
assertEquals("", SpoofChecker.RESTRICTION_LEVEL, result.checks);
result.position = 666;
checkResults = sc.failsChecks(han_Hiragana, result);
assertFalse("", checkResults);
assertEquals("", 0, result.checks);
}
@Test
public void TestAreConfusable1() {
SpoofChecker sc = new SpoofChecker.Builder().build();
int checkResults;
checkResults = sc.areConfusable(scLatin, scMixed);
assertEquals("Latin/Mixed is not MIXED_SCRIPT_CONFUSABLE", SpoofChecker.MIXED_SCRIPT_CONFUSABLE, checkResults);
checkResults = sc.areConfusable(goodGreek, scLatin);
assertEquals("Greek/Latin is not unconfusable", 0, checkResults);
checkResults = sc.areConfusable(lll_Latin_a, lll_Latin_b);
assertEquals("Latin/Latin is not SINGLE_SCRIPT_CONFUSABLE", SpoofChecker.SINGLE_SCRIPT_CONFUSABLE, checkResults);
}
@Test
public void TestGetSkeleton() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build();
String dest;
dest = sc.getSkeleton(SpoofChecker.ANY_CASE, lll_Latin_a);
assertEquals("", lll_Skel, dest);
}
/**
* IntlTestSpoof is the top level test class for the Unicode Spoof detection tests
*/
// Test the USpoofDetector API functions that require C++
// The pure C part of the API, which is most of it, is tested in cintltst
/**
* IntlTestSpoof tests for USpoofDetector
*/
@Test
public void TestSpoofAPI() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.ALL_CHECKS).build();
String s = "xyz";
SpoofChecker.CheckResult result = new SpoofChecker.CheckResult();
result.position = 666;
boolean checkResults = sc.failsChecks(s, result);
assertFalse("", checkResults);
assertEquals("", 0, result.position);
sc = new SpoofChecker.Builder().build();
String s1 = "cxs";
String s2 = Utility.unescape("\\u0441\\u0445\\u0455"); // Cyrillic "cxs"
int checkResult = sc.areConfusable(s1, s2);
assertEquals("", SpoofChecker.MIXED_SCRIPT_CONFUSABLE | SpoofChecker.WHOLE_SCRIPT_CONFUSABLE, checkResult);
sc = new SpoofChecker.Builder().build();
s = "I1l0O";
String dest = sc.getSkeleton(SpoofChecker.ANY_CASE, s);
assertEquals("", dest, "lllOO");
}
@Test
public void TestSkeleton() {
SpoofChecker sc = new SpoofChecker.Builder().build();
checkSkeleton(sc, "TestSkeleton");
}
// testSkeleton. Spot check a number of confusable skeleton substitutions from the
// Unicode data file confusables.txt
// Test cases chosen for substitutions of various lengths, and
// membership in different mapping tables.
public void checkSkeleton(SpoofChecker sc, String testName) {
int ML = 0;
int SL = SpoofChecker.SINGLE_SCRIPT_CONFUSABLE;
int MA = SpoofChecker.ANY_CASE;
int SA = SpoofChecker.SINGLE_SCRIPT_CONFUSABLE | SpoofChecker.ANY_CASE;
checkSkeleton(sc, MA, "\\u02b9identifier'", "'identifier'", testName);
checkSkeleton(sc, SL, "nochange", "nochange", testName);
checkSkeleton(sc, SA, "nochange", "nochange", testName);
checkSkeleton(sc, ML, "nochange", "nochange", testName);
checkSkeleton(sc, MA, "nochange", "nochange", testName);
checkSkeleton(sc, MA, "love", "love", testName);
checkSkeleton(sc, MA, "1ove", "love", testName); // Digit 1 to letter l
checkSkeleton(sc, ML, "OOPS", "OOPS", testName);
checkSkeleton(sc, ML, "00PS", "OOPS", testName);
checkSkeleton(sc, MA, "OOPS", "OOPS", testName);
checkSkeleton(sc, MA, "00PS", "OOPS", testName); // Digit 0 to letter O
checkSkeleton(sc, SL, "\\u059c", "\\u0301", testName);
checkSkeleton(sc, SL, "\\u2A74", "\\u003A\\u003A\\u003D", testName);
checkSkeleton(sc, SL, "\\u247E", "(ll)", testName);
checkSkeleton(sc, SL, "\\uFDFB", "\\u062C\\u0644\\u0020\\u062C\\u0644\\u006c\\u0644\\u006f", testName);
// 0C83 mapping existed in the ML and MA tables, did not exist in SL, SA (Original Unicode 7)
// mapping exists in all tables (ICU 55).
// 0C83 ; 0983 ; ML # KANNADA SIGN VISARGA to
checkSkeleton(sc, SL, "\\u0C83", "\\u0983", testName);
checkSkeleton(sc, SA, "\\u0C83", "\\u0983", testName);
checkSkeleton(sc, ML, "\\u0C83", "\\u0983", testName);
checkSkeleton(sc, MA, "\\u0C83", "\\u0983", testName);
// 0391 mappings existed only in MA and SA tables (Original Unicode 7).
// mappings exist in all tables (ICU 55)
checkSkeleton(sc, MA, "\\u0391", "A", testName);
checkSkeleton(sc, SA, "\\u0391", "A", testName);
checkSkeleton(sc, ML, "\\u0391", "A", testName);
checkSkeleton(sc, SL, "\\u0391", "A", testName);
// 13CF Mappings in all four tables, different in MA (Original Unicode 7).
// Mapping same in all tables (ICU 55)
checkSkeleton(sc, ML, "\\u13CF", "b", testName);
checkSkeleton(sc, MA, "\\u13CF", "b", testName);
checkSkeleton(sc, SL, "\\u13CF", "b", testName);
checkSkeleton(sc, SA, "\\u13CF", "b", testName);
// 0022 ; 0027 0027 ;
// all tables
checkSkeleton(sc, SL, "\"", "\\u0027\\u0027", testName);
checkSkeleton(sc, SA, "\"", "\\u0027\\u0027", testName);
checkSkeleton(sc, ML, "\"", "\\u0027\\u0027", testName);
checkSkeleton(sc, MA, "\"", "\\u0027\\u0027", testName);
}
// Internal function to run a single skeleton test case.
//
// Run a single confusable skeleton transformation test case.
//
void checkSkeleton(SpoofChecker sc, int type, String input, String expected, String testName) {
String uInput = Utility.unescape(input);
String uExpected = Utility.unescape(expected);
String actual;
actual = sc.getSkeleton(type, uInput);
Throwable t = new Throwable();
int lineNumberOfTest = t.getStackTrace()[1].getLineNumber();
assertEquals(testName + " test at line " + lineNumberOfTest + " : Expected (escaped): " + expected, uExpected, actual);
}
@Test
public void TestAreConfusable() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.CONFUSABLE).build();
String s1 = "A long string that will overflow stack buffers. A long string that will overflow stack buffers. "
+ "A long string that will overflow stack buffers. A long string that will overflow stack buffers. ";
String s2 = "A long string that wi11 overflow stack buffers. A long string that will overflow stack buffers. "
+ "A long string that wi11 overflow stack buffers. A long string that will overflow stack buffers. ";
assertEquals("", SpoofChecker.SINGLE_SCRIPT_CONFUSABLE, sc.areConfusable(s1, s2));
}
@Test
public void TestConfusableFlagVariants() {
// The spoof checker should only return those tests that the user requested. This test makes sure that
// the checker doesn't return anything the user doesn't want. This test started passing in ICU 58.
String latn = "desordenado";
String cyrl = "ԁеѕогԁепаԁо";
String mixed = "dеѕогdenаdo";
Object[][] tests = {
// string 1, string 2, checks for spoof checker, expected output
{ latn, cyrl,
SpoofChecker.CONFUSABLE,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE | SpoofChecker.WHOLE_SCRIPT_CONFUSABLE },
{ latn, cyrl,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE | SpoofChecker.WHOLE_SCRIPT_CONFUSABLE,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE | SpoofChecker.WHOLE_SCRIPT_CONFUSABLE },
{ latn, cyrl,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE },
{ latn, cyrl,
SpoofChecker.WHOLE_SCRIPT_CONFUSABLE,
SpoofChecker.WHOLE_SCRIPT_CONFUSABLE },
{ latn, cyrl,
SpoofChecker.SINGLE_SCRIPT_CONFUSABLE,
0 },
{ latn, mixed,
SpoofChecker.CONFUSABLE,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE },
{ latn, mixed,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE },
{ latn, mixed,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE | SpoofChecker.WHOLE_SCRIPT_CONFUSABLE,
SpoofChecker.MIXED_SCRIPT_CONFUSABLE },
{ latn, mixed,
SpoofChecker.WHOLE_SCRIPT_CONFUSABLE,
0 },
{ latn, latn,
SpoofChecker.CONFUSABLE,
SpoofChecker.SINGLE_SCRIPT_CONFUSABLE },
};
for (Object[] test : tests) {
String s1 = (String) test[0];
String s2 = (String) test[1];
int checks = (Integer) test[2];
int expectedResult = (Integer) test[3];
// Sanity check: expectedResult should be a subset of checks
assertEquals("Invalid test case", expectedResult & checks, expectedResult);
SpoofChecker sc = new SpoofChecker.Builder().setChecks(checks).build();
int actualResult = sc.areConfusable(s1, s2);
assertEquals("Comparing '" + s1 + "' and '" + s2 + "' with checks '" + checks + "'",
expectedResult, actualResult);
}
}
@Test
public void TestInvisible() {
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.INVISIBLE).build();
String s = Utility.unescape("abcd\\u0301ef");
SpoofChecker.CheckResult result = new SpoofChecker.CheckResult();
result.position = -42;
assertFalse("", sc.failsChecks(s, result));
assertEquals("", 0, result.checks);
assertEquals("", result.position, 0);
String s2 = Utility.unescape("abcd\\u0301\\u0302\\u0301ef");
assertTrue("", sc.failsChecks(s2, result));
assertEquals("", SpoofChecker.INVISIBLE, result.checks);
assertEquals("", 0, result.position);
// Two acute accents, one from the composed a with acute accent, \u00e1,
// and one separate.
result.position = -42;
String s3 = Utility.unescape("abcd\\u00e1\\u0301xyz");
assertTrue("", sc.failsChecks(s3, result));
assertEquals("", SpoofChecker.INVISIBLE, result.checks);
assertEquals("", 0, result.position);
}
@Test
public void TestRestrictionLevel() {
Object[][] tests = {
{"aγ♥", RestrictionLevel.UNRESTRICTIVE},
{"a", RestrictionLevel.ASCII},
{"γ", RestrictionLevel.SINGLE_SCRIPT_RESTRICTIVE},
{"aアー", RestrictionLevel.HIGHLY_RESTRICTIVE},
{"aऄ", RestrictionLevel.MODERATELY_RESTRICTIVE},
{"aγ", RestrictionLevel.MINIMALLY_RESTRICTIVE},
{"a♥", RestrictionLevel.UNRESTRICTIVE},
{"a\u303c", RestrictionLevel.HIGHLY_RESTRICTIVE},
{"aー\u303c", RestrictionLevel.HIGHLY_RESTRICTIVE},
{"aー\u303cア", RestrictionLevel.HIGHLY_RESTRICTIVE},
{ "アaー\u303c", RestrictionLevel.HIGHLY_RESTRICTIVE},
{"a1١", RestrictionLevel.MODERATELY_RESTRICTIVE},
{"a1١۱", RestrictionLevel.MODERATELY_RESTRICTIVE},
{"١ー\u303caア1१۱", RestrictionLevel.MINIMALLY_RESTRICTIVE},
{"aアー\u303c1१١۱", RestrictionLevel.MINIMALLY_RESTRICTIVE},
};
UnicodeSet allowedChars = new UnicodeSet();
// Allowed Identifier Characters. In addition to the Recommended Set,
// allow u303c, which has an interesting script extension of Hani Hira Kana.
allowedChars.addAll(SpoofChecker.RECOMMENDED).add(0x303c);
CheckResult checkResult = new CheckResult();
for (Object[] test : tests) {
String testString = (String) test[0];
RestrictionLevel expectedLevel = (RestrictionLevel) test[1];
for (RestrictionLevel levelSetInSpoofChecker : RestrictionLevel.values()) {
SpoofChecker sc = new SpoofChecker.Builder()
.setAllowedChars(allowedChars)
.setRestrictionLevel(levelSetInSpoofChecker)
.setChecks(SpoofChecker.RESTRICTION_LEVEL) // only check this
.build();
boolean actualValue = sc.failsChecks(testString, checkResult);
assertEquals("Testing restriction level for '" + testString + "'",
expectedLevel, checkResult.restrictionLevel);
// we want to fail if the text is (say) MODERATE and the testLevel is ASCII
boolean expectedFailure = expectedLevel.compareTo(levelSetInSpoofChecker) > 0;
assertEquals("Testing spoof restriction level for '" + testString + "', " + levelSetInSpoofChecker,
expectedFailure, actualValue);
// Coverage for getRestrictionLevel
assertEquals("Restriction level on built SpoofChecker should be same as on builder",
levelSetInSpoofChecker, sc.getRestrictionLevel());
}
}
}
@Test
public void TestMixedNumbers() {
Object[][] tests = {
{"1", "[0]"},
{"१", "[०]"},
{"1१", "[0०]"},
{"١۱", "[٠۰]"},
{"a♥", "[]"},
{"a\u303c", "[]"},
{"aー\u303c", "[]"},
{"aー\u303cア", "[]"},
{ "アaー\u303c", "[]"},
{"a1١", "[0٠]"},
{"a1١۱", "[0٠۰]"},
{"١ー\u303caア1१۱", "[0٠۰०]"},
{"aアー\u303c1१١۱", "[0٠۰०]"},
};
CheckResult checkResult = new CheckResult();
for (Object[] test : tests) {
String testString = (String) test[0];
UnicodeSet expected = new UnicodeSet((String)test[1]);
SpoofChecker sc = new SpoofChecker.Builder()
.setChecks(SpoofChecker.MIXED_NUMBERS) // only check this
.build();
boolean actualValue = sc.failsChecks(testString, checkResult);
assertEquals("", expected, checkResult.numerics);
assertEquals("Testing spoof mixed numbers for '" + testString + "', ", expected.size() > 1, actualValue);
}
}
@Test
public void TestBug11635() {
// The bug was an error in iterating through supplementary characters in IdentifierInfo.
// The three supplemental chars in the string are "123" from the mathematical bold digit range.
// Common script, Nd general category, and no other restrictions on allowed characters
// leaves "ABC123" as SINGLE_SCRIPT_RESTRICTIVE.
String identifier = Utility.unescape("ABC\\U0001D7CF\\U0001D7D0\\U0001D7D1");
CheckResult checkResult = new CheckResult();
SpoofChecker sc = new SpoofChecker.Builder().setChecks(SpoofChecker.RESTRICTION_LEVEL).build();
sc.failsChecks(identifier, checkResult);
assertEquals("", RestrictionLevel.SINGLE_SCRIPT_RESTRICTIVE, checkResult.restrictionLevel);
}
private String parseHex(String in) {
StringBuilder sb = new StringBuilder();
for (String oneCharAsHexString : in.split("\\s+")) {
if (oneCharAsHexString.length() > 0) {
sb.appendCodePoint(Integer.parseInt(oneCharAsHexString, 16));
}
}
return sb.toString();
}
private String escapeString(String in) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
int c = in.codePointAt(i);
if (c <= 0x7f) {
out.append((char) c);
} else if (c <= 0xffff) {
out.append(String.format("\\u%04x", c));
} else {
out.append(String.format("\\U%06x", c));
i++;
}
}
return out.toString();
}
// Verify that each item from the Unicode confusables.txt file
// transforms into the expected skeleton.
@Test
public void testConfData() {
if (TestUtil.getJavaVendor() == JavaVendor.IBM && TestUtil.getJavaVersion() == 5) {
// Note: IBM Java 5 has a bug reading a large UTF-8 text contents
logln("Skip this test case because of the IBM Java 5 bug");
return;
}
try {
// Read in the confusables.txt file. (Distributed by Unicode.org)
String fileName = "unicode/confusables.txt";
BufferedReader confusablesRdr = TestUtil.getDataReader(fileName, "UTF-8");
// Create a default spoof checker to use in this test.
SpoofChecker sc = new SpoofChecker.Builder().build();
// Parse lines from the confusables.txt file. Example Line:
// FF44 ; 0064 ; SL # ( d -> d ) FULLWIDTH ....
// Lines have three fields. The hex fields can contain more than one character,
// and each character may be more than 4 digits (for supplemntals)
// This regular expression matches lines and splits the fields into capture groups.
// Capture group 1: map from chars
// 2: map to chars
// 3: table type, SL, ML, SA or MA (deprecated)
// 4: Comment Lines Only
// 5: Error Lines Only
Matcher parseLine = Pattern.compile(
"\\ufeff?" + "(?:([0-9A-F\\s]+);([0-9A-F\\s]+);\\s*(SL|ML|SA|MA)\\s*(?:#.*?)?$)"
+ "|\\ufeff?(\\s*(?:#.*)?)"). // Comment line
matcher("");
Normalizer2 normalizer = Normalizer2.getNFDInstance();
int lineNum = 0;
String inputLine;
while ((inputLine = confusablesRdr.readLine()) != null) {
lineNum++;
parseLine.reset(inputLine);
if (!parseLine.matches()) {
errln("Syntax error in confusable data file at line " + lineNum);
errln(inputLine);
break;
}
if (parseLine.group(4) != null) {
continue; // comment line
}
String from = parseHex(parseLine.group(1));
if (!normalizer.isNormalized(from)) {
// The source character was not NFD.
// Skip this case; the first step in obtaining a skeleton is to NFD the input,
// so the mapping in this line of confusables.txt will never be applied.
continue;
}
String rawExpected = parseHex(parseLine.group(2));
String expected = normalizer.normalize(rawExpected);
String actual;
actual = sc.getSkeleton(from);
if (!actual.equals(expected)) {
errln("confusables.txt: " + lineNum + ": " + parseLine.group(0));
errln("Actual: " + escapeString(actual));
}
}
confusablesRdr.close();
} catch (IOException e) {
errln(e.toString());
}
}
@Test
public void TestCheckResultToString11447() {
CheckResult checkResult = new CheckResult();
SpoofChecker sc = new SpoofChecker.Builder()
.setChecks(SpoofChecker.MIXED_NUMBERS)
.build();
sc.failsChecks("1१", checkResult);
assertTrue("CheckResult: ", checkResult.toString().contains("MIXED_NUMBERS"));
}
@Test
public void TestDeprecated() {
// getSkeleton
SpoofChecker sc = new SpoofChecker.Builder().build();
assertEquals("Deprecated version of getSkeleton method does not work",
sc.getSkeleton(SpoofChecker.ANY_CASE, scMixed),
sc.getSkeleton(scMixed));
// setData
try {
String fileName1 = "unicode/confusables.txt";
String fileName2 = "unicode/confusablesWholeScript.txt";
Reader reader1 = TestUtil.getDataReader(fileName1, "UTF-8");
Reader reader2 = TestUtil.getDataReader(fileName2, "UTF-8");
Reader reader3 = TestUtil.getDataReader(fileName1, "UTF-8");
try {
SpoofChecker sc2 = new SpoofChecker.Builder()
.setData(reader1, reader2)
.build();
SpoofChecker sc1 = new SpoofChecker.Builder()
.setData(reader3)
.build();
assertEquals("Deprecated version of setData method does not work", sc1, sc2);
} finally {
reader1.close();
reader2.close();
reader3.close();
}
} catch(IOException e) {
fail("Could not load confusables data");
} catch (ParseException e) {
fail("Could not parse confusables data");
}
}
@Test
public void testScriptSet() {
try {
Class ScriptSet = Class.forName("android.icu.text.SpoofChecker$ScriptSet");
Constructor ctor = ScriptSet.getDeclaredConstructor();
ctor.setAccessible(true);
BitSet ss = (BitSet) ctor.newInstance();
ss.set(UScript.MYANMAR);
assertEquals("ScriptSet toString with Myanmar", "<ScriptSet { Mymr }>", ss.toString());
ss.set(UScript.BENGALI);
ss.set(UScript.LATIN);
assertEquals("ScriptSet toString with Myanmar, Latin, and Bengali", "<ScriptSet { Beng Latn Mymr }>", ss.toString());
Method and = ScriptSet.getDeclaredMethod("and", Integer.TYPE);
and.setAccessible(true);
and.invoke(ss, UScript.BENGALI);
assertEquals("ScriptSet toString with Bengali only", "<ScriptSet { Beng }>", ss.toString());
Method setAll = ScriptSet.getDeclaredMethod("setAll");
setAll.setAccessible(true);
setAll.invoke(ss);
assertEquals("ScriptSet toString with all scripts", "<ScriptSet { * }>", ss.toString());
Method isFull = ScriptSet.getDeclaredMethod("isFull");
isFull.setAccessible(true);
boolean result = (Boolean) isFull.invoke(ss);
assertEquals("ScriptSet should evaluate as full", true, result);
} catch (ClassNotFoundException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
} catch (InstantiationException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
} catch (IllegalAccessException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
} catch (SecurityException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
} catch (NoSuchMethodException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
} catch (IllegalArgumentException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
} catch (InvocationTargetException e) {
fail("Failed while testing ScriptSet: " + e.getClass() + ": " + e.getMessage());
}
}
@Test
public void testCopyConstructor() {
SpoofChecker sc1 = new SpoofChecker.Builder()
.setAllowedChars(SpoofChecker.RECOMMENDED)
.setChecks(SpoofChecker.ALL_CHECKS &~ SpoofChecker.INVISIBLE)
.build();
SpoofChecker sc2 = new SpoofChecker.Builder(sc1).build();
assertEquals("Copy constructor should produce identical instances", sc1, sc2);
}
}
|
googleapis/google-cloud-java | 37,429 | java-analytics-admin/proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/ListCustomMetricsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/analytics/admin/v1beta/analytics_admin.proto
// Protobuf Java Version: 3.25.8
package com.google.analytics.admin.v1beta;
/**
*
*
* <pre>
* Response message for ListCustomMetrics RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1beta.ListCustomMetricsResponse}
*/
public final class ListCustomMetricsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.ListCustomMetricsResponse)
ListCustomMetricsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListCustomMetricsResponse.newBuilder() to construct.
private ListCustomMetricsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListCustomMetricsResponse() {
customMetrics_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListCustomMetricsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_ListCustomMetricsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_ListCustomMetricsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1beta.ListCustomMetricsResponse.class,
com.google.analytics.admin.v1beta.ListCustomMetricsResponse.Builder.class);
}
public static final int CUSTOM_METRICS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.analytics.admin.v1beta.CustomMetric> customMetrics_;
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.analytics.admin.v1beta.CustomMetric> getCustomMetricsList() {
return customMetrics_;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.analytics.admin.v1beta.CustomMetricOrBuilder>
getCustomMetricsOrBuilderList() {
return customMetrics_;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
@java.lang.Override
public int getCustomMetricsCount() {
return customMetrics_.size();
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
@java.lang.Override
public com.google.analytics.admin.v1beta.CustomMetric getCustomMetrics(int index) {
return customMetrics_.get(index);
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
@java.lang.Override
public com.google.analytics.admin.v1beta.CustomMetricOrBuilder getCustomMetricsOrBuilder(
int index) {
return customMetrics_.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 < customMetrics_.size(); i++) {
output.writeMessage(1, customMetrics_.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 < customMetrics_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, customMetrics_.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.analytics.admin.v1beta.ListCustomMetricsResponse)) {
return super.equals(obj);
}
com.google.analytics.admin.v1beta.ListCustomMetricsResponse other =
(com.google.analytics.admin.v1beta.ListCustomMetricsResponse) obj;
if (!getCustomMetricsList().equals(other.getCustomMetricsList())) 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 (getCustomMetricsCount() > 0) {
hash = (37 * hash) + CUSTOM_METRICS_FIELD_NUMBER;
hash = (53 * hash) + getCustomMetricsList().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.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.analytics.admin.v1beta.ListCustomMetricsResponse 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 ListCustomMetrics RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1beta.ListCustomMetricsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.ListCustomMetricsResponse)
com.google.analytics.admin.v1beta.ListCustomMetricsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_ListCustomMetricsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_ListCustomMetricsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1beta.ListCustomMetricsResponse.class,
com.google.analytics.admin.v1beta.ListCustomMetricsResponse.Builder.class);
}
// Construct using com.google.analytics.admin.v1beta.ListCustomMetricsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (customMetricsBuilder_ == null) {
customMetrics_ = java.util.Collections.emptyList();
} else {
customMetrics_ = null;
customMetricsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_ListCustomMetricsResponse_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1beta.ListCustomMetricsResponse getDefaultInstanceForType() {
return com.google.analytics.admin.v1beta.ListCustomMetricsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1beta.ListCustomMetricsResponse build() {
com.google.analytics.admin.v1beta.ListCustomMetricsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1beta.ListCustomMetricsResponse buildPartial() {
com.google.analytics.admin.v1beta.ListCustomMetricsResponse result =
new com.google.analytics.admin.v1beta.ListCustomMetricsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.analytics.admin.v1beta.ListCustomMetricsResponse result) {
if (customMetricsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
customMetrics_ = java.util.Collections.unmodifiableList(customMetrics_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.customMetrics_ = customMetrics_;
} else {
result.customMetrics_ = customMetricsBuilder_.build();
}
}
private void buildPartial0(com.google.analytics.admin.v1beta.ListCustomMetricsResponse 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.analytics.admin.v1beta.ListCustomMetricsResponse) {
return mergeFrom((com.google.analytics.admin.v1beta.ListCustomMetricsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1beta.ListCustomMetricsResponse other) {
if (other == com.google.analytics.admin.v1beta.ListCustomMetricsResponse.getDefaultInstance())
return this;
if (customMetricsBuilder_ == null) {
if (!other.customMetrics_.isEmpty()) {
if (customMetrics_.isEmpty()) {
customMetrics_ = other.customMetrics_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCustomMetricsIsMutable();
customMetrics_.addAll(other.customMetrics_);
}
onChanged();
}
} else {
if (!other.customMetrics_.isEmpty()) {
if (customMetricsBuilder_.isEmpty()) {
customMetricsBuilder_.dispose();
customMetricsBuilder_ = null;
customMetrics_ = other.customMetrics_;
bitField0_ = (bitField0_ & ~0x00000001);
customMetricsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCustomMetricsFieldBuilder()
: null;
} else {
customMetricsBuilder_.addAllMessages(other.customMetrics_);
}
}
}
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.analytics.admin.v1beta.CustomMetric m =
input.readMessage(
com.google.analytics.admin.v1beta.CustomMetric.parser(), extensionRegistry);
if (customMetricsBuilder_ == null) {
ensureCustomMetricsIsMutable();
customMetrics_.add(m);
} else {
customMetricsBuilder_.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.analytics.admin.v1beta.CustomMetric> customMetrics_ =
java.util.Collections.emptyList();
private void ensureCustomMetricsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
customMetrics_ =
new java.util.ArrayList<com.google.analytics.admin.v1beta.CustomMetric>(customMetrics_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.admin.v1beta.CustomMetric,
com.google.analytics.admin.v1beta.CustomMetric.Builder,
com.google.analytics.admin.v1beta.CustomMetricOrBuilder>
customMetricsBuilder_;
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public java.util.List<com.google.analytics.admin.v1beta.CustomMetric> getCustomMetricsList() {
if (customMetricsBuilder_ == null) {
return java.util.Collections.unmodifiableList(customMetrics_);
} else {
return customMetricsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public int getCustomMetricsCount() {
if (customMetricsBuilder_ == null) {
return customMetrics_.size();
} else {
return customMetricsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public com.google.analytics.admin.v1beta.CustomMetric getCustomMetrics(int index) {
if (customMetricsBuilder_ == null) {
return customMetrics_.get(index);
} else {
return customMetricsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder setCustomMetrics(
int index, com.google.analytics.admin.v1beta.CustomMetric value) {
if (customMetricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomMetricsIsMutable();
customMetrics_.set(index, value);
onChanged();
} else {
customMetricsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder setCustomMetrics(
int index, com.google.analytics.admin.v1beta.CustomMetric.Builder builderForValue) {
if (customMetricsBuilder_ == null) {
ensureCustomMetricsIsMutable();
customMetrics_.set(index, builderForValue.build());
onChanged();
} else {
customMetricsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder addCustomMetrics(com.google.analytics.admin.v1beta.CustomMetric value) {
if (customMetricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomMetricsIsMutable();
customMetrics_.add(value);
onChanged();
} else {
customMetricsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder addCustomMetrics(
int index, com.google.analytics.admin.v1beta.CustomMetric value) {
if (customMetricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomMetricsIsMutable();
customMetrics_.add(index, value);
onChanged();
} else {
customMetricsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder addCustomMetrics(
com.google.analytics.admin.v1beta.CustomMetric.Builder builderForValue) {
if (customMetricsBuilder_ == null) {
ensureCustomMetricsIsMutable();
customMetrics_.add(builderForValue.build());
onChanged();
} else {
customMetricsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder addCustomMetrics(
int index, com.google.analytics.admin.v1beta.CustomMetric.Builder builderForValue) {
if (customMetricsBuilder_ == null) {
ensureCustomMetricsIsMutable();
customMetrics_.add(index, builderForValue.build());
onChanged();
} else {
customMetricsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder addAllCustomMetrics(
java.lang.Iterable<? extends com.google.analytics.admin.v1beta.CustomMetric> values) {
if (customMetricsBuilder_ == null) {
ensureCustomMetricsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, customMetrics_);
onChanged();
} else {
customMetricsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder clearCustomMetrics() {
if (customMetricsBuilder_ == null) {
customMetrics_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
customMetricsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public Builder removeCustomMetrics(int index) {
if (customMetricsBuilder_ == null) {
ensureCustomMetricsIsMutable();
customMetrics_.remove(index);
onChanged();
} else {
customMetricsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public com.google.analytics.admin.v1beta.CustomMetric.Builder getCustomMetricsBuilder(
int index) {
return getCustomMetricsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public com.google.analytics.admin.v1beta.CustomMetricOrBuilder getCustomMetricsOrBuilder(
int index) {
if (customMetricsBuilder_ == null) {
return customMetrics_.get(index);
} else {
return customMetricsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public java.util.List<? extends com.google.analytics.admin.v1beta.CustomMetricOrBuilder>
getCustomMetricsOrBuilderList() {
if (customMetricsBuilder_ != null) {
return customMetricsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(customMetrics_);
}
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public com.google.analytics.admin.v1beta.CustomMetric.Builder addCustomMetricsBuilder() {
return getCustomMetricsFieldBuilder()
.addBuilder(com.google.analytics.admin.v1beta.CustomMetric.getDefaultInstance());
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public com.google.analytics.admin.v1beta.CustomMetric.Builder addCustomMetricsBuilder(
int index) {
return getCustomMetricsFieldBuilder()
.addBuilder(index, com.google.analytics.admin.v1beta.CustomMetric.getDefaultInstance());
}
/**
*
*
* <pre>
* List of CustomMetrics.
* </pre>
*
* <code>repeated .google.analytics.admin.v1beta.CustomMetric custom_metrics = 1;</code>
*/
public java.util.List<com.google.analytics.admin.v1beta.CustomMetric.Builder>
getCustomMetricsBuilderList() {
return getCustomMetricsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.admin.v1beta.CustomMetric,
com.google.analytics.admin.v1beta.CustomMetric.Builder,
com.google.analytics.admin.v1beta.CustomMetricOrBuilder>
getCustomMetricsFieldBuilder() {
if (customMetricsBuilder_ == null) {
customMetricsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.admin.v1beta.CustomMetric,
com.google.analytics.admin.v1beta.CustomMetric.Builder,
com.google.analytics.admin.v1beta.CustomMetricOrBuilder>(
customMetrics_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
customMetrics_ = null;
}
return customMetricsBuilder_;
}
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.analytics.admin.v1beta.ListCustomMetricsResponse)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.ListCustomMetricsResponse)
private static final com.google.analytics.admin.v1beta.ListCustomMetricsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.ListCustomMetricsResponse();
}
public static com.google.analytics.admin.v1beta.ListCustomMetricsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListCustomMetricsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListCustomMetricsResponse>() {
@java.lang.Override
public ListCustomMetricsResponse 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<ListCustomMetricsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListCustomMetricsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1beta.ListCustomMetricsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,453 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListSearchConfigsResponse.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 ListSearchConfigs.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListSearchConfigsResponse}
*/
public final class ListSearchConfigsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListSearchConfigsResponse)
ListSearchConfigsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSearchConfigsResponse.newBuilder() to construct.
private ListSearchConfigsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSearchConfigsResponse() {
searchConfigs_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSearchConfigsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ListSearchConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ListSearchConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListSearchConfigsResponse.class,
com.google.cloud.visionai.v1.ListSearchConfigsResponse.Builder.class);
}
public static final int SEARCH_CONFIGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.visionai.v1.SearchConfig> searchConfigs_;
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.visionai.v1.SearchConfig> getSearchConfigsList() {
return searchConfigs_;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.visionai.v1.SearchConfigOrBuilder>
getSearchConfigsOrBuilderList() {
return searchConfigs_;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
@java.lang.Override
public int getSearchConfigsCount() {
return searchConfigs_.size();
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.visionai.v1.SearchConfig getSearchConfigs(int index) {
return searchConfigs_.get(index);
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.visionai.v1.SearchConfigOrBuilder getSearchConfigsOrBuilder(int index) {
return searchConfigs_.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 < searchConfigs_.size(); i++) {
output.writeMessage(1, searchConfigs_.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 < searchConfigs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, searchConfigs_.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.ListSearchConfigsResponse)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.ListSearchConfigsResponse other =
(com.google.cloud.visionai.v1.ListSearchConfigsResponse) obj;
if (!getSearchConfigsList().equals(other.getSearchConfigsList())) 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 (getSearchConfigsCount() > 0) {
hash = (37 * hash) + SEARCH_CONFIGS_FIELD_NUMBER;
hash = (53 * hash) + getSearchConfigsList().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.ListSearchConfigsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListSearchConfigsResponse 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.ListSearchConfigsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListSearchConfigsResponse 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.ListSearchConfigsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListSearchConfigsResponse 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.ListSearchConfigsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListSearchConfigsResponse 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.ListSearchConfigsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListSearchConfigsResponse 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.ListSearchConfigsResponse 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.ListSearchConfigsResponse 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.ListSearchConfigsResponse 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 ListSearchConfigs.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListSearchConfigsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListSearchConfigsResponse)
com.google.cloud.visionai.v1.ListSearchConfigsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ListSearchConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_ListSearchConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListSearchConfigsResponse.class,
com.google.cloud.visionai.v1.ListSearchConfigsResponse.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.ListSearchConfigsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (searchConfigsBuilder_ == null) {
searchConfigs_ = java.util.Collections.emptyList();
} else {
searchConfigs_ = null;
searchConfigsBuilder_.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_ListSearchConfigsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListSearchConfigsResponse getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.ListSearchConfigsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListSearchConfigsResponse build() {
com.google.cloud.visionai.v1.ListSearchConfigsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListSearchConfigsResponse buildPartial() {
com.google.cloud.visionai.v1.ListSearchConfigsResponse result =
new com.google.cloud.visionai.v1.ListSearchConfigsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.visionai.v1.ListSearchConfigsResponse result) {
if (searchConfigsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
searchConfigs_ = java.util.Collections.unmodifiableList(searchConfigs_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.searchConfigs_ = searchConfigs_;
} else {
result.searchConfigs_ = searchConfigsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.visionai.v1.ListSearchConfigsResponse 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.ListSearchConfigsResponse) {
return mergeFrom((com.google.cloud.visionai.v1.ListSearchConfigsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.ListSearchConfigsResponse other) {
if (other == com.google.cloud.visionai.v1.ListSearchConfigsResponse.getDefaultInstance())
return this;
if (searchConfigsBuilder_ == null) {
if (!other.searchConfigs_.isEmpty()) {
if (searchConfigs_.isEmpty()) {
searchConfigs_ = other.searchConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSearchConfigsIsMutable();
searchConfigs_.addAll(other.searchConfigs_);
}
onChanged();
}
} else {
if (!other.searchConfigs_.isEmpty()) {
if (searchConfigsBuilder_.isEmpty()) {
searchConfigsBuilder_.dispose();
searchConfigsBuilder_ = null;
searchConfigs_ = other.searchConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
searchConfigsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSearchConfigsFieldBuilder()
: null;
} else {
searchConfigsBuilder_.addAllMessages(other.searchConfigs_);
}
}
}
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.SearchConfig m =
input.readMessage(
com.google.cloud.visionai.v1.SearchConfig.parser(), extensionRegistry);
if (searchConfigsBuilder_ == null) {
ensureSearchConfigsIsMutable();
searchConfigs_.add(m);
} else {
searchConfigsBuilder_.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.SearchConfig> searchConfigs_ =
java.util.Collections.emptyList();
private void ensureSearchConfigsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
searchConfigs_ =
new java.util.ArrayList<com.google.cloud.visionai.v1.SearchConfig>(searchConfigs_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.visionai.v1.SearchConfig,
com.google.cloud.visionai.v1.SearchConfig.Builder,
com.google.cloud.visionai.v1.SearchConfigOrBuilder>
searchConfigsBuilder_;
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public java.util.List<com.google.cloud.visionai.v1.SearchConfig> getSearchConfigsList() {
if (searchConfigsBuilder_ == null) {
return java.util.Collections.unmodifiableList(searchConfigs_);
} else {
return searchConfigsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public int getSearchConfigsCount() {
if (searchConfigsBuilder_ == null) {
return searchConfigs_.size();
} else {
return searchConfigsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public com.google.cloud.visionai.v1.SearchConfig getSearchConfigs(int index) {
if (searchConfigsBuilder_ == null) {
return searchConfigs_.get(index);
} else {
return searchConfigsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder setSearchConfigs(int index, com.google.cloud.visionai.v1.SearchConfig value) {
if (searchConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSearchConfigsIsMutable();
searchConfigs_.set(index, value);
onChanged();
} else {
searchConfigsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder setSearchConfigs(
int index, com.google.cloud.visionai.v1.SearchConfig.Builder builderForValue) {
if (searchConfigsBuilder_ == null) {
ensureSearchConfigsIsMutable();
searchConfigs_.set(index, builderForValue.build());
onChanged();
} else {
searchConfigsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder addSearchConfigs(com.google.cloud.visionai.v1.SearchConfig value) {
if (searchConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSearchConfigsIsMutable();
searchConfigs_.add(value);
onChanged();
} else {
searchConfigsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder addSearchConfigs(int index, com.google.cloud.visionai.v1.SearchConfig value) {
if (searchConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSearchConfigsIsMutable();
searchConfigs_.add(index, value);
onChanged();
} else {
searchConfigsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder addSearchConfigs(
com.google.cloud.visionai.v1.SearchConfig.Builder builderForValue) {
if (searchConfigsBuilder_ == null) {
ensureSearchConfigsIsMutable();
searchConfigs_.add(builderForValue.build());
onChanged();
} else {
searchConfigsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder addSearchConfigs(
int index, com.google.cloud.visionai.v1.SearchConfig.Builder builderForValue) {
if (searchConfigsBuilder_ == null) {
ensureSearchConfigsIsMutable();
searchConfigs_.add(index, builderForValue.build());
onChanged();
} else {
searchConfigsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder addAllSearchConfigs(
java.lang.Iterable<? extends com.google.cloud.visionai.v1.SearchConfig> values) {
if (searchConfigsBuilder_ == null) {
ensureSearchConfigsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, searchConfigs_);
onChanged();
} else {
searchConfigsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder clearSearchConfigs() {
if (searchConfigsBuilder_ == null) {
searchConfigs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
searchConfigsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public Builder removeSearchConfigs(int index) {
if (searchConfigsBuilder_ == null) {
ensureSearchConfigsIsMutable();
searchConfigs_.remove(index);
onChanged();
} else {
searchConfigsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public com.google.cloud.visionai.v1.SearchConfig.Builder getSearchConfigsBuilder(int index) {
return getSearchConfigsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public com.google.cloud.visionai.v1.SearchConfigOrBuilder getSearchConfigsOrBuilder(int index) {
if (searchConfigsBuilder_ == null) {
return searchConfigs_.get(index);
} else {
return searchConfigsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.visionai.v1.SearchConfigOrBuilder>
getSearchConfigsOrBuilderList() {
if (searchConfigsBuilder_ != null) {
return searchConfigsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(searchConfigs_);
}
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public com.google.cloud.visionai.v1.SearchConfig.Builder addSearchConfigsBuilder() {
return getSearchConfigsFieldBuilder()
.addBuilder(com.google.cloud.visionai.v1.SearchConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public com.google.cloud.visionai.v1.SearchConfig.Builder addSearchConfigsBuilder(int index) {
return getSearchConfigsFieldBuilder()
.addBuilder(index, com.google.cloud.visionai.v1.SearchConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The search configurations from the specified corpus.
* </pre>
*
* <code>repeated .google.cloud.visionai.v1.SearchConfig search_configs = 1;</code>
*/
public java.util.List<com.google.cloud.visionai.v1.SearchConfig.Builder>
getSearchConfigsBuilderList() {
return getSearchConfigsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.visionai.v1.SearchConfig,
com.google.cloud.visionai.v1.SearchConfig.Builder,
com.google.cloud.visionai.v1.SearchConfigOrBuilder>
getSearchConfigsFieldBuilder() {
if (searchConfigsBuilder_ == null) {
searchConfigsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.visionai.v1.SearchConfig,
com.google.cloud.visionai.v1.SearchConfig.Builder,
com.google.cloud.visionai.v1.SearchConfigOrBuilder>(
searchConfigs_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
searchConfigs_ = null;
}
return searchConfigsBuilder_;
}
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.ListSearchConfigsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListSearchConfigsResponse)
private static final com.google.cloud.visionai.v1.ListSearchConfigsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListSearchConfigsResponse();
}
public static com.google.cloud.visionai.v1.ListSearchConfigsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSearchConfigsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSearchConfigsResponse>() {
@java.lang.Override
public ListSearchConfigsResponse 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<ListSearchConfigsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSearchConfigsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListSearchConfigsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/commons-io | 37,685 | src/test/java/org/apache/commons/io/input/BoundedInputStreamTest.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
*
* 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 org.apache.commons.io.input;
import static org.apache.commons.io.IOUtils.EOF;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.test.CustomIOException;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests for {@link BoundedInputStream}.
*/
class BoundedInputStreamTest {
static Stream<Arguments> testAvailableAfterClose() throws IOException {
// Case 1: behaves like ByteArrayInputStream — close() is a no-op, available() still returns a value (e.g., 42).
final InputStream noOpClose = mock(InputStream.class);
when(noOpClose.available()).thenReturn(42, 42);
// Case 2: returns 0 after close (Commons memory-backed streams that ignore close but report 0 when exhausted).
final InputStream returnsZeroAfterClose = mock(InputStream.class);
when(returnsZeroAfterClose.available()).thenReturn(42, 0);
// Case 3: throws IOException after close (e.g., FileInputStream-like behavior).
final InputStream throwsAfterClose = mock(InputStream.class);
when(throwsAfterClose.available()).thenReturn(42).thenThrow(new IOException("Stream closed"));
return Stream.of(
Arguments.of("underlying stream still returns 42 after close", noOpClose, 42),
Arguments.of("underlying stream returns 0 after close", returnsZeroAfterClose, 42),
Arguments.of("underlying stream throws IOException after close", throwsAfterClose, 42));
}
static Stream<Arguments> testAvailableUpperLimit() {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
return Stream.of(
// Limited by maxCount
Arguments.of(new ByteArrayInputStream(helloWorld), helloWorld.length - 1, helloWorld.length - 1, 0),
// Limited by data length
Arguments.of(new ByteArrayInputStream(helloWorld), helloWorld.length + 1, helloWorld.length, 0),
// Limited by Integer.MAX_VALUE
Arguments.of(
new NullInputStream(Long.MAX_VALUE), Long.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE));
}
static Stream<Arguments> testReadAfterClose() throws IOException {
// Case 1: no-op close (ByteArrayInputStream-like): read() still returns a value after close
final InputStream noOpClose = mock(InputStream.class);
when(noOpClose.read()).thenReturn(42);
// Case 2: returns EOF (-1) after close
final InputStream returnsEofAfterClose = mock(InputStream.class);
when(returnsEofAfterClose.read()).thenReturn(IOUtils.EOF);
// Case 3: throws IOException after close (FileInputStream-like)
final InputStream throwsAfterClose = mock(InputStream.class);
final IOException closed = new IOException("Stream closed");
when(throwsAfterClose.read()).thenThrow(closed);
return Stream.of(
Arguments.of("underlying stream still reads data after close", noOpClose, 42),
Arguments.of("underlying stream returns EOF after close", returnsEofAfterClose, IOUtils.EOF),
Arguments.of("underlying stream throws IOException after close", throwsAfterClose, closed));
}
static Stream<Arguments> testRemaining() {
return Stream.of(
// Unbounded: any negative maxCount is treated as "no limit".
Arguments.of("unbounded (EOF constant)", IOUtils.EOF, Long.MAX_VALUE),
Arguments.of("unbounded (arbitrary negative)", Long.MIN_VALUE, Long.MAX_VALUE),
// Bounded: remaining equals the configured limit, regardless of underlying data size.
Arguments.of("bounded (zero)", 0L, 0L),
Arguments.of("bounded (small)", 1024L, 1024L),
Arguments.of("bounded (Integer.MAX_VALUE)", Integer.MAX_VALUE, (long) Integer.MAX_VALUE),
// Bounded but extremely large: still not 'unbounded'.
Arguments.of("bounded (Long.MAX_VALUE)", Long.MAX_VALUE, Long.MAX_VALUE));
}
private void compare(final String message, final byte[] expected, final byte[] actual) {
assertEquals(expected.length, actual.length, () -> message + " (array length equals check)");
final MutableInt mi = new MutableInt();
for (int i = 0; i < expected.length; i++) {
mi.setValue(i);
assertEquals(expected[i], actual[i], () -> message + " byte[" + mi + "]");
}
}
@Test
void testAfterReadConsumer() throws Exception {
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
final AtomicBoolean boolRef = new AtomicBoolean();
// @formatter:off
try (InputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(hello))
.setMaxCount(hello.length)
.setAfterRead(i -> boolRef.set(true))
.get()) {
IOUtils.consume(bounded);
}
// @formatter:on
assertTrue(boolRef.get());
// Throwing
final String message = "test exception message";
// @formatter:off
try (InputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(hello))
.setMaxCount(hello.length)
.setAfterRead(i -> {
throw new CustomIOException(message);
})
.get()) {
assertEquals(message, assertThrowsExactly(CustomIOException.class, () -> IOUtils.consume(bounded)).getMessage());
}
// @formatter:on
}
@ParameterizedTest(name = "{index} — {0}")
@MethodSource
void testAvailableAfterClose(final String caseName, final InputStream delegate, final int expectedBeforeClose)
throws Exception {
final InputStream shadow;
try (InputStream in = BoundedInputStream.builder()
.setInputStream(delegate)
.setPropagateClose(true)
.get()) {
// Before close: pass-through behavior
assertEquals(expectedBeforeClose, in.available(), caseName + " (before close)");
shadow = in; // keep reference to call after close
}
// Verify the underlying stream was closed
verify(delegate, times(1)).close();
// After close: behavior depends on the underlying stream
assertEquals(0, shadow.available(), caseName + " (after close)");
// Interactions: available called only once before close.
verify(delegate, times(1)).available();
verifyNoMoreInteractions(delegate);
}
@ParameterizedTest
@MethodSource
void testAvailableUpperLimit(final InputStream input, final long maxCount, final int expectedBeforeSkip, final int expectedAfterSkip)
throws Exception {
try (BoundedInputStream bounded = BoundedInputStream.builder()
.setInputStream(input)
.setMaxCount(maxCount)
.get()) {
assertEquals(
expectedBeforeSkip, bounded.available(), "available should be limited by maxCount and data length");
IOUtils.skip(bounded, expectedBeforeSkip);
assertEquals(
expectedAfterSkip,
bounded.available(),
"after skipping available should be limited by maxCount and data length");
}
}
@Test
void testBuilderGet() {
// java.lang.IllegalStateException: origin == null
assertThrows(IllegalStateException.class, () -> BoundedInputStream.builder().get());
}
@Test
void testCloseHandleIOException() throws IOException {
ProxyInputStreamTest.testCloseHandleIOException(BoundedInputStream.builder());
}
@ParameterizedTest
@ValueSource(longs = { -100, -1, 0, 1, 2, 4, 8, 16, 32, 64 })
void testCounts(final long startCount) throws Exception {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
final long actualStart = startCount < 0 ? 0 : startCount;
// limit = length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setCount(startCount)
.setMaxCount(helloWorld.length).get()) {
assertTrue(bounded.markSupported());
assertEquals(helloWorld.length, bounded.getMaxCount());
assertEquals(helloWorld.length, bounded.getMaxLength());
assertEquals(actualStart, bounded.getCount());
assertEquals(Math.max(0, bounded.getMaxCount() - actualStart), bounded.getRemaining());
assertEquals(Math.max(0, bounded.getMaxLength() - actualStart), bounded.getRemaining());
int readCount = 0;
for (int i = 0; i < helloWorld.length; i++) {
final byte expectedCh = bounded.getRemaining() > 0 ? helloWorld[i] : EOF;
final int actualCh = bounded.read();
assertEquals(expectedCh, actualCh, "limit = length byte[" + i + "]");
if (actualCh != EOF) {
readCount++;
}
assertEquals(helloWorld.length, bounded.getMaxCount());
assertEquals(helloWorld.length, bounded.getMaxLength());
assertEquals(actualStart + readCount, bounded.getCount(), "i=" + i);
assertEquals(Math.max(0, bounded.getMaxCount() - (readCount + actualStart)), bounded.getRemaining());
assertEquals(Math.max(0, bounded.getMaxLength() - (readCount + actualStart)), bounded.getRemaining());
}
assertEquals(-1, bounded.read(), "limit = length end");
assertEquals(helloWorld.length, bounded.getMaxLength());
assertEquals(readCount + actualStart, bounded.getCount());
assertEquals(0, bounded.getRemaining());
assertEquals(0, bounded.available());
// should be invariant
assertTrue(bounded.markSupported());
}
// limit > length
final int maxCountP1 = helloWorld.length + 1;
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setCount(startCount)
.setMaxCount(maxCountP1).get()) {
assertTrue(bounded.markSupported());
assertEquals(maxCountP1, bounded.getMaxLength());
assertEquals(actualStart, bounded.getCount());
assertEquals(Math.max(0, bounded.getMaxCount() - actualStart), bounded.getRemaining());
assertEquals(Math.max(0, bounded.getMaxLength() - actualStart), bounded.getRemaining());
int readCount = 0;
for (int i = 0; i < helloWorld.length; i++) {
final byte expectedCh = bounded.getRemaining() > 0 ? helloWorld[i] : EOF;
final int actualCh = bounded.read();
assertEquals(expectedCh, actualCh, "limit = length byte[" + i + "]");
if (actualCh != EOF) {
readCount++;
}
assertEquals(maxCountP1, bounded.getMaxCount());
assertEquals(maxCountP1, bounded.getMaxLength());
assertEquals(actualStart + readCount, bounded.getCount(), "i=" + i);
assertEquals(Math.max(0, bounded.getMaxCount() - (readCount + actualStart)), bounded.getRemaining());
assertEquals(Math.max(0, bounded.getMaxLength() - (readCount + actualStart)), bounded.getRemaining());
}
assertEquals(-1, bounded.read(), "limit > length end");
assertEquals(0, bounded.available());
assertEquals(maxCountP1, bounded.getMaxLength());
assertEquals(readCount + actualStart, bounded.getCount());
assertEquals(Math.max(0, maxCountP1 - bounded.getCount()), bounded.getRemaining());
// should be invariant
assertTrue(bounded.markSupported());
}
// limit < length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(hello.length).get()) {
assertTrue(bounded.markSupported());
assertEquals(hello.length, bounded.getMaxLength());
assertEquals(0, bounded.getCount());
assertEquals(bounded.getMaxLength(), bounded.getRemaining());
int readCount = 0;
for (int i = 0; i < hello.length; i++) {
assertEquals(hello[i], bounded.read(), "limit < length byte[" + i + "]");
readCount++;
assertEquals(hello.length, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
}
assertEquals(-1, bounded.read(), "limit < length end");
assertEquals(0, bounded.available());
assertEquals(hello.length, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
// should be invariant
assertTrue(bounded.markSupported());
}
}
@Test
void testMarkReset() throws Exception {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
final int helloWorldLen = helloWorld.length;
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
final byte[] world = " World".getBytes(StandardCharsets.UTF_8);
final int helloLen = hello.length;
// limit = -1
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).get()) {
assertTrue(bounded.markSupported());
bounded.mark(0);
compare("limit = -1", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit = -1", hello, IOUtils.toByteArray(bounded, helloLen));
bounded.mark(helloWorldLen);
compare("limit = -1", world, IOUtils.toByteArray(bounded));
bounded.reset();
compare("limit = -1", world, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit = 0
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(0).get()) {
assertTrue(bounded.markSupported());
bounded.mark(0);
compare("limit = 0", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit = 0", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
bounded.mark(helloWorldLen);
compare("limit = 0", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit = length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length).get()) {
assertTrue(bounded.markSupported());
bounded.mark(0);
compare("limit = length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit = length", hello, IOUtils.toByteArray(bounded, helloLen));
bounded.mark(helloWorldLen);
compare("limit = length", world, IOUtils.toByteArray(bounded));
bounded.reset();
compare("limit = length", world, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit > length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length + 1).get()) {
assertTrue(bounded.markSupported());
bounded.mark(0);
compare("limit > length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit > length", helloWorld, IOUtils.toByteArray(bounded));
bounded.reset();
compare("limit > length", hello, IOUtils.toByteArray(bounded, helloLen));
bounded.mark(helloWorldLen);
compare("limit > length", world, IOUtils.toByteArray(bounded));
bounded.reset();
compare("limit > length", world, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit < length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length - (hello.length + 1)).get()) {
assertTrue(bounded.markSupported());
bounded.mark(0);
compare("limit < length", hello, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit < length", hello, IOUtils.toByteArray(bounded));
bounded.reset();
compare("limit < length", hello, IOUtils.toByteArray(bounded, helloLen));
bounded.mark(helloWorldLen);
compare("limit < length", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
bounded.reset();
compare("limit < length", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
}
@Test
void testOnMaxCountConsumer() throws Exception {
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
final AtomicBoolean boolRef = new AtomicBoolean();
// @formatter:off
try (BoundedInputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(hello))
.setMaxCount(hello.length)
.setOnMaxCount(null) // should not blow up
.setOnMaxCount((m, c) -> boolRef.set(true))
.get()) {
IOUtils.consume(bounded);
}
// @formatter:on
assertTrue(boolRef.get());
// Throwing
final String message = "test exception message";
// @formatter:off
try (BoundedInputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(hello))
.setMaxCount(hello.length)
.setOnMaxCount((m, c) -> {
throw new CustomIOException(message);
})
.get()) {
assertEquals(message, assertThrowsExactly(CustomIOException.class, () -> IOUtils.consume(bounded)).getMessage());
}
// @formatter:on
}
@SuppressWarnings("deprecation")
@Test
void testOnMaxLength() throws Exception {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
final AtomicBoolean boolRef = new AtomicBoolean();
// limit = length
try (BoundedInputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length)
.setOnMaxCount((m, c) -> boolRef.set(true))
.get()) {
assertTrue(bounded.markSupported());
assertEquals(helloWorld.length, bounded.getMaxCount());
assertEquals(helloWorld.length, bounded.getMaxLength());
assertEquals(0, bounded.getCount());
assertEquals(bounded.getMaxCount(), bounded.getRemaining());
assertEquals(bounded.getMaxLength(), bounded.getRemaining());
assertFalse(boolRef.get());
int readCount = 0;
for (int i = 0; i < helloWorld.length; i++) {
assertEquals(helloWorld[i], bounded.read(), "limit = length byte[" + i + "]");
readCount++;
assertEquals(helloWorld.length, bounded.getMaxCount());
assertEquals(helloWorld.length, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxCount() - readCount, bounded.getRemaining());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
}
assertEquals(-1, bounded.read(), "limit = length end");
assertEquals(0, bounded.available());
assertEquals(helloWorld.length, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
assertTrue(boolRef.get());
// should be invariant
assertTrue(bounded.markSupported());
}
// limit > length
boolRef.set(false);
final int length2 = helloWorld.length + 1;
try (BoundedInputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(length2)
.setOnMaxCount((m, c) -> boolRef.set(true))
.get()) {
assertTrue(bounded.markSupported());
assertEquals(length2, bounded.getMaxLength());
assertEquals(0, bounded.getCount());
assertEquals(bounded.getMaxLength(), bounded.getRemaining());
assertFalse(boolRef.get());
int readCount = 0;
for (int i = 0; i < helloWorld.length; i++) {
assertEquals(helloWorld[i], bounded.read(), "limit > length byte[" + i + "]");
readCount++;
assertEquals(length2, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
}
assertEquals(0, bounded.available());
assertEquals(-1, bounded.read(), "limit > length end");
assertEquals(length2, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
assertFalse(boolRef.get());
// should be invariant
assertTrue(bounded.markSupported());
}
// limit < length
boolRef.set(false);
try (BoundedInputStream bounded = BoundedInputStream.builder()
.setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(hello.length)
.setOnMaxCount((m, c) -> boolRef.set(true))
.get()) {
assertTrue(bounded.markSupported());
assertEquals(hello.length, bounded.getMaxLength());
assertEquals(0, bounded.getCount());
assertEquals(bounded.getMaxLength(), bounded.getRemaining());
assertFalse(boolRef.get());
int readCount = 0;
for (int i = 0; i < hello.length; i++) {
assertEquals(hello[i], bounded.read(), "limit < length byte[" + i + "]");
readCount++;
assertEquals(hello.length, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
}
assertEquals(-1, bounded.read(), "limit < length end");
assertEquals(hello.length, bounded.getMaxLength());
assertEquals(readCount, bounded.getCount());
assertEquals(bounded.getMaxLength() - readCount, bounded.getRemaining());
assertTrue(boolRef.get());
// should be invariant
assertTrue(bounded.markSupported());
}
}
@SuppressWarnings("deprecation")
@Test
void testPublicConstructors() throws IOException {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
try (ByteArrayInputStream baos = new ByteArrayInputStream(helloWorld);
BoundedInputStream inputStream = new BoundedInputStream(baos)) {
assertSame(baos, inputStream.unwrap());
}
final long maxCount = 2;
try (ByteArrayInputStream baos = new ByteArrayInputStream(helloWorld);
BoundedInputStream inputStream = new BoundedInputStream(baos, maxCount)) {
assertSame(baos, inputStream.unwrap());
assertSame(maxCount, inputStream.getMaxCount());
}
}
@ParameterizedTest(name = "{index} — {0}")
@MethodSource("testReadAfterClose")
void testReadAfterClose(
final String caseName,
final InputStream delegate,
final Object expectedAfterClose // Integer (value) or IOException (expected thrown)
) throws Exception {
final InputStream bounded;
try (InputStream in = BoundedInputStream.builder()
.setInputStream(delegate)
.setPropagateClose(true)
.get()) {
bounded = in; // call read() only after close
}
// Underlying stream should be closed exactly once
verify(delegate, times(1)).close();
if (expectedAfterClose instanceof Integer) {
assertEquals(expectedAfterClose, bounded.read(), caseName + " (after close)");
} else if (expectedAfterClose instanceof IOException) {
final IOException actual = assertThrows(IOException.class, bounded::read, caseName + " (after close)");
// verify it's the exact instance we configured
assertSame(expectedAfterClose, actual, caseName + " (exception instance)");
} else {
fail("Unexpected expectedAfterClose type: " + expectedAfterClose);
}
// We only performed one read() (after close)
verify(delegate, times(1)).read();
verifyNoMoreInteractions(delegate);
}
@Test
void testReadArray() throws Exception {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).get()) {
assertTrue(bounded.markSupported());
compare("limit = -1", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(0).get()) {
assertTrue(bounded.markSupported());
compare("limit = 0", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length).get()) {
assertTrue(bounded.markSupported());
compare("limit = length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length + 1).get()) {
assertTrue(bounded.markSupported());
compare("limit > length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length - 6).get()) {
assertTrue(bounded.markSupported());
compare("limit < length", hello, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
}
@Test
void testReadSingle() throws Exception {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
// limit = length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(helloWorld.length)
.get()) {
assertTrue(bounded.markSupported());
for (int i = 0; i < helloWorld.length; i++) {
assertEquals(helloWorld[i], bounded.read(), "limit = length byte[" + i + "]");
}
assertEquals(-1, bounded.read(), "limit = length end");
// should be invariant
assertTrue(bounded.markSupported());
}
// limit > length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(helloWorld.length + 1)
.get()) {
assertTrue(bounded.markSupported());
for (int i = 0; i < helloWorld.length; i++) {
assertEquals(helloWorld[i], bounded.read(), "limit > length byte[" + i + "]");
}
assertEquals(-1, bounded.read(), "limit > length end");
// should be invariant
assertTrue(bounded.markSupported());
}
// limit < length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(hello.length).get()) {
assertTrue(bounded.markSupported());
for (int i = 0; i < hello.length; i++) {
assertEquals(hello[i], bounded.read(), "limit < length byte[" + i + "]");
}
assertEquals(-1, bounded.read(), "limit < length end");
// should be invariant
assertTrue(bounded.markSupported());
}
}
@ParameterizedTest(name = "{index}: {0} -> initial remaining {2}")
@MethodSource
void testRemaining(final String caseName, final long maxCount, final long expectedInitialRemaining)
throws Exception {
final byte[] data = "Hello World".getBytes(StandardCharsets.UTF_8); // 11 bytes
try (BoundedInputStream in = BoundedInputStream.builder()
.setByteArray(data)
.setMaxCount(maxCount)
.get()) {
// Initial remaining respects the imposed limit (or is Long.MAX_VALUE if unbounded).
assertEquals(expectedInitialRemaining, in.getRemaining(), caseName + " (initial)");
// Skip more than the data length to exercise both bounded and unbounded paths.
final long skipped = IOUtils.skip(in, 42);
// For unbounded streams (EOF == -1), remaining stays the same.
// For bounded, it decreases by 'skipped'.
final long expectedAfterSkip =
in.getMaxCount() == IOUtils.EOF ? expectedInitialRemaining : expectedInitialRemaining - skipped;
assertEquals(expectedAfterSkip, in.getRemaining(), caseName + " (after skip)");
}
}
@Test
void testReset() throws Exception {
final byte[] helloWorld = "Hello World".getBytes(StandardCharsets.UTF_8);
final byte[] hello = "Hello".getBytes(StandardCharsets.UTF_8);
// limit = -1
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).get()) {
assertTrue(bounded.markSupported());
bounded.reset();
compare("limit = -1", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit = -1", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit = 0
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld)).setMaxCount(0).get()) {
assertTrue(bounded.markSupported());
bounded.reset();
compare("limit = 0", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit = 0", IOUtils.EMPTY_BYTE_ARRAY, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit = length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length).get()) {
assertTrue(bounded.markSupported());
bounded.reset();
compare("limit = length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit = length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit > length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length + 1).get()) {
assertTrue(bounded.markSupported());
bounded.reset();
compare("limit > length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit > length", helloWorld, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
// limit < length
try (BoundedInputStream bounded = BoundedInputStream.builder().setInputStream(new ByteArrayInputStream(helloWorld))
.setMaxCount(helloWorld.length - 6).get()) {
assertTrue(bounded.markSupported());
bounded.reset();
compare("limit < length", hello, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
// again
bounded.reset();
compare("limit < length", hello, IOUtils.toByteArray(bounded));
// should be invariant
assertTrue(bounded.markSupported());
}
}
}
|
apache/druid | 36,790 | indexing-service/src/test/java/org/apache/druid/indexing/input/DruidSegmentReaderTest.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.indexing.input;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.apache.druid.data.input.BytesCountingInputEntity;
import org.apache.druid.data.input.ColumnsFilter;
import org.apache.druid.data.input.InputEntity;
import org.apache.druid.data.input.InputEntity.CleanableFile;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.data.input.InputStats;
import org.apache.druid.data.input.MapBasedInputRow;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.DoubleDimensionSchema;
import org.apache.druid.data.input.impl.InputStatsImpl;
import org.apache.druid.data.input.impl.LongDimensionSchema;
import org.apache.druid.data.input.impl.StringDimensionSchema;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.hll.HyperLogLogCollector;
import org.apache.druid.hll.HyperLogLogHash;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.FileUtils;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.guava.BaseSequence;
import org.apache.druid.java.util.common.guava.BaseSequence.IteratorMaker;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.CountAggregatorFactory;
import org.apache.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory;
import org.apache.druid.query.filter.NotDimFilter;
import org.apache.druid.query.filter.OrDimFilter;
import org.apache.druid.query.filter.SelectorDimFilter;
import org.apache.druid.segment.AutoTypeColumnSchema;
import org.apache.druid.segment.IndexBuilder;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.column.ColumnType;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.loading.NoopSegmentCacheManager;
import org.apache.druid.segment.writeout.OnHeapMemorySegmentWriteOutMediumFactory;
import org.apache.druid.testing.InitializedNullHandlingTest;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.partition.TombstoneShardSpec;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertThrows;
public class DruidSegmentReaderTest extends InitializedNullHandlingTest
{
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File segmentDirectory;
private long segmentSize;
private final IndexIO indexIO = TestHelper.getTestIndexIO();
private DimensionsSpec dimensionsSpec;
private List<AggregatorFactory> metrics;
private InputStats inputStats;
@Before
public void setUp() throws IOException
{
// Write a segment with two rows in it, with columns: s (string), d (double), cnt (long), met_s (complex).
dimensionsSpec = new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
);
metrics = ImmutableList.of(
new CountAggregatorFactory("cnt"),
new HyperUniquesAggregatorFactory("met_s", "strCol")
);
final List<InputRow> rows = ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "foo")
.put("dblCol", 1.23)
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "bar")
.put("dblCol", 4.56)
.build()
)
);
inputStats = new InputStatsImpl();
persistSegment(rows);
}
@Test
public void testReader() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.put("cnt", 1L)
.put("met_s", makeHLLC("bar"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderWhenFilteringOnLongColumn() throws IOException
{
dimensionsSpec = new DimensionsSpec(
ImmutableList.of(
new LongDimensionSchema("longCol"),
StringDimensionSchema.create("a"),
StringDimensionSchema.create("b")
)
);
metrics = ImmutableList.of();
List<String> columnNames = ImmutableList.of("longCol", "a", "b");
final List<InputRow> rows = ImmutableList.of(
new MapBasedInputRow(
DateTimes.utc(1667115726217L),
columnNames,
ImmutableMap.<String, Object>builder()
.put("__time", 1667115726217L)
.put("longCol", 0L)
.put("a", "foo1")
.put("b", "bar1")
.build()
),
new MapBasedInputRow(
DateTimes.utc(1667115726224L),
columnNames,
ImmutableMap.<String, Object>builder()
.put("__time", 1667115726224L)
.put("longCol", 0L)
.put("a", "foo2")
.put("b", "bar2")
.build()
),
new MapBasedInputRow(
DateTimes.utc(1667115726128L),
columnNames,
ImmutableMap.<String, Object>builder()
.put("__time", 1667115726128L)
.put("longCol", 5L)
.put("a", "foo3")
.put("b", "bar3")
.build()
)
);
persistSegment(rows);
final InputStats inputStats = new InputStatsImpl();
final DruidSegmentReader reader = new DruidSegmentReader(
new BytesCountingInputEntity(
makeInputEntity(Intervals.of("2022-10-30/2022-10-31"), segmentDirectory, columnNames, null),
inputStats
),
indexIO,
new TimestampSpec("__time", "iso", null),
dimensionsSpec,
ColumnsFilter.all(),
new OrDimFilter(
new SelectorDimFilter("longCol", "5", null),
new NotDimFilter(new SelectorDimFilter("a", "foo1", null)),
new NotDimFilter(new SelectorDimFilter("b", "bar1", null))
),
temporaryFolder.newFolder()
);
Assert.assertEquals(Arrays.asList(rows.get(2), rows.get(1)), readRows(reader));
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testDruidTombstoneSegmentReader() throws IOException
{
final DruidTombstoneSegmentReader reader = new DruidTombstoneSegmentReader(
makeTombstoneInputEntity(Intervals.of("2000/P1D"))
);
Assert.assertFalse(reader.intermediateRowIterator().hasNext());
Assert.assertTrue(readRows(reader).isEmpty());
}
@Test
public void testDruidTombstoneSegmentReaderNotCreatedFromTombstone()
{
Exception exception = assertThrows(
IllegalArgumentException.class,
() -> new DruidTombstoneSegmentReader(
makeInputEntity(
Intervals.of("2000/P1D"),
segmentDirectory,
Collections.emptyList(),
Collections.emptyList()
)
)
);
Assert.assertEquals(
"DruidSegmentInputEntity must be created from a tombstone.",
exception.getMessage()
);
}
@Test
public void testReaderAutoTimestampFormat() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "auto", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.put("cnt", 1L)
.put("met_s", makeHLLC("bar"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderWithDimensionExclusions() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
DimensionsSpec.builder().setDimensionExclusions(ImmutableList.of("__time", "strCol", "cnt", "met_s")).build(),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.put("cnt", 1L)
.put("met_s", makeHLLC("bar"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderWithInclusiveColumnsFilter() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.inclusionBased(ImmutableSet.of("__time", "strCol", "dblCol")),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderWithInclusiveColumnsFilterNoTimestamp() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.inclusionBased(ImmutableSet.of("strCol", "dblCol")),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("1971"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "foo")
.put("dblCol", 1.23d)
.build()
),
new MapBasedInputRow(
DateTimes.of("1971"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "bar")
.put("dblCol", 4.56d)
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderWithFilter() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.all(),
new SelectorDimFilter("dblCol", "1.23", null),
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderTimestampFromDouble() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("dblCol", "posix", null),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("1970-01-01T00:00:01.000Z"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
),
new MapBasedInputRow(
DateTimes.of("1970-01-01T00:00:04.000Z"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.put("cnt", 1L)
.put("met_s", makeHLLC("bar"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderTimestampAsPosixIncorrectly() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec("__time", "posix", null),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("31969-04-01T00:00:00.000Z"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
),
new MapBasedInputRow(
DateTimes.of("31969-05-12T16:00:00.000Z"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.put("cnt", 1L)
.put("met_s", makeHLLC("bar"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testReaderTimestampSpecDefault() throws IOException
{
final DruidSegmentReader reader = new DruidSegmentReader(
makeInputEntity(Intervals.of("2000/P1D")),
indexIO,
new TimestampSpec(null, null, DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol")
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
Assert.assertEquals(
ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("1971"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T").getMillis())
.put("strCol", "foo")
.put("dblCol", 1.23d)
.put("cnt", 1L)
.put("met_s", makeHLLC("foo"))
.build()
),
new MapBasedInputRow(
DateTimes.of("1971"),
ImmutableList.of("strCol", "dblCol"),
ImmutableMap.<String, Object>builder()
.put("__time", DateTimes.of("2000T01").getMillis())
.put("strCol", "bar")
.put("dblCol", 4.56d)
.put("cnt", 1L)
.put("met_s", makeHLLC("bar"))
.build()
)
),
readRows(reader)
);
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testMakeCloseableIteratorFromSequenceAndSegmentFileCloseYielderOnClose() throws IOException
{
MutableBoolean isSequenceClosed = new MutableBoolean(false);
MutableBoolean isFileClosed = new MutableBoolean(false);
Sequence<Map<String, Object>> sequence = new BaseSequence<>(
new IteratorMaker<>()
{
@Override
public Iterator<Map<String, Object>> make()
{
return Collections.emptyIterator();
}
@Override
public void cleanup(Iterator<Map<String, Object>> iterFromMake)
{
isSequenceClosed.setValue(true);
}
}
);
CleanableFile cleanableFile = new CleanableFile()
{
@Override
public File file()
{
return null;
}
@Override
public void close()
{
isFileClosed.setValue(true);
}
};
try (CloseableIterator<Map<String, Object>> iterator =
DruidSegmentReader.makeCloseableIteratorFromSequenceAndSegmentFile(sequence, cleanableFile)) {
while (iterator.hasNext()) {
iterator.next();
}
}
Assert.assertTrue("File is not closed", isFileClosed.booleanValue());
Assert.assertTrue("Sequence is not closed", isSequenceClosed.booleanValue());
}
@Test
public void testArrayColumns() throws IOException
{
// make our own stuff here so that we don't pollute the shared spec, rows, and segment defined in setup and
// break all the other tests
DimensionsSpec dimensionsSpec = new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol"),
AutoTypeColumnSchema.of("arrayCol")
)
);
List<AggregatorFactory> metrics = ImmutableList.of(
new CountAggregatorFactory("cnt"),
new HyperUniquesAggregatorFactory("met_s", "strCol")
);
final List<InputRow> rows = ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol", "arrayCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "foo")
.put("dblCol", 1.23)
.put("arrayCol", ImmutableList.of("a", "b", "c"))
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("strCol", "dblCol", "arrayCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "bar")
.put("dblCol", 4.56)
.put("arrayCol", ImmutableList.of("x", "y", "z"))
.build()
)
);
InputStats inputStats = new InputStatsImpl();
final IncrementalIndex incrementalIndex =
IndexBuilder.create()
.schema(
new IncrementalIndexSchema.Builder()
.withDimensionsSpec(dimensionsSpec)
.withMetrics(metrics.toArray(new AggregatorFactory[0]))
.withRollup(false)
.build()
)
.rows(rows)
.buildIncrementalIndex();
File segmentDirectory = temporaryFolder.newFolder();
long segmentSize;
try {
TestHelper.getTestIndexMergerV9(
OnHeapMemorySegmentWriteOutMediumFactory.instance()
).persist(
incrementalIndex,
segmentDirectory,
IndexSpec.getDefault(),
null
);
segmentSize = FileUtils.getFileSize(segmentDirectory);
}
finally {
incrementalIndex.close();
}
InputEntity entity = new BytesCountingInputEntity(
makeInputEntity(
Intervals.of("2000/P1D"),
segmentDirectory,
ImmutableList.of("strCol", "dblCol", "arrayCol"),
ImmutableList.of("cnt", "met_s")
),
inputStats
);
final DruidSegmentReader reader = new DruidSegmentReader(
entity,
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol"),
AutoTypeColumnSchema.of("arrayCol")
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
List<InputRow> readRows = readRows(reader);
Assert.assertEquals(ImmutableList.of("strCol", "dblCol", "arrayCol"), readRows.get(0).getDimensions());
Assert.assertEquals(DateTimes.of("2000T").getMillis(), readRows.get(0).getTimestampFromEpoch());
Assert.assertEquals("foo", readRows.get(0).getRaw("strCol"));
Assert.assertEquals(1.23, readRows.get(0).getRaw("dblCol"));
Assert.assertArrayEquals(new Object[]{"a", "b", "c"}, (Object[]) readRows.get(0).getRaw("arrayCol"));
Assert.assertEquals(1L, readRows.get(0).getRaw("cnt"));
Assert.assertEquals(makeHLLC("foo"), readRows.get(0).getRaw("met_s"));
Assert.assertEquals(DateTimes.of("2000T1").getMillis(), readRows.get(1).getTimestampFromEpoch());
Assert.assertEquals("bar", readRows.get(1).getRaw("strCol"));
Assert.assertEquals(4.56, readRows.get(1).getRaw("dblCol"));
Assert.assertArrayEquals(new Object[]{"x", "y", "z"}, (Object[]) readRows.get(1).getRaw("arrayCol"));
Assert.assertEquals(1L, readRows.get(1).getRaw("cnt"));
Assert.assertEquals(makeHLLC("bar"), readRows.get(1).getRaw("met_s"));
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
@Test
public void testArrayColumnsCast() throws IOException
{
// make our own stuff here so that we don't pollute the shared spec, rows, and segment defined in setup and
// break all the other tests
DimensionsSpec dimensionsSpec = new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol"),
new AutoTypeColumnSchema("arrayCol", ColumnType.STRING_ARRAY, null)
)
);
List<AggregatorFactory> metrics = ImmutableList.of(
new CountAggregatorFactory("cnt"),
new HyperUniquesAggregatorFactory("met_s", "strCol")
);
final List<InputRow> rows = ImmutableList.of(
new MapBasedInputRow(
DateTimes.of("2000"),
ImmutableList.of("strCol", "dblCol", "arrayCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "foo")
.put("dblCol", 1.23)
.put("arrayCol", ImmutableList.of("a", "b", "c"))
.build()
),
new MapBasedInputRow(
DateTimes.of("2000T01"),
ImmutableList.of("strCol", "dblCol", "arrayCol"),
ImmutableMap.<String, Object>builder()
.put("strCol", "bar")
.put("dblCol", 4.56)
.put("arrayCol", ImmutableList.of(1L, 2L, 3L))
.build()
)
);
InputStats inputStats = new InputStatsImpl();
final IncrementalIndex incrementalIndex =
IndexBuilder.create()
.schema(
new IncrementalIndexSchema.Builder()
.withDimensionsSpec(dimensionsSpec)
.withMetrics(metrics.toArray(new AggregatorFactory[0]))
.withRollup(false)
.build()
)
.rows(rows)
.buildIncrementalIndex();
File segmentDirectory = temporaryFolder.newFolder();
long segmentSize;
try {
TestHelper.getTestIndexMergerV9(
OnHeapMemorySegmentWriteOutMediumFactory.instance()
).persist(
incrementalIndex,
segmentDirectory,
IndexSpec.getDefault(),
null
);
segmentSize = FileUtils.getFileSize(segmentDirectory);
}
finally {
incrementalIndex.close();
}
InputEntity entity = new BytesCountingInputEntity(
makeInputEntity(
Intervals.of("2000/P1D"),
segmentDirectory,
ImmutableList.of("strCol", "dblCol", "arrayCol"),
ImmutableList.of("cnt", "met_s")
),
inputStats
);
final DruidSegmentReader reader = new DruidSegmentReader(
entity,
indexIO,
new TimestampSpec("__time", "millis", DateTimes.of("1971")),
new DimensionsSpec(
ImmutableList.of(
StringDimensionSchema.create("strCol"),
new DoubleDimensionSchema("dblCol"),
new AutoTypeColumnSchema("arrayCol", ColumnType.STRING_ARRAY, null)
)
),
ColumnsFilter.all(),
null,
temporaryFolder.newFolder()
);
List<InputRow> readRows = readRows(reader);
Assert.assertEquals(ImmutableList.of("strCol", "dblCol", "arrayCol"), readRows.get(0).getDimensions());
Assert.assertEquals(DateTimes.of("2000T").getMillis(), readRows.get(0).getTimestampFromEpoch());
Assert.assertEquals("foo", readRows.get(0).getRaw("strCol"));
Assert.assertEquals(1.23, readRows.get(0).getRaw("dblCol"));
Assert.assertArrayEquals(new Object[]{"a", "b", "c"}, (Object[]) readRows.get(0).getRaw("arrayCol"));
Assert.assertEquals(1L, readRows.get(0).getRaw("cnt"));
Assert.assertEquals(makeHLLC("foo"), readRows.get(0).getRaw("met_s"));
Assert.assertEquals(DateTimes.of("2000T1").getMillis(), readRows.get(1).getTimestampFromEpoch());
Assert.assertEquals("bar", readRows.get(1).getRaw("strCol"));
Assert.assertEquals(4.56, readRows.get(1).getRaw("dblCol"));
Assert.assertArrayEquals(new Object[]{"1", "2", "3"}, (Object[]) readRows.get(1).getRaw("arrayCol"));
Assert.assertEquals(1L, readRows.get(1).getRaw("cnt"));
Assert.assertEquals(makeHLLC("bar"), readRows.get(1).getRaw("met_s"));
Assert.assertEquals(segmentSize, inputStats.getProcessedBytes());
}
private InputEntity makeInputEntity(final Interval interval)
{
return new BytesCountingInputEntity(
makeInputEntity(
interval,
segmentDirectory,
ImmutableList.of("strCol", "dblCol"),
ImmutableList.of("cnt", "met_s")
),
inputStats
);
}
public static DruidSegmentInputEntity makeInputEntity(
final Interval interval,
final File segmentDirectory,
final List<String> dimensions,
final List<String> metrics
)
{
return new DruidSegmentInputEntity(
new NoopSegmentCacheManager()
{
@Override
public void load(DataSegment segment)
{
// do nothing
}
@Override
public File getSegmentFiles(DataSegment segment)
{
return segmentDirectory;
}
@Override
public void drop(DataSegment segment)
{
segmentDirectory.delete();
}
},
DataSegment.builder()
.dataSource("ds")
.dimensions(dimensions)
.metrics(metrics)
.interval(interval)
.version("1")
.size(0)
.build(),
interval
);
}
public static DruidSegmentInputEntity makeTombstoneInputEntity(final Interval interval)
{
return new DruidSegmentInputEntity(
new NoopSegmentCacheManager(),
DataSegment.builder()
.dataSource("ds")
.interval(Intervals.of("2000/P1D"))
.version("1")
.shardSpec(new TombstoneShardSpec())
.loadSpec(ImmutableMap.of("type", "tombstone"))
.size(1)
.build(),
interval
);
}
private List<InputRow> readRows(DruidSegmentReader reader) throws IOException
{
final List<InputRow> rows = new ArrayList<>();
try (final CloseableIterator<Map<String, Object>> iterator = reader.intermediateRowIterator()) {
while (iterator.hasNext()) {
rows.addAll(reader.parseInputRows(iterator.next()));
}
}
return rows;
}
private List<InputRow> readRows(DruidTombstoneSegmentReader reader) throws IOException
{
final List<InputRow> rows = new ArrayList<>();
try (final CloseableIterator<Map<String, Object>> iterator = reader.intermediateRowIterator()) {
while (iterator.hasNext()) {
rows.addAll(reader.parseInputRows(iterator.next()));
}
}
return rows;
}
private static HyperLogLogCollector makeHLLC(final String... values)
{
final HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
for (String value : values) {
collector.add(HyperLogLogHash.getDefault().hash(value));
}
return collector;
}
private void persistSegment(List<InputRow> rows) throws IOException
{
final IncrementalIndex incrementalIndex =
IndexBuilder.create()
.schema(
new IncrementalIndexSchema.Builder()
.withDimensionsSpec(dimensionsSpec)
.withMetrics(metrics.toArray(new AggregatorFactory[0]))
.withRollup(false)
.build()
)
.rows(rows)
.buildIncrementalIndex();
segmentDirectory = temporaryFolder.newFolder();
try {
TestHelper.getTestIndexMergerV9(
OnHeapMemorySegmentWriteOutMediumFactory.instance()
).persist(
incrementalIndex,
segmentDirectory,
IndexSpec.getDefault(),
null
);
segmentSize = FileUtils.getFileSize(segmentDirectory);
}
finally {
incrementalIndex.close();
}
}
}
|
apache/linkis | 36,953 | linkis-public-enhancements/linkis-configuration/src/main/java/org/apache/linkis/configuration/restful/api/ConfigurationRestfulApi.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.linkis.configuration.restful.api;
import org.apache.linkis.configuration.conf.Configuration;
import org.apache.linkis.configuration.entity.*;
import org.apache.linkis.configuration.exception.ConfigurationException;
import org.apache.linkis.configuration.service.CategoryService;
import org.apache.linkis.configuration.service.ConfigKeyService;
import org.apache.linkis.configuration.service.ConfigurationService;
import org.apache.linkis.configuration.util.ConfigurationConfiguration;
import org.apache.linkis.configuration.util.JsonNodeUtil;
import org.apache.linkis.configuration.util.LabelEntityParser;
import org.apache.linkis.configuration.validate.ValidatorManager;
import org.apache.linkis.manager.label.entity.engine.EngineTypeLabel;
import org.apache.linkis.manager.label.entity.engine.UserCreatorLabel;
import org.apache.linkis.manager.label.utils.LabelUtils;
import org.apache.linkis.server.BDPJettyServerHelper;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.linkis.configuration.errorcode.LinkisConfigurationErrorCodeSummary.*;
@Api(tags = "parameter configuration")
@RestController
@RequestMapping(path = "/configuration")
public class ConfigurationRestfulApi {
private static final Logger logger = LoggerFactory.getLogger(ConfigurationRestfulApi.class);
@Autowired private ConfigurationService configurationService;
@Autowired private CategoryService categoryService;
@Autowired private ConfigKeyService configKeyService;
@Autowired private ValidatorManager validatorManager;
ObjectMapper mapper = new ObjectMapper();
private static final String NULL = "null";
@ApiOperation(value = "addKeyForEngine", notes = "add key for engine", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "engineType", dataType = "String"),
@ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version"),
@ApiImplicitParam(name = "token, required = false", dataType = "String", value = "token"),
@ApiImplicitParam(name = "keyJson", required = false, dataType = "String", value = "key json")
})
@RequestMapping(path = "/addKeyForEngine", method = RequestMethod.GET)
public Message addKeyForEngine(
HttpServletRequest req,
@RequestParam(value = "engineType", required = false) String engineType,
@RequestParam(value = "version", required = false) String version,
@RequestParam(value = "token", required = false) String token,
@RequestParam(value = "keyJson", required = false) String keyJson)
throws ConfigurationException {
if (StringUtils.isBlank(engineType)
|| StringUtils.isBlank(version)
|| StringUtils.isBlank(token)) {
throw new ConfigurationException(PARAMS_CANNOT_BE_EMPTY.getErrorDesc());
}
ModuleUserUtils.getOperationUser(
req,
MessageFormat.format(
"addKeyForEngine,engineType:{0},version:{1},token:{2}", engineType, version, token));
// todo 检验token
if (!token.equals(ConfigurationConfiguration.COPYKEYTOKEN)) {
throw new ConfigurationException(TOKEN_IS_ERROR.getErrorDesc());
}
ConfigKey configKey = BDPJettyServerHelper.gson().fromJson(keyJson, ConfigKey.class);
configurationService.addKeyForEngine(engineType, version, configKey);
// TODO: 2019/12/30 configKey参数校验
return Message.ok();
}
@ApiOperation(
value = "getFullTreesByAppName",
notes = "get full trees by app name",
response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "engineType", dataType = "String"),
@ApiImplicitParam(name = "version", dataType = "String", value = "version"),
@ApiImplicitParam(name = "creator", dataType = "String", value = "creator")
})
@RequestMapping(path = "/getFullTreesByAppName", method = RequestMethod.GET)
public Message getFullTreesByAppName(
HttpServletRequest req,
@RequestParam(value = "engineType", required = false) String engineType,
@RequestParam(value = "version", required = false) String version,
@RequestParam(value = "creator", required = false) String creator)
throws ConfigurationException {
if (creator != null
&& (creator.equals(org.apache.linkis.common.conf.Configuration.GLOBAL_CONF_CHN_NAME())
|| creator.equals(org.apache.linkis.common.conf.Configuration.GLOBAL_CONF_CHN_OLDNAME())
|| creator.equals(
org.apache.linkis.common.conf.Configuration.GLOBAL_CONF_CHN_EN_NAME()))) {
engineType = "*";
version = "*";
creator = "*";
}
String username =
ModuleUserUtils.getOperationUser(
req,
MessageFormat.format(
"getFullTreesByAppName,engineType:{0},version:{1},creator:{2}",
engineType, version, creator));
List labelList =
LabelEntityParser.generateUserCreatorEngineTypeLabelList(
username, creator, engineType, version);
ArrayList<ConfigTree> configTrees =
configurationService.getFullTreeByLabelList(
labelList, true, req.getHeader("Content-Language"));
return Message.ok().data("fullTree", configTrees);
}
@ApiOperation(value = "getCategory", notes = "get category", response = Message.class)
@RequestMapping(path = "/getCategory", method = RequestMethod.GET)
public Message getCategory(HttpServletRequest req) {
List<CategoryLabelVo> categoryLabelList =
categoryService.getAllCategory(req.getHeader("Content-Language"));
return Message.ok().data("Category", categoryLabelList);
}
@ApiOperation(
value = "getItemList",
notes = "get configuration list by engineType",
response = Message.class)
@RequestMapping(path = "/getItemList", method = RequestMethod.GET)
public Message getItemList(
HttpServletRequest req, @RequestParam(value = "engineType") String engineType)
throws ConfigurationException {
ModuleUserUtils.getOperationUser(req, "getItemList with engineType:" + engineType);
// Adding * represents returning all configuration information
if ("*".equals(engineType)) {
engineType = "";
}
List<ConfigKey> result = configKeyService.getConfigKeyList(engineType);
List<Map<String, Object>> filterResult = new ArrayList<>();
for (ConfigKey configKey : result) {
Map<String, Object> temp = new HashMap<>();
temp.put("key", configKey.getKey());
temp.put("name", configKey.getName());
temp.put("description", configKey.getDescription());
temp.put("engineType", configKey.getEngineType());
temp.put("validateType", configKey.getValidateType());
temp.put("validateRange", configKey.getValidateRange());
temp.put("boundaryType", configKey.getBoundaryType());
temp.put("defaultValue", configKey.getDefaultValue());
temp.put("require", configKey.getTemplateRequired());
filterResult.add(temp);
}
return Message.ok().data("itemList", filterResult);
}
@ApiOperation(
value = "createFirstCategory",
notes = "create first category",
response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "categoryName", required = true, dataType = "String"),
@ApiImplicitParam(name = "description", required = true, dataType = "String"),
})
@ApiOperationSupport(ignoreParameters = {"jsonNode"})
@RequestMapping(path = "/createFirstCategory", method = RequestMethod.POST)
public Message createFirstCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(request, "createFirstCategory");
checkAdmin(username);
String categoryName = jsonNode.get("categoryName").asText();
String description = jsonNode.get("description").asText();
if (StringUtils.isEmpty(categoryName) || categoryName.equals(NULL)) {
throw new ConfigurationException(IS_NULL_CANNOT_BE_ADDED.getErrorDesc());
}
if (StringUtils.isEmpty(categoryName) || categoryName.contains("-")) {
throw new ConfigurationException(CANNOT_BE_INCLUDED.getErrorDesc());
}
categoryService.createFirstCategory(categoryName, description);
return Message.ok();
}
@ApiOperation(value = "deleteCategory", notes = "delete category", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "categoryId", required = true, dataType = "String", example = "54")
})
@ApiOperationSupport(ignoreParameters = "jsonNode")
@RequestMapping(path = "/deleteCategory", method = RequestMethod.POST)
public Message deleteCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(request, "deleteCategory");
checkAdmin(username);
Integer categoryId = jsonNode.get("categoryId").asInt();
categoryService.deleteCategory(categoryId);
return Message.ok();
}
@ApiOperation(
value = "createSecondCategory",
notes = "create second category",
response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "categoryId", required = true, dataType = "String", example = "39"),
@ApiImplicitParam(name = "engineType", required = true, dataType = "String", example = "hive"),
@ApiImplicitParam(name = "version", required = true, dataType = "String", example = "1.2.0"),
@ApiImplicitParam(name = "description", required = true, dataType = "String"),
})
@ApiOperationSupport(ignoreParameters = {"jsonNode"})
@RequestMapping(path = "/createSecondCategory", method = RequestMethod.POST)
public Message createSecondCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(request, "createSecondCategory");
checkAdmin(username);
Integer categoryId = jsonNode.get("categoryId").asInt();
String engineType = jsonNode.get("engineType").asText();
String version = jsonNode.get("version").asText();
String description = jsonNode.get("description").asText();
if (categoryId <= 0) {
throw new ConfigurationException(CREATOR_IS_NULL_CANNOT_BE_ADDED.getErrorDesc());
}
if (StringUtils.isEmpty(engineType) || engineType.toLowerCase().equals(NULL)) {
throw new ConfigurationException(ENGINE_TYPE_IS_NULL.getErrorDesc());
}
if (StringUtils.isEmpty(version) || version.toLowerCase().equals(NULL)) {
version = LabelUtils.COMMON_VALUE;
}
categoryService.createSecondCategory(categoryId, engineType, version, description);
return Message.ok();
}
@ApiOperation(value = "saveFullTree", notes = "save full tree", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "creator", required = true, dataType = "String", example = "xwzTest"),
@ApiImplicitParam(name = "engineType", required = true, dataType = "String", example = "hive"),
@ApiImplicitParam(name = "fullTree", required = true, dataType = "List", value = "full tree"),
@ApiImplicitParam(name = "name", required = true, dataType = "String", value = "name"),
@ApiImplicitParam(name = "description", required = true, dataType = "String"),
@ApiImplicitParam(name = "settings", required = true, dataType = "List", value = "settings")
})
@ApiOperationSupport(ignoreParameters = {"json"})
@RequestMapping(path = "/saveFullTree", method = RequestMethod.POST)
public Message saveFullTree(HttpServletRequest req, @RequestBody JsonNode json)
throws IOException, ConfigurationException {
List fullTrees = mapper.treeToValue(json.get("fullTree"), List.class);
String creator = JsonNodeUtil.getStringValue(json.get("creator"));
String engineType = JsonNodeUtil.getStringValue(json.get("engineType"));
if (creator != null
&& (creator.equals(org.apache.linkis.common.conf.Configuration.GLOBAL_CONF_CHN_NAME())
|| creator.equals(org.apache.linkis.common.conf.Configuration.GLOBAL_CONF_CHN_OLDNAME())
|| creator.equals(
org.apache.linkis.common.conf.Configuration.GLOBAL_CONF_CHN_EN_NAME()))) {
creator = "*";
}
String username = ModuleUserUtils.getOperationUser(req, "saveFullTree");
ArrayList<ConfigValue> createList = new ArrayList<>();
ArrayList<ConfigValue> updateList = new ArrayList<>();
ArrayList<List<ConfigKeyValue>> chekList = new ArrayList<>();
String sparkConf = "";
for (Object o : fullTrees) {
String s = BDPJettyServerHelper.gson().toJson(o);
ConfigTree fullTree = BDPJettyServerHelper.gson().fromJson(s, ConfigTree.class);
List<ConfigKeyValue> settings = fullTree.getSettings();
chekList.add(settings);
for (ConfigKeyValue configKeyValue : settings) {
if (configKeyValue.getKey().equals("spark.conf")
&& StringUtils.isNotBlank(configKeyValue.getConfigValue())) {
sparkConf = configKeyValue.getConfigValue().trim();
configKeyValue.setConfigValue(sparkConf);
}
}
}
for (List<ConfigKeyValue> settings : chekList) {
sparkConfCheck(settings, sparkConf);
Integer userLabelId =
configurationService.checkAndCreateUserLabel(settings, username, creator);
for (ConfigKeyValue setting : settings) {
configurationService.updateUserValue(setting, userLabelId, createList, updateList);
}
}
String engine = null;
String version = null;
if (engineType != null) {
String[] tmpString = engineType.split("-");
if (tmpString.length != 2) {
throw new ConfigurationException(INCORRECT_FIXED_SUCH.getErrorDesc());
}
engine = tmpString[0];
version = tmpString[1];
}
configurationService.updateUserValue(createList, updateList);
// TODO: Add a refresh cache interface later
if (StringUtils.isNotBlank(creator) && creator.equals("*")) {
List<CategoryLabelVo> allCategory = categoryService.getAllCategory(null);
List<CategoryLabelVo> categoryLabelVos =
allCategory.stream()
.filter(s -> s.getCategoryName().equals(Configuration.REMOVE_APPLICATION_CACHE()))
.map(CategoryLabelVo::getChildCategory)
.findFirst()
.get();
categoryLabelVos.stream()
.map(CategoryLabelVo::getCategoryName)
.filter(StringUtils::isNotBlank)
.forEach(
info -> {
String[] tmpString = info.split("-");
if (tmpString.length == 2) {
String engineName = tmpString[0];
String engineVersion = tmpString[1];
logger.info(
"Config remove engine cache:engineName:{},engineVersion:{}",
engineName,
engineVersion);
configurationService.clearAMCacheConf(
username,
Configuration.REMOVE_APPLICATION_CACHE(),
engineName,
engineVersion);
}
});
configurationService.clearAMCacheConf(username, creator, null, null);
} else {
configurationService.clearAMCacheConf(username, creator, engine, version);
}
return Message.ok();
}
private void sparkConfCheck(List<ConfigKeyValue> settings, String sparkConf)
throws ConfigurationException {
if (StringUtils.isNotBlank(sparkConf)) {
// Check if there are any duplicates in spark. conf
// spark.conf : spark.shuffle.compress=ture;spark.executor.memory=4g
String[] split = sparkConf.split(";");
int setSize =
Arrays.stream(split).map(s -> s.split("=")[0].trim()).collect(Collectors.toSet()).size();
int listSize =
Arrays.stream(split).map(s -> s.split("=")[0].trim()).collect(Collectors.toList()).size();
if (listSize != setSize) {
throw new ConfigurationException("Spark.conf contains duplicate keys");
}
// Check if there are any duplicates in the spark.conf configuration and other individual
for (String keyValue : split) {
String key = keyValue.split("=")[0].trim();
boolean matchResult =
settings.stream().anyMatch(settingKey -> key.equals(settingKey.getKey()));
if (matchResult) {
throw new ConfigurationException(
"Saved key is duplicated with the spark conf key , key :" + key);
}
}
}
}
@ApiOperation(
value = "listAllEngineType",
notes = "list all engine type",
response = Message.class)
@RequestMapping(path = "/engineType", method = RequestMethod.GET)
public Message listAllEngineType(HttpServletRequest request) {
String[] engineType = configurationService.listAllEngineType();
return Message.ok().data("engineType", engineType);
}
@ApiOperation(
value = "updateCategoryInfo",
notes = "update category info",
response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "description", required = true, dataType = "String"),
@ApiImplicitParam(name = "categoryId", required = true, dataType = "String")
})
@ApiOperationSupport(ignoreParameters = {"jsonNode"})
@RequestMapping(path = "/updateCategoryInfo", method = RequestMethod.POST)
public Message updateCategoryInfo(HttpServletRequest request, @RequestBody JsonNode jsonNode)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(request, "updateCategoryInfo");
checkAdmin(username);
String description = null;
Integer categoryId = null;
try {
description = jsonNode.get("description").asText();
categoryId = jsonNode.get("categoryId").asInt();
} catch (Exception e) {
throw new ConfigurationException(INCOMPLETE_RECONFIRM.getErrorDesc());
}
if (description != null) {
categoryService.updateCategory(categoryId, description);
}
return Message.ok();
}
@ApiOperation(value = "rpcTest", notes = "rpc test", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "creator", dataType = "String", value = "creator"),
@ApiImplicitParam(name = "engineType", dataType = "String"),
@ApiImplicitParam(name = "username", dataType = "String"),
@ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version")
})
@RequestMapping(path = "/rpcTest", method = RequestMethod.GET)
public Message rpcTest(
@RequestParam(value = "username", required = false) String username,
@RequestParam(value = "creator", required = false) String creator,
@RequestParam(value = "engineType", required = false) String engineType,
@RequestParam(value = "version", required = false) String version) {
configurationService.queryGlobalConfig(username);
EngineTypeLabel engineTypeLabel = new EngineTypeLabel();
engineTypeLabel.setVersion(version);
engineTypeLabel.setEngineType(engineType);
configurationService.queryDefaultEngineConfig(engineTypeLabel);
UserCreatorLabel userCreatorLabel = new UserCreatorLabel();
userCreatorLabel.setCreator(creator);
userCreatorLabel.setUser(username);
configurationService.queryConfig(userCreatorLabel, engineTypeLabel, "wds.linkis.rm");
Message message = Message.ok();
return message;
}
private void checkAdmin(String userName) throws ConfigurationException {
if (!org.apache.linkis.common.conf.Configuration.isAdmin(userName)) {
throw new ConfigurationException(ONLY_ADMIN_PERFORM.getErrorDesc());
}
}
@ApiOperation(value = "getKeyValue", notes = "get key value", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "creator", required = false, dataType = "String", value = "creator"),
@ApiImplicitParam(name = "engineType", dataType = "String"),
@ApiImplicitParam(name = "configKey", dataType = "String"),
@ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version")
})
@RequestMapping(path = "/keyvalue", method = RequestMethod.GET)
public Message getKeyValue(
HttpServletRequest req,
@RequestParam(value = "engineType", required = false, defaultValue = "*") String engineType,
@RequestParam(value = "version", required = false, defaultValue = "*") String version,
@RequestParam(value = "creator", required = false, defaultValue = "*") String creator,
@RequestParam(value = "configKey") String configKey)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(req, "getKeyValue");
if (engineType.equals("*") && !version.equals("*")) {
return Message.error("When engineType is any engine, the version must also be any version");
}
List labelList =
LabelEntityParser.generateUserCreatorEngineTypeLabelList(
username, creator, engineType, version);
List<ConfigValue> configValues = configKeyService.getConfigValue(configKey, labelList);
Message message = Message.ok().data("configValues", configValues);
if (configValues.size() > 1) {
message.data(
"warnMessage", "There are multiple values for the corresponding Key: " + configKey);
}
return message;
}
@ApiOperation(value = "saveKeyValue", notes = "save key value", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "engineType", required = true, dataType = "String"),
@ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version"),
@ApiImplicitParam(name = "creator", required = true, dataType = "String", value = "creator"),
@ApiImplicitParam(name = "configKey", required = true, dataType = "String"),
@ApiImplicitParam(name = "configValue", required = true, dataType = "String"),
@ApiImplicitParam(name = "configKeyId", required = false, dataType = "String")
})
@ApiOperationSupport(ignoreParameters = {"json"})
@RequestMapping(path = "/keyvalue", method = RequestMethod.POST)
public Message saveKeyValue(HttpServletRequest req, @RequestBody Map<String, Object> json)
throws ConfigurationException {
Message message = Message.ok();
String username = ModuleUserUtils.getOperationUser(req, "saveKey");
String engineType = ((String) json.getOrDefault("engineType", "*")).trim();
String user = ((String) json.getOrDefault("user", "")).trim();
String version = ((String) json.getOrDefault("version", "*")).trim();
String creator = ((String) json.getOrDefault("creator", "*")).trim();
String configKey = ((String) json.get("configKey")).trim();
String value = ((String) json.get("configValue")).trim();
String configKeyId = ((String) json.getOrDefault("configKeyId", "")).trim();
boolean force = Boolean.parseBoolean(json.getOrDefault("force", "false").toString());
if (!org.apache.linkis.common.conf.Configuration.isAdmin(username) && !username.equals(user)) {
return Message.error("Only admin can modify other user configuration data");
}
if (engineType.equals("*") && !version.equals("*")) {
return Message.error("When engineType is any engine, the version must also be any version");
}
if (StringUtils.isBlank(configKey)) {
return Message.error("key cannot be empty");
}
if (StringUtils.isNotBlank(user)) {
username = user;
}
List labelList =
LabelEntityParser.generateUserCreatorEngineTypeLabelList(
username, creator, engineType, version);
ConfigKeyValue configKeyValue = new ConfigKeyValue();
configKeyValue.setKey(configKey);
configKeyValue.setConfigValue(value);
if (StringUtils.isNotBlank(configKeyId)) {
configKeyValue.setId(Long.valueOf(configKeyId));
}
try {
configurationService.paramCheck(configKeyValue);
} catch (Exception e) {
if (force && e instanceof ConfigurationException) {
message.data(
"msg",
"The update was successful, but the value verification failed. Please confirm if it has any impact:"
+ "(更新成功,但是值校验失败,请确认是否有影响)\n"
+ e.getMessage());
} else {
return Message.error(e.getMessage());
}
}
ConfigValue configValue = configKeyService.saveConfigValue(configKeyValue, labelList);
configurationService.clearAMCacheConf(username, creator, engineType, version);
return message.data("configValue", configValue);
}
@ApiOperation(value = "deleteKeyValue", notes = "delete key value", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "engineType", required = true, dataType = "String"),
@ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version"),
@ApiImplicitParam(name = "creator", required = true, dataType = "String", value = "creator"),
@ApiImplicitParam(name = "configKey", required = true, dataType = "String")
})
@ApiOperationSupport(ignoreParameters = {"json"})
@RequestMapping(path = "/keyvalue", method = RequestMethod.DELETE)
public Message deleteKeyValue(HttpServletRequest req, @RequestBody Map<String, Object> json)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(req, "deleteKeyValue");
String engineType = ((String) json.getOrDefault("engineType", "*")).trim();
String version = ((String) json.getOrDefault("version", "*")).trim();
String creator = ((String) json.getOrDefault("creator", "*")).trim();
String configKey = ((String) json.get("configKey")).trim();
if (engineType.equals("*") && !version.equals("*")) {
return Message.error("When engineType is any engine, the version must also be any version");
}
if (StringUtils.isBlank(configKey)) {
return Message.error("key cannot be empty");
}
List labelList =
LabelEntityParser.generateUserCreatorEngineTypeLabelList(
username, creator, engineType, version);
List<ConfigValue> configValues = configKeyService.deleteConfigValue(configKey, labelList);
return Message.ok().data("configValues", configValues);
}
@ApiOperation(value = "getBaseKeyValue", notes = "get key", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(
name = "engineType",
required = false,
dataType = "String",
value = "engineType"),
@ApiImplicitParam(name = "key", required = false, dataType = "String", value = "key"),
@ApiImplicitParam(name = "pageNow", required = false, dataType = "Integer", defaultValue = "1"),
@ApiImplicitParam(
name = "pageSize",
required = false,
dataType = "Integer",
defaultValue = "20"),
})
@RequestMapping(path = "/baseKeyValue", method = RequestMethod.GET)
public Message getBaseKeyValue(
HttpServletRequest req,
@RequestParam(value = "engineType", required = false) String engineType,
@RequestParam(value = "key", required = false) String key,
@RequestParam(value = "pageNow", required = false, defaultValue = "1") Integer pageNow,
@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize)
throws ConfigurationException {
checkAdmin(ModuleUserUtils.getOperationUser(req, "getBaseKeyValue"));
if (StringUtils.isBlank(engineType)) {
engineType = null;
}
if (StringUtils.isBlank(key)) {
key = null;
}
PageHelper.startPage(pageNow, pageSize);
List<ConfigKey> list = null;
try {
list = configKeyService.getConfigBykey(engineType, key, req.getHeader("Content-Language"));
} finally {
PageHelper.clearPage();
}
PageInfo<ConfigKey> pageInfo = new PageInfo<>(list);
long total = pageInfo.getTotal();
return Message.ok().data("configKeyList", list).data("totalPage", total);
}
@ApiOperation(value = "deleteBaseKeyValue", notes = "delete key", response = Message.class)
@ApiImplicitParams({@ApiImplicitParam(name = "id", required = true, dataType = "Integer")})
@RequestMapping(path = "/baseKeyValue", method = RequestMethod.DELETE)
public Message deleteBaseKeyValue(HttpServletRequest req, @RequestParam(value = "id") Integer id)
throws ConfigurationException {
checkAdmin(ModuleUserUtils.getOperationUser(req, "deleteBaseKeyValue ID:" + id));
configKeyService.deleteConfigById(id);
return Message.ok();
}
@ApiOperation(value = "saveBaseKeyValue", notes = "save key", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", required = false, dataType = "Integer", value = "id"),
@ApiImplicitParam(name = "key", required = true, dataType = "String", value = "key"),
@ApiImplicitParam(name = "name", required = true, dataType = "String", value = "name"),
@ApiImplicitParam(
name = "description",
required = true,
dataType = "String",
value = "description"),
@ApiImplicitParam(
name = "defaultValue",
required = true,
dataType = "String",
value = "defaultValue"),
@ApiImplicitParam(
name = "validateType",
required = true,
dataType = "String",
value = "validateType"),
@ApiImplicitParam(
name = "validateRange",
required = true,
dataType = "String",
value = "validateRange"),
@ApiImplicitParam(
name = "boundaryType",
required = true,
dataType = "String",
value = "boundaryType"),
@ApiImplicitParam(name = "treeName", required = true, dataType = "String", value = "treeName"),
@ApiImplicitParam(
name = "engineType",
required = true,
dataType = "String",
value = "engineType"),
@ApiImplicitParam(name = "enName", required = false, dataType = "String", value = "enName"),
@ApiImplicitParam(
name = "enDescription",
required = false,
dataType = "String",
value = "enDescription"),
@ApiImplicitParam(
name = "enTreeName",
required = false,
dataType = "String",
value = "enTreeName"),
@ApiImplicitParam(
name = "templateRequired",
required = false,
dataType = "String",
value = "1"),
})
@ApiOperationSupport(ignoreParameters = {"json"})
@RequestMapping(path = "/baseKeyValue", method = RequestMethod.POST)
public Message saveBaseKeyValue(HttpServletRequest req, @RequestBody ConfigKey configKey)
throws ConfigurationException, InstantiationException, IllegalAccessException {
checkAdmin(ModuleUserUtils.getOperationUser(req, "saveBaseKeyValue"));
String key = configKey.getKey();
String defaultValue = configKey.getDefaultValue();
String validateType = configKey.getValidateType();
String validateRange = configKey.getValidateRange();
String engineType = configKey.getEngineType();
if (StringUtils.isBlank(key)) {
return Message.error("key cannot be empty");
}
configKey.setKey(configKey.getKey().trim());
if (StringUtils.isBlank(configKey.getName())) {
return Message.error("name cannot be empty");
}
if (StringUtils.isBlank(configKey.getDescription())) {
return Message.error("description cannot be empty");
}
if (StringUtils.isBlank(configKey.getTreeName())) {
return Message.error("treeName cannot be empty");
}
if (StringUtils.isBlank(validateType)) {
return Message.error("validateType cannot be empty");
}
if (!validateType.equals("None") && StringUtils.isBlank(validateRange)) {
return Message.error("validateRange cannot be empty");
}
if (null == configKey.getBoundaryType()) {
return Message.error("boundaryType cannot be empty");
}
if (StringUtils.isNotEmpty(defaultValue)
&& !validatorManager
.getOrCreateValidator(validateType)
.validate(defaultValue, validateRange)) {
String msg =
MessageFormat.format(
"Parameter configValue verification failed(参数defaultValue校验失败):"
+ "key:{0}, ValidateType:{1}, ValidateRange:{2},ConfigValue:{3}",
key, validateType, validateRange, defaultValue);
throw new ConfigurationException(msg);
}
configKey.setDefaultValue(configKey.getDefaultValue().trim());
if (null == configKey.getId()) {
List<ConfigKey> configBykey =
configKeyService.getConfigBykey(engineType, key, req.getHeader("Content-Language"));
if (CollectionUtils.isNotEmpty(configBykey)) {
return Message.error("The engine has the same key: " + key);
}
configKeyService.saveConfigKey(configKey);
} else {
configKey.setId(configKey.getId());
configKeyService.updateConfigKey(configKey);
}
return Message.ok().data("configKey", configKey);
}
@ApiOperation(value = "getUserkeyvalue", notes = "get key", response = Message.class)
@ApiImplicitParams({
@ApiImplicitParam(
name = "engineType",
required = false,
dataType = "String",
value = "engineType"),
@ApiImplicitParam(name = "key", required = false, dataType = "String", value = "key"),
@ApiImplicitParam(name = "creator", required = false, dataType = "String", value = "creator"),
@ApiImplicitParam(name = "user", required = false, dataType = "String", value = "user"),
@ApiImplicitParam(name = "pageNow", required = false, dataType = "Integer", defaultValue = "1"),
@ApiImplicitParam(
name = "pageSize",
required = false,
dataType = "Integer",
defaultValue = "20"),
})
@RequestMapping(path = "/userKeyValue", method = RequestMethod.GET)
public Message getUserKeyValue(
HttpServletRequest req,
@RequestParam(value = "engineType", required = false) String engineType,
@RequestParam(value = "key", required = false) String key,
@RequestParam(value = "creator", required = false) String creator,
@RequestParam(value = "user", required = false) String user,
@RequestParam(value = "pageNow", required = false, defaultValue = "1") Integer pageNow,
@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize)
throws ConfigurationException {
String username = ModuleUserUtils.getOperationUser(req, "getUserKeyValue");
if (StringUtils.isBlank(engineType)) {
engineType = null;
}
if (StringUtils.isBlank(key)) {
key = null;
}
if (StringUtils.isBlank(creator)) {
creator = null;
}
if (StringUtils.isBlank(user)) {
user = null;
}
if (!org.apache.linkis.common.conf.Configuration.isAdmin(username) && !username.equals(user)) {
return Message.error("Only admin can query other user configuration data");
}
PageHelper.startPage(pageNow, pageSize);
List<ConfigUserValue> list;
try {
list = configKeyService.getUserConfigValue(engineType, key, creator, user);
} finally {
PageHelper.clearPage();
}
PageInfo<ConfigUserValue> pageInfo = new PageInfo<>(list);
long total = pageInfo.getTotal();
return Message.ok().data("configValueList", list).data("totalPage", total);
}
}
|
google/ExoPlayer | 37,002 | library/hls/src/test/java/com/google/android/exoplayer2/source/hls/HlsMediaSourceTest.java | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source.hls;
import static com.google.android.exoplayer2.robolectric.RobolectricUtil.runMainLooperUntil;
import static com.google.common.truth.Truth.assertThat;
import android.net.Uri;
import android.os.SystemClock;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.analytics.PlayerId;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist;
import com.google.android.exoplayer2.source.hls.playlist.HlsPlaylistParser;
import com.google.android.exoplayer2.testutil.FakeDataSet;
import com.google.android.exoplayer2.testutil.FakeDataSource;
import com.google.android.exoplayer2.util.Util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit test for {@link HlsMediaSource}. */
@RunWith(AndroidJUnit4.class)
public class HlsMediaSourceTest {
@Test
public void loadLivePlaylist_noTargetLiveOffsetDefined_fallbackToThreeTargetDuration()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds but not hold back or part hold back.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:CAN-SKIP-UNTIL=24";
// The playlist finishes 1 second before the current time, therefore there's a live edge
// offset of 1 second.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from target duration (3 * 4 = 12 seconds) and then expressed
// in relation to the live edge (12 + 1 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(13000);
assertThat(window.liveConfiguration.minPlaybackSpeed).isEqualTo(1f);
assertThat(window.liveConfiguration.maxPlaybackSpeed).isEqualTo(1f);
assertThat(window.defaultPositionUs).isEqualTo(4000000);
}
@Test
public void loadLivePlaylist_holdBackInPlaylist_targetLiveOffsetFromHoldBack()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds and a hold back of 12 seconds.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12";
// The playlist finishes 1 second before the current time, therefore there's a live edge
// offset of 1 second.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from hold back and then expressed in relation to the live
// edge (+1 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(13000);
assertThat(window.liveConfiguration.minPlaybackSpeed).isEqualTo(C.RATE_UNSET);
assertThat(window.liveConfiguration.maxPlaybackSpeed).isEqualTo(C.RATE_UNSET);
assertThat(window.defaultPositionUs).isEqualTo(4000000);
}
@Test
public void
loadLivePlaylist_partHoldBackWithoutPartInformationInPlaylist_targetLiveOffsetFromHoldBack()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a part hold back but not EXT-X-PART-INF. We should pick up the hold back.
// The duration of the playlist is 16 seconds so that the defined hold back is within the live
// window.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from hold back and then expressed in relation to the live
// edge (+1 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(13000);
assertThat(window.liveConfiguration.minPlaybackSpeed).isEqualTo(C.RATE_UNSET);
assertThat(window.liveConfiguration.maxPlaybackSpeed).isEqualTo(C.RATE_UNSET);
assertThat(window.defaultPositionUs).isEqualTo(4000000);
}
@Test
public void
loadLivePlaylist_partHoldBackWithPartInformationInPlaylist_targetLiveOffsetFromPartHoldBack()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 4 seconds, part hold back and EXT-X-PART-INF defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXT-X-PART-INF:PART-TARGET=0.5\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:05.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from part hold back and then expressed in relation to the
// live edge (+1 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(4000);
assertThat(window.liveConfiguration.minPlaybackSpeed).isEqualTo(C.RATE_UNSET);
assertThat(window.liveConfiguration.maxPlaybackSpeed).isEqualTo(C.RATE_UNSET);
assertThat(window.defaultPositionUs).isEqualTo(0);
}
@Test
public void loadLivePlaylist_withParts_defaultPositionPointsAtClosestIndependentPart()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 7 seconds, part hold back and EXT-X-PART-INF defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=2\n"
+ "#EXT-X-PART-INF:PART-TARGET=0.5\n"
+ "#EXT-X-PART:DURATION=0.5000,URI=\"fileSequence1.0.ts\",INDEPENDENT=YES\n"
+ "#EXT-X-PART:DURATION=0.5000,URI=\"fileSequence1.1.ts\"\n"
+ "#EXT-X-PART:DURATION=0.5000,URI=\"fileSequence1.2.ts\",INDEPENDENT=YES\n"
+ "#EXT-X-PART:DURATION=0.5000,URI=\"fileSequence1.3.ts\"\n"
+ "#EXT-X-PART:DURATION=0.5000,URI=\"fileSequence1.4.ts\",INDEPENDENT=YES\n"
+ "#EXT-X-PART:DURATION=0.5000,URI=\"fileSequence1.5.ts\"";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:08.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from part hold back and then expressed in relation to the
// live edge (+1 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(3000);
// The default position points the closest preceding independent part.
assertThat(window.defaultPositionUs).isEqualTo(5000000);
}
@Test
public void loadLivePlaylist_withNonPreciseStartTime_targetLiveOffsetFromStartTime()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds, and part hold back, hold back and start time
// defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-START:TIME-OFFSET=-10\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3\n";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from start time (16 - 10 = 6) and then expressed in relation
// to the live edge (17 - 6 = 11 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(11000);
// The default position points to the segment containing the start time.
assertThat(window.defaultPositionUs).isEqualTo(4000000);
}
@Test
public void
loadLivePlaylist_withNonPreciseStartTimeAndUserDefinedLiveOffset_startsFromPrecedingSegment()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds, and part hold back, hold back and start time
// defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-START:TIME-OFFSET=-10\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3\n";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(playlistUri)
.setLiveConfiguration(
new MediaItem.LiveConfiguration.Builder().setTargetOffsetMs(3000).build())
.build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(3000);
// The default position points to the segment containing the start time.
assertThat(window.defaultPositionUs).isEqualTo(4000000);
}
@Test
public void loadLivePlaylist_withPreciseStartTime_targetLiveOffsetFromStartTime()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds, and part hold back, hold back and start time
// defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-START:TIME-OFFSET=-10,PRECISE=YES\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = MediaItem.fromUri(playlistUri);
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from start time (16 - 10 = 6) and then expressed in relation
// to the live edge (17 - 7 = 11 seconds).
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(11000);
// The default position points to the start time.
assertThat(window.defaultPositionUs).isEqualTo(6000000);
}
@Test
public void loadLivePlaylist_withPreciseStartTimeAndUserDefinedLiveOffset_startsFromStartTime()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds, and part hold back, hold back and start time
// defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-START:TIME-OFFSET=-10,PRECISE=YES\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3";
// The playlist finishes 1 second before the current time.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:17.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(playlistUri)
.setLiveConfiguration(
new MediaItem.LiveConfiguration.Builder().setTargetOffsetMs(3000).build())
.build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(3000);
// The default position points to the start time.
assertThat(window.defaultPositionUs).isEqualTo(6000000);
}
@Test
public void loadLivePlaylist_targetLiveOffsetInMediaItem_targetLiveOffsetPickedFromMediaItem()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a hold back of 12 seconds and a part hold back of 3 seconds.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12,PART-HOLD-BACK=3";
// The playlist finishes 1 second before the current time. This should not affect the target
// live offset set in the media item.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:05.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(playlistUri)
.setLiveConfiguration(
new MediaItem.LiveConfiguration.Builder().setTargetOffsetMs(1000).build())
.build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is picked from the media item and not adjusted.
assertThat(window.liveConfiguration).isEqualTo(mediaItem.liveConfiguration);
assertThat(window.defaultPositionUs).isEqualTo(0);
}
@Test
public void loadLivePlaylist_noHoldBackInPlaylistAndNoPlaybackSpeedInMediaItem_usesUnitSpeed()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has no hold back defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts";
// The playlist finishes 1 second before the current time. This should not affect the target
// live offset set in the media item.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:05.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(playlistUri)
.setLiveConfiguration(
new MediaItem.LiveConfiguration.Builder().setTargetOffsetMs(1000).build())
.build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(window.liveConfiguration.minPlaybackSpeed).isEqualTo(1f);
assertThat(window.liveConfiguration.maxPlaybackSpeed).isEqualTo(1f);
assertThat(window.defaultPositionUs).isEqualTo(0);
}
@Test
public void
loadLivePlaylist_noHoldBackInPlaylistAndPlaybackSpeedInMediaItem_usesMediaItemConfiguration()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has no hold back defined.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts";
// The playlist finishes 1 second before the current time. This should not affect the target
// live offset set in the media item.
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:05.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(playlistUri)
.setLiveConfiguration(
new MediaItem.LiveConfiguration.Builder()
.setTargetOffsetMs(1000)
.setMinPlaybackSpeed(0.94f)
.setMaxPlaybackSpeed(1.02f)
.build())
.build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(window.liveConfiguration).isEqualTo(mediaItem.liveConfiguration);
assertThat(window.defaultPositionUs).isEqualTo(0);
}
@Test
public void
loadLivePlaylist_targetLiveOffsetLargerThanLiveWindow_targetLiveOffsetIsWithinLiveWindow()
throws TimeoutException, ParserException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 8 seconds and a hold back of 12 seconds.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PROGRAM-DATE-TIME:2020-01-01T00:00:00.0+00:00\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXT-X-SERVER-CONTROL:CAN-SKIP-UNTIL=24";
// The playlist finishes 1 second before the live edge, therefore the live window duration is
// 9 seconds (8 + 1).
SystemClock.setCurrentTimeMillis(Util.parseXsDateTime("2020-01-01T00:00:09.0+00:00"));
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem =
new MediaItem.Builder()
.setUri(playlistUri)
.setLiveConfiguration(
new MediaItem.LiveConfiguration.Builder().setTargetOffsetMs(20_000).build())
.build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(mediaItem.liveConfiguration.targetOffsetMs)
.isGreaterThan(Util.usToMs(window.durationUs));
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(9000);
}
@Test
public void
loadLivePlaylist_withoutProgramDateTime_targetLiveOffsetFromPlaylistNotAdjustedToLiveEdge()
throws TimeoutException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
// The playlist has a duration of 16 seconds and a hold back of 12 seconds.
String playlist =
"#EXTM3U\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK=12";
// The playlist finishes 8 seconds before the current time.
SystemClock.setCurrentTimeMillis(20000);
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = new MediaItem.Builder().setUri(playlistUri).build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is not adjusted to the live edge because the list does not have
// program date time.
assertThat(window.liveConfiguration.targetOffsetMs).isEqualTo(12000);
assertThat(window.defaultPositionUs).isEqualTo(4000000);
}
@Test
public void loadOnDemandPlaylist_withPreciseStartTime_setsDefaultPosition()
throws TimeoutException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PLAYLIST-TYPE:VOD\n"
+ "#EXT-X-TARGETDURATION:10\n"
+ "#EXT-X-VERSION:4\n"
+ "#EXT-X-START:TIME-OFFSET=15.000,PRECISE=YES"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence2.ts\n"
+ "#EXT-X-ENDLIST";
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = new MediaItem.Builder().setUri(playlistUri).build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is not adjusted to the live edge because the list does not have
// program date time.
assertThat(window.liveConfiguration).isNull();
assertThat(window.defaultPositionUs).isEqualTo(15000000);
}
@Test
public void loadOnDemandPlaylist_withNonPreciseStartTime_setsDefaultPosition()
throws TimeoutException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PLAYLIST-TYPE:VOD\n"
+ "#EXT-X-TARGETDURATION:10\n"
+ "#EXT-X-VERSION:4\n"
+ "#EXT-X-START:TIME-OFFSET=15.000"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence2.ts\n"
+ "#EXT-X-ENDLIST";
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = new MediaItem.Builder().setUri(playlistUri).build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
// The target live offset is not adjusted to the live edge because the list does not have
// program date time.
assertThat(window.liveConfiguration).isNull();
assertThat(window.defaultPositionUs).isEqualTo(10000000);
}
@Test
public void
loadOnDemandPlaylist_withStartTimeBeforeTheBeginning_setsDefaultPositionToTheBeginning()
throws TimeoutException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PLAYLIST-TYPE:VOD\n"
+ "#EXT-X-TARGETDURATION:10\n"
+ "#EXT-X-VERSION:4\n"
+ "#EXT-X-START:TIME-OFFSET=-35.000"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence2.ts\n"
+ "#EXT-X-ENDLIST";
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = new MediaItem.Builder().setUri(playlistUri).build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(window.liveConfiguration).isNull();
assertThat(window.defaultPositionUs).isEqualTo(0);
}
@Test
public void loadOnDemandPlaylist_withStartTimeAfterTheNed_setsDefaultPositionToTheEnd()
throws TimeoutException {
String playlistUri = "fake://foo.bar/media0/playlist.m3u8";
String playlist =
"#EXTM3U\n"
+ "#EXT-X-PLAYLIST-TYPE:VOD\n"
+ "#EXT-X-TARGETDURATION:10\n"
+ "#EXT-X-VERSION:4\n"
+ "#EXT-X-START:TIME-OFFSET=35.000"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:10.0,\n"
+ "fileSequence2.ts\n"
+ "#EXT-X-ENDLIST";
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri, playlist);
MediaItem mediaItem = new MediaItem.Builder().setUri(playlistUri).build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
Timeline timeline = prepareAndWaitForTimeline(mediaSource);
Timeline.Window window = timeline.getWindow(0, new Timeline.Window());
assertThat(window.liveConfiguration).isNull();
assertThat(window.defaultPositionUs).isEqualTo(20000000);
}
@Test
public void refreshPlaylist_targetLiveOffsetRemainsInWindow()
throws TimeoutException, IOException {
String playlistUri1 = "fake://foo.bar/media0/playlist1.m3u8";
// The playlist has a duration of 16 seconds and a hold back of 12 seconds.
String playlist1 =
"#EXTM3U\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:0\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence0.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence1.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence2.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence3.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK:12";
// The second playlist defines a different hold back.
String playlistUri2 = "fake://foo.bar/media0/playlist2.m3u8";
String playlist2 =
"#EXTM3U\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:4\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence4.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence5.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence6.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence7.ts\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK:14";
// The third playlist has a duration of 8 seconds.
String playlistUri3 = "fake://foo.bar/media0/playlist3.m3u8";
String playlist3 =
"#EXTM3U\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:4\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence8.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence9.ts\n"
+ "#EXTINF:4.00000,\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK:12";
// The third playlist has a duration of 16 seconds but the target live offset should remain at
// 8 seconds.
String playlistUri4 = "fake://foo.bar/media0/playlist4.m3u8";
String playlist4 =
"#EXTM3U\n"
+ "#EXT-X-TARGETDURATION:4\n"
+ "#EXT-X-VERSION:3\n"
+ "#EXT-X-MEDIA-SEQUENCE:4\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence10.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence11.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence12.ts\n"
+ "#EXTINF:4.00000,\n"
+ "fileSequence13.ts\n"
+ "#EXTINF:4.00000,\n"
+ "#EXT-X-SERVER-CONTROL:HOLD-BACK:12";
HlsMediaSource.Factory factory = createHlsMediaSourceFactory(playlistUri1, playlist1);
MediaItem mediaItem = new MediaItem.Builder().setUri(playlistUri1).build();
HlsMediaSource mediaSource = factory.createMediaSource(mediaItem);
HlsMediaPlaylist secondPlaylist = parseHlsMediaPlaylist(playlistUri2, playlist2);
HlsMediaPlaylist thirdPlaylist = parseHlsMediaPlaylist(playlistUri3, playlist3);
HlsMediaPlaylist fourthPlaylist = parseHlsMediaPlaylist(playlistUri4, playlist4);
List<Timeline> timelines = new ArrayList<>();
MediaSource.MediaSourceCaller mediaSourceCaller = (source, timeline) -> timelines.add(timeline);
mediaSource.prepareSource(mediaSourceCaller, /* mediaTransferListener= */ null, PlayerId.UNSET);
runMainLooperUntil(() -> timelines.size() == 1);
mediaSource.onPrimaryPlaylistRefreshed(secondPlaylist);
runMainLooperUntil(() -> timelines.size() == 2);
mediaSource.onPrimaryPlaylistRefreshed(thirdPlaylist);
runMainLooperUntil(() -> timelines.size() == 3);
mediaSource.onPrimaryPlaylistRefreshed(fourthPlaylist);
runMainLooperUntil(() -> timelines.size() == 4);
Timeline.Window window = new Timeline.Window();
assertThat(timelines.get(0).getWindow(0, window).liveConfiguration.targetOffsetMs)
.isEqualTo(12000);
assertThat(timelines.get(1).getWindow(0, window).liveConfiguration.targetOffsetMs)
.isEqualTo(12000);
assertThat(timelines.get(2).getWindow(0, window).liveConfiguration.targetOffsetMs)
.isEqualTo(8000);
assertThat(timelines.get(3).getWindow(0, window).liveConfiguration.targetOffsetMs)
.isEqualTo(8000);
}
private static HlsMediaSource.Factory createHlsMediaSourceFactory(
String playlistUri, String playlist) {
FakeDataSet fakeDataSet = new FakeDataSet().setData(playlistUri, Util.getUtf8Bytes(playlist));
return new HlsMediaSource.Factory(
dataType -> new FakeDataSource.Factory().setFakeDataSet(fakeDataSet).createDataSource())
.setElapsedRealTimeOffsetMs(0);
}
/** Prepares the media source and waits until the timeline is updated. */
private static Timeline prepareAndWaitForTimeline(HlsMediaSource mediaSource)
throws TimeoutException {
AtomicReference<Timeline> receivedTimeline = new AtomicReference<>();
mediaSource.prepareSource(
(source, timeline) -> receivedTimeline.set(timeline),
/* mediaTransferListener= */ null,
PlayerId.UNSET);
runMainLooperUntil(() -> receivedTimeline.get() != null);
return receivedTimeline.get();
}
private static HlsMediaPlaylist parseHlsMediaPlaylist(String playlistUri, String playlist)
throws IOException {
return (HlsMediaPlaylist)
new HlsPlaylistParser()
.parse(Uri.parse(playlistUri), new ByteArrayInputStream(Util.getUtf8Bytes(playlist)));
}
}
|
googleapis/google-cloud-java | 37,351 | java-maps-mapsplatformdatasets/proto-google-maps-mapsplatformdatasets-v1/src/main/java/com/google/maps/mapsplatformdatasets/v1/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/maps/mapsplatformdatasets/v1/maps_platform_datasets.proto
// Protobuf Java Version: 3.25.8
package com.google.maps.mapsplatformdatasets.v1;
/**
*
*
* <pre>
* Request to list datasets for the project.
* </pre>
*
* Protobuf type {@code google.maps.mapsplatformdatasets.v1.ListDatasetsRequest}
*/
public final class ListDatasetsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.maps.mapsplatformdatasets.v1.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_ = "";
pageToken_ = "";
tag_ = "";
}
@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.maps.mapsplatformdatasets.v1.MapsPlatformDatasetsProto
.internal_static_google_maps_mapsplatformdatasets_v1_ListDatasetsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.maps.mapsplatformdatasets.v1.MapsPlatformDatasetsProto
.internal_static_google_maps_mapsplatformdatasets_v1_ListDatasetsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest.class,
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of datasets to return per page.
*
* If unspecified (or zero), all datasets will be returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TAG_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object tag_ = "";
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @return The tag.
*/
@java.lang.Override
public java.lang.String getTag() {
java.lang.Object ref = tag_;
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();
tag_ = s;
return s;
}
}
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @return The bytes for tag.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTagBytes() {
java.lang.Object ref = tag_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
tag_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tag_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, tag_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tag_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, tag_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest)) {
return super.equals(obj);
}
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest other =
(com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getTag().equals(other.getTag())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + TAG_FIELD_NUMBER;
hash = (53 * hash) + getTag().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.maps.mapsplatformdatasets.v1.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.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.maps.mapsplatformdatasets.v1.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.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.maps.mapsplatformdatasets.v1.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.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.maps.mapsplatformdatasets.v1.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.maps.mapsplatformdatasets.v1.ListDatasetsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.maps.mapsplatformdatasets.v1.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.maps.mapsplatformdatasets.v1.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 to list datasets for the project.
* </pre>
*
* Protobuf type {@code google.maps.mapsplatformdatasets.v1.ListDatasetsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.maps.mapsplatformdatasets.v1.ListDatasetsRequest)
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.maps.mapsplatformdatasets.v1.MapsPlatformDatasetsProto
.internal_static_google_maps_mapsplatformdatasets_v1_ListDatasetsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.maps.mapsplatformdatasets.v1.MapsPlatformDatasetsProto
.internal_static_google_maps_mapsplatformdatasets_v1_ListDatasetsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest.class,
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest.Builder.class);
}
// Construct using com.google.maps.mapsplatformdatasets.v1.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_ = "";
pageSize_ = 0;
pageToken_ = "";
tag_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.maps.mapsplatformdatasets.v1.MapsPlatformDatasetsProto
.internal_static_google_maps_mapsplatformdatasets_v1_ListDatasetsRequest_descriptor;
}
@java.lang.Override
public com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest getDefaultInstanceForType() {
return com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest build() {
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest buildPartial() {
com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest result =
new com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.tag_ = tag_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest) {
return mergeFrom((com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest other) {
if (other == com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getTag().isEmpty()) {
tag_ = other.tag_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
tag_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the project to list all the datasets for.
* Format: projects/{project}
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of datasets to return per page.
*
* If unspecified (or zero), all datasets will be returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of datasets to return per page.
*
* If unspecified (or zero), all datasets will be returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of datasets to return per page.
*
* If unspecified (or zero), all datasets will be returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The page token, received from a previous ListDatasets call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object tag_ = "";
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @return The tag.
*/
public java.lang.String getTag() {
java.lang.Object ref = tag_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
tag_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @return The bytes for tag.
*/
public com.google.protobuf.ByteString getTagBytes() {
java.lang.Object ref = tag_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
tag_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @param value The tag to set.
* @return This builder for chaining.
*/
public Builder setTag(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
tag_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearTag() {
tag_ = getDefaultInstance().getTag();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* The tag that specifies the desired version for each dataset.
*
* Note that when pagination is also specified, some filtering can happen
* after pagination, which may cause the response to contain fewer datasets
* than the page size, even if it's not the last page.
*
* Tag "active": Each dataset in the response will include the info of its
* latest completed version, and the dataset will be skipped if it does not
* have one.
* </pre>
*
* <code>string tag = 4;</code>
*
* @param value The bytes for tag to set.
* @return This builder for chaining.
*/
public Builder setTagBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
tag_ = 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.maps.mapsplatformdatasets.v1.ListDatasetsRequest)
}
// @@protoc_insertion_point(class_scope:google.maps.mapsplatformdatasets.v1.ListDatasetsRequest)
private static final com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.maps.mapsplatformdatasets.v1.ListDatasetsRequest();
}
public static com.google.maps.mapsplatformdatasets.v1.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.maps.mapsplatformdatasets.v1.ListDatasetsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,477 | java-accesscontextmanager/proto-google-identity-accesscontextmanager-v1/src/main/java/com/google/identity/accesscontextmanager/v1/UpdateAccessLevelRequest.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/identity/accesscontextmanager/v1/access_context_manager.proto
// Protobuf Java Version: 3.25.8
package com.google.identity.accesscontextmanager.v1;
/**
*
*
* <pre>
* A request to update an `AccessLevel`.
* </pre>
*
* Protobuf type {@code google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest}
*/
public final class UpdateAccessLevelRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest)
UpdateAccessLevelRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateAccessLevelRequest.newBuilder() to construct.
private UpdateAccessLevelRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateAccessLevelRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateAccessLevelRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.identity.accesscontextmanager.v1.AccessContextManagerProto
.internal_static_google_identity_accesscontextmanager_v1_UpdateAccessLevelRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.identity.accesscontextmanager.v1.AccessContextManagerProto
.internal_static_google_identity_accesscontextmanager_v1_UpdateAccessLevelRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest.class,
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest.Builder.class);
}
private int bitField0_;
public static final int ACCESS_LEVEL_FIELD_NUMBER = 1;
private com.google.identity.accesscontextmanager.v1.AccessLevel accessLevel_;
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the accessLevel field is set.
*/
@java.lang.Override
public boolean hasAccessLevel() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The accessLevel.
*/
@java.lang.Override
public com.google.identity.accesscontextmanager.v1.AccessLevel getAccessLevel() {
return accessLevel_ == null
? com.google.identity.accesscontextmanager.v1.AccessLevel.getDefaultInstance()
: accessLevel_;
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.identity.accesscontextmanager.v1.AccessLevelOrBuilder
getAccessLevelOrBuilder() {
return accessLevel_ == null
? com.google.identity.accesscontextmanager.v1.AccessLevel.getDefaultInstance()
: accessLevel_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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, getAccessLevel());
}
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, getAccessLevel());
}
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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest)) {
return super.equals(obj);
}
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest other =
(com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest) obj;
if (hasAccessLevel() != other.hasAccessLevel()) return false;
if (hasAccessLevel()) {
if (!getAccessLevel().equals(other.getAccessLevel())) 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 (hasAccessLevel()) {
hash = (37 * hash) + ACCESS_LEVEL_FIELD_NUMBER;
hash = (53 * hash) + getAccessLevel().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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest 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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest 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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest 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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request to update an `AccessLevel`.
* </pre>
*
* Protobuf type {@code google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest)
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.identity.accesscontextmanager.v1.AccessContextManagerProto
.internal_static_google_identity_accesscontextmanager_v1_UpdateAccessLevelRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.identity.accesscontextmanager.v1.AccessContextManagerProto
.internal_static_google_identity_accesscontextmanager_v1_UpdateAccessLevelRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest.class,
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest.Builder.class);
}
// Construct using
// com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getAccessLevelFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
accessLevel_ = null;
if (accessLevelBuilder_ != null) {
accessLevelBuilder_.dispose();
accessLevelBuilder_ = 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.identity.accesscontextmanager.v1.AccessContextManagerProto
.internal_static_google_identity_accesscontextmanager_v1_UpdateAccessLevelRequest_descriptor;
}
@java.lang.Override
public com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
getDefaultInstanceForType() {
return com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest build() {
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest buildPartial() {
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest result =
new com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.accessLevel_ =
accessLevelBuilder_ == null ? accessLevel_ : accessLevelBuilder_.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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest) {
return mergeFrom(
(com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest other) {
if (other
== com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
.getDefaultInstance()) return this;
if (other.hasAccessLevel()) {
mergeAccessLevel(other.getAccessLevel());
}
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(getAccessLevelFieldBuilder().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.identity.accesscontextmanager.v1.AccessLevel accessLevel_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.identity.accesscontextmanager.v1.AccessLevel,
com.google.identity.accesscontextmanager.v1.AccessLevel.Builder,
com.google.identity.accesscontextmanager.v1.AccessLevelOrBuilder>
accessLevelBuilder_;
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the accessLevel field is set.
*/
public boolean hasAccessLevel() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The accessLevel.
*/
public com.google.identity.accesscontextmanager.v1.AccessLevel getAccessLevel() {
if (accessLevelBuilder_ == null) {
return accessLevel_ == null
? com.google.identity.accesscontextmanager.v1.AccessLevel.getDefaultInstance()
: accessLevel_;
} else {
return accessLevelBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAccessLevel(com.google.identity.accesscontextmanager.v1.AccessLevel value) {
if (accessLevelBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
accessLevel_ = value;
} else {
accessLevelBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAccessLevel(
com.google.identity.accesscontextmanager.v1.AccessLevel.Builder builderForValue) {
if (accessLevelBuilder_ == null) {
accessLevel_ = builderForValue.build();
} else {
accessLevelBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeAccessLevel(com.google.identity.accesscontextmanager.v1.AccessLevel value) {
if (accessLevelBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& accessLevel_ != null
&& accessLevel_
!= com.google.identity.accesscontextmanager.v1.AccessLevel.getDefaultInstance()) {
getAccessLevelBuilder().mergeFrom(value);
} else {
accessLevel_ = value;
}
} else {
accessLevelBuilder_.mergeFrom(value);
}
if (accessLevel_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearAccessLevel() {
bitField0_ = (bitField0_ & ~0x00000001);
accessLevel_ = null;
if (accessLevelBuilder_ != null) {
accessLevelBuilder_.dispose();
accessLevelBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.identity.accesscontextmanager.v1.AccessLevel.Builder getAccessLevelBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getAccessLevelFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.identity.accesscontextmanager.v1.AccessLevelOrBuilder
getAccessLevelOrBuilder() {
if (accessLevelBuilder_ != null) {
return accessLevelBuilder_.getMessageOrBuilder();
} else {
return accessLevel_ == null
? com.google.identity.accesscontextmanager.v1.AccessLevel.getDefaultInstance()
: accessLevel_;
}
}
/**
*
*
* <pre>
* Required. The updated [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel]. Syntactic
* correctness of the [Access Level]
* [google.identity.accesscontextmanager.v1.AccessLevel] is a
* precondition for creation.
* </pre>
*
* <code>
* .google.identity.accesscontextmanager.v1.AccessLevel access_level = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.identity.accesscontextmanager.v1.AccessLevel,
com.google.identity.accesscontextmanager.v1.AccessLevel.Builder,
com.google.identity.accesscontextmanager.v1.AccessLevelOrBuilder>
getAccessLevelFieldBuilder() {
if (accessLevelBuilder_ == null) {
accessLevelBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.identity.accesscontextmanager.v1.AccessLevel,
com.google.identity.accesscontextmanager.v1.AccessLevel.Builder,
com.google.identity.accesscontextmanager.v1.AccessLevelOrBuilder>(
getAccessLevel(), getParentForChildren(), isClean());
accessLevel_ = null;
}
return accessLevelBuilder_;
}
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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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. Mask to control which fields get updated. Must be non-empty.
* </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.identity.accesscontextmanager.v1.UpdateAccessLevelRequest)
}
// @@protoc_insertion_point(class_scope:google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest)
private static final com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest();
}
public static com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateAccessLevelRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateAccessLevelRequest>() {
@java.lang.Override
public UpdateAccessLevelRequest 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<UpdateAccessLevelRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateAccessLevelRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.identity.accesscontextmanager.v1.UpdateAccessLevelRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hudi | 37,606 | hudi-common/src/main/java/org/apache/hudi/avro/AvroSchemaCompatibility.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.avro;
import org.apache.hudi.common.util.Either;
import org.apache.hudi.common.util.Option;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import static org.apache.hudi.avro.HoodieAvroUtils.isTypeNumeric;
import static org.apache.hudi.common.util.ValidationUtils.checkState;
/**
* Evaluate the compatibility between a reader schema and a writer schema. A
* reader and a writer schema are declared compatible if all datum instances of
* the writer schema can be successfully decoded using the specified reader
* schema.
* <p>
* NOTE: PLEASE READ CAREFULLY BEFORE CHANGING
* <p>
* This code is borrowed from Avro 1.10, with the following modifications:
* <ol>
* <li>Compatibility checks ignore schema name, unless schema is held inside
* a union</li>
* </ol>
*/
public class AvroSchemaCompatibility {
private static final Logger LOG = LoggerFactory.getLogger(AvroSchemaCompatibility.class);
/**
* Utility class cannot be instantiated.
*/
private AvroSchemaCompatibility() {
}
/**
* Message to annotate reader/writer schema pairs that are compatible.
*/
public static final String READER_WRITER_COMPATIBLE_MESSAGE = "Reader schema can always successfully decode data written using the writer schema.";
/**
* Validates that the provided reader schema can be used to decode avro data
* written with the provided writer schema.
*
* @param reader schema to check.
* @param writer schema to check.
* @return a result object identifying any compatibility errors.
*/
public static SchemaPairCompatibility checkReaderWriterCompatibility(final Schema reader,
final Schema writer,
boolean checkNamingOverride) {
final SchemaCompatibilityResult compatibility =
new ReaderWriterCompatibilityChecker(checkNamingOverride).getCompatibility(reader, writer);
final String message;
switch (compatibility.getCompatibility()) {
case INCOMPATIBLE: {
message = String.format(
"Data encoded using writer schema:%n%s%n" + "will or may fail to decode using reader schema:%n%s%n",
writer.toString(true), reader.toString(true));
break;
}
case COMPATIBLE: {
message = READER_WRITER_COMPATIBLE_MESSAGE;
break;
}
default:
throw new AvroRuntimeException("Unknown compatibility: " + compatibility);
}
return new SchemaPairCompatibility(compatibility, reader, writer, message);
}
// -----------------------------------------------------------------------------------------------
/**
* Tests the equality of two Avro named schemas.
*
* <p>
* Matching includes reader name aliases.
* </p>
*
* @param reader Named reader schema.
* @param writer Named writer schema.
* @return whether the names of the named schemas match or not.
*/
public static boolean schemaNameEquals(final Schema reader, final Schema writer) {
if (objectsEqual(reader.getName(), writer.getName())) {
return true;
}
// Apply reader aliases:
return reader.getAliases().contains(writer.getFullName());
}
/**
* Identifies the writer field that corresponds to the specified reader field.
*
* <p>
* Matching includes reader name aliases.
* </p>
*
* @param writerSchema Schema of the record where to look for the writer field.
* @param readerField Reader field to identify the corresponding writer field
* of.
* @return the writer field, if any does correspond, or None.
*/
public static Field lookupWriterField(final Schema writerSchema, final Field readerField) {
assert (writerSchema.getType() == Type.RECORD);
final List<Field> writerFields = new ArrayList<>();
final Field direct = writerSchema.getField(readerField.name());
if (direct != null) {
writerFields.add(direct);
}
for (final String readerFieldAliasName : readerField.aliases()) {
final Field writerField = writerSchema.getField(readerFieldAliasName);
if (writerField != null) {
writerFields.add(writerField);
}
}
switch (writerFields.size()) {
case 0:
return null;
case 1:
return writerFields.get(0);
default: {
throw new AvroRuntimeException(String.format(
"Reader record field %s matches multiple fields in writer record schema %s", readerField, writerSchema));
}
}
}
/**
* Reader/writer schema pair that can be used as a key in a hash map.
* <p>
* This reader/writer pair differentiates Schema objects based on their system
* hash code.
*/
private static final class ReaderWriter {
private final Schema mReader;
private final Schema mWriter;
/**
* Initializes a new reader/writer pair.
*
* @param reader Reader schema.
* @param writer Writer schema.
*/
public ReaderWriter(final Schema reader, final Schema writer) {
mReader = reader;
mWriter = writer;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return System.identityHashCode(mReader) ^ System.identityHashCode(mWriter);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ReaderWriter)) {
return false;
}
final ReaderWriter that = (ReaderWriter) obj;
// Use pointer comparison here:
return (this.mReader == that.mReader) && (this.mWriter == that.mWriter);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("ReaderWriter{reader:%s, writer:%s}", mReader, mWriter);
}
}
/**
* Determines the compatibility of a reader/writer schema pair.
*
* <p>
* Provides memoization to handle recursive schemas.
* </p>
*/
private static final class ReaderWriterCompatibilityChecker {
private final AvroDefaultValueAccessor defaultValueAccessor = new AvroDefaultValueAccessor();
private final Map<ReaderWriter, SchemaCompatibilityResult> mMemoizeMap = new HashMap<>();
private final boolean checkNaming;
public ReaderWriterCompatibilityChecker(boolean checkNaming) {
this.checkNaming = checkNaming;
}
/**
* Reports the compatibility of a reader/writer schema pair.
*
* <p>
* Memorizes the compatibility results.
* </p>
*
* @param reader Reader schema to test.
* @param writer Writer schema to test.
* @return the compatibility of the reader/writer schema pair.
*/
public SchemaCompatibilityResult getCompatibility(final Schema reader, final Schema writer) {
ArrayDeque<LocationInfo> locations = new ArrayDeque<>(
Collections.singletonList(new LocationInfo(reader.getName(), reader.getType()))
);
return getCompatibility(reader, writer, locations);
}
/**
* Reports the compatibility of a reader/writer schema pair.
* <p>
* Memorizes the compatibility results.
* </p>
*
* @param reader Reader schema to test.
* @param writer Writer schema to test.
* @param locations Stack tracking the path (chain of locations) within the
* schema.
* @return the compatibility of the reader/writer schema pair.
*/
private SchemaCompatibilityResult getCompatibility(final Schema reader,
final Schema writer,
final Deque<LocationInfo> locations) {
LOG.debug("Checking compatibility of reader {} with writer {}", reader, writer);
final ReaderWriter pair = new ReaderWriter(reader, writer);
SchemaCompatibilityResult result = mMemoizeMap.get(pair);
if (result != null) {
if (result.getCompatibility() == SchemaCompatibilityType.RECURSION_IN_PROGRESS) {
// Break the recursion here.
// schemas are compatible unless proven incompatible:
result = SchemaCompatibilityResult.compatible();
}
} else {
// Mark this reader/writer pair as "in progress":
mMemoizeMap.put(pair, SchemaCompatibilityResult.recursionInProgress());
result = calculateCompatibility(reader, writer, locations);
mMemoizeMap.put(pair, result);
}
return result;
}
private static String getLocationName(final Deque<LocationInfo> locations, Type readerType) {
StringBuilder sb = new StringBuilder();
Iterator<LocationInfo> locationInfoIterator = locations.iterator();
boolean addDot = false;
while (locationInfoIterator.hasNext()) {
if (addDot) {
sb.append(".");
} else {
addDot = true;
}
LocationInfo next = locationInfoIterator.next();
sb.append(next.name);
//we check the reader type if we are at the last location. This is because
//if the type is array/map, that means the problem is that the field type
//of the writer is not array/map. If the type is something else, the problem
//is between the array element/map value of the reader and writer schemas
if (next.type.equals(Type.MAP)) {
if (locationInfoIterator.hasNext() || !readerType.equals(Type.MAP)) {
sb.append(".value");
}
} else if (next.type.equals(Type.ARRAY)) {
if (locationInfoIterator.hasNext() || !readerType.equals(Type.ARRAY)) {
sb.append(".element");
}
}
}
return sb.toString();
}
/**
* Calculates the compatibility of a reader/writer schema pair.
*
* <p>
* Relies on external memoization performed by
* {@link #getCompatibility(Schema, Schema)}.
* </p>
*
* @param reader Reader schema to test.
* @param writer Writer schema to test.
* @param locations Stack with which to track the location within the schema.
* @return the compatibility of the reader/writer schema pair.
*/
private SchemaCompatibilityResult calculateCompatibility(final Schema reader, final Schema writer,
final Deque<LocationInfo> locations) {
SchemaCompatibilityResult result = SchemaCompatibilityResult.compatible();
if (reader.getType() == writer.getType()) {
switch (reader.getType()) {
case NULL:
case BOOLEAN:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case BYTES:
case STRING: {
return result;
}
case ARRAY: {
return result.mergedWith(getCompatibility(reader.getElementType(), writer.getElementType(), locations));
}
case MAP: {
return result.mergedWith(getCompatibility(reader.getValueType(), writer.getValueType(), locations));
}
case FIXED: {
result = result.mergedWith(checkSchemaNames(reader, writer, locations));
return result.mergedWith(checkFixedSize(reader, writer, locations));
}
case ENUM: {
result = result.mergedWith(checkSchemaNames(reader, writer, locations));
return result.mergedWith(checkReaderEnumContainsAllWriterEnumSymbols(reader, writer, locations));
}
case RECORD: {
result = result.mergedWith(checkSchemaNames(reader, writer, locations));
return result.mergedWith(checkReaderWriterRecordFields(reader, writer, locations));
}
case UNION: {
// Check that each individual branch of the writer union can be decoded:
for (final Schema writerBranch : writer.getTypes()) {
SchemaCompatibilityResult compatibility = getCompatibility(reader, writerBranch, locations);
if (compatibility.getCompatibility() == SchemaCompatibilityType.INCOMPATIBLE) {
String message = String.format("reader union lacking writer type: %s for field: '%s'", writerBranch.getType(), getLocationName(locations, reader.getType()));
result = result.mergedWith(SchemaCompatibilityResult.incompatible(
SchemaIncompatibilityType.MISSING_UNION_BRANCH, reader, writer, message, asList(locations)));
}
}
// Each schema in the writer union can be decoded with the reader:
return result;
}
default: {
throw new AvroRuntimeException("Unknown schema type: " + reader.getType());
}
}
} else {
// Reader and writer have different schema types:
// Reader compatible with all branches of a writer union is compatible
if (writer.getType() == Schema.Type.UNION) {
for (Schema s : writer.getTypes()) {
result = result.mergedWith(getCompatibility(reader, s, locations));
}
return result;
}
switch (reader.getType()) {
case NULL:
return result.mergedWith(typeMismatch(reader, writer, locations));
case BOOLEAN:
return result.mergedWith(typeMismatch(reader, writer, locations));
case INT:
return result.mergedWith(typeMismatch(reader, writer, locations));
case LONG: {
return (writer.getType() == Type.INT) ? result : result.mergedWith(typeMismatch(reader, writer, locations));
}
case FLOAT: {
return ((writer.getType() == Type.INT) || (writer.getType() == Type.LONG)) ? result
: result.mergedWith(typeMismatch(reader, writer, locations));
}
case DOUBLE: {
return ((writer.getType() == Type.INT) || (writer.getType() == Type.LONG) || (writer.getType() == Type.FLOAT))
? result
: result.mergedWith(typeMismatch(reader, writer, locations));
}
case BYTES: {
return (writer.getType() == Type.STRING) ? result : result.mergedWith(typeMismatch(reader, writer, locations));
}
case STRING: {
return (isTypeNumeric(writer.getType()) || (writer.getType() == Schema.Type.BYTES)
? result : result.mergedWith(typeMismatch(reader, writer, locations)));
}
case ARRAY:
return result.mergedWith(typeMismatch(reader, writer, locations));
case MAP:
return result.mergedWith(typeMismatch(reader, writer, locations));
case FIXED:
return result.mergedWith(typeMismatch(reader, writer, locations));
case ENUM:
return result.mergedWith(typeMismatch(reader, writer, locations));
case RECORD:
return result.mergedWith(typeMismatch(reader, writer, locations));
case UNION: {
for (final Schema readerBranch : reader.getTypes()) {
SchemaCompatibilityResult compatibility = getCompatibility(readerBranch, writer, locations);
if (compatibility.getCompatibility() == SchemaCompatibilityType.COMPATIBLE) {
return result;
}
}
// No branch in the reader union has been found compatible with the writer
// schema:
String message = String.format("reader union lacking writer type: %s for field: '%s'", writer.getType(), getLocationName(locations, reader.getType()));
return result.mergedWith(SchemaCompatibilityResult
.incompatible(SchemaIncompatibilityType.MISSING_UNION_BRANCH, reader, writer, message, asList(locations)));
}
default: {
throw new AvroRuntimeException("Unknown schema type: " + reader.getType());
}
}
}
}
private SchemaCompatibilityResult checkReaderWriterRecordFields(final Schema reader, final Schema writer,
final Deque<LocationInfo> locations) {
SchemaCompatibilityResult result = SchemaCompatibilityResult.compatible();
// Check that each field in the reader record can be populated from the writer
// record:
for (final Field readerField : reader.getFields()) {
final Field writerField = lookupWriterField(writer, readerField);
if (writerField == null) {
// Reader field does not correspond to any field in the writer record schema, so
// the
// reader field must have a default value.
if (defaultValueAccessor.getDefaultValue(readerField) == null) {
// reader field has no default value
String message = String.format("Field '%s.%s' has no default value", getLocationName(locations, readerField.schema().getType()), readerField.name());
result = result.mergedWith(
SchemaCompatibilityResult.incompatible(SchemaIncompatibilityType.READER_FIELD_MISSING_DEFAULT_VALUE,
reader, writer, message, asList(locations)));
}
} else {
locations.addLast(new LocationInfo(readerField.name(), readerField.schema().getType()));
result = result.mergedWith(getCompatibility(readerField.schema(), writerField.schema(), locations));
locations.removeLast();
}
}
return result;
}
private static class AvroDefaultValueAccessor {
// Avro <= 1.8.2
private final Option<Method> legacyDefaultValueMethod = loadMethodNoThrow("defaultValue");
// Avro >= 1.10.0
private final Option<Method> newDefaultValueMethod = loadMethodNoThrow("defaultVal");
public Object getDefaultValue(Field field) {
return newDefaultValueMethod.or(legacyDefaultValueMethod)
.map(m -> invokeMethodNoThrow(m, field).asLeft())
.orElse(null);
}
private static Either<Object, Exception> invokeMethodNoThrow(Method m, Object obj, Object... args) {
try {
return Either.left(m.invoke(obj, args));
} catch (IllegalAccessException | InvocationTargetException e) {
return Either.right(e);
}
}
private static Option<Method> loadMethodNoThrow(String defaultValue) {
try {
return Option.of(Field.class.getMethod(defaultValue));
} catch (NoSuchMethodException e) {
return Option.empty();
}
}
}
private SchemaCompatibilityResult checkReaderEnumContainsAllWriterEnumSymbols(final Schema reader,
final Schema writer, final Deque<LocationInfo> locations) {
SchemaCompatibilityResult result = SchemaCompatibilityResult.compatible();
final Set<String> symbols = new TreeSet<>(writer.getEnumSymbols());
symbols.removeAll(reader.getEnumSymbols());
if (!symbols.isEmpty()) {
String message = String.format("Field '%s' missing enum symbols: %s", getLocationName(locations, reader.getType()), symbols);
result = SchemaCompatibilityResult.incompatible(SchemaIncompatibilityType.MISSING_ENUM_SYMBOLS, reader,
writer, message, asList(locations));
}
return result;
}
private SchemaCompatibilityResult checkFixedSize(final Schema reader, final Schema writer,
final Deque<LocationInfo> locations) {
SchemaCompatibilityResult result = SchemaCompatibilityResult.compatible();
int actual = reader.getFixedSize();
int expected = writer.getFixedSize();
if (actual != expected) {
String message = String.format("Fixed size field '%s' expected: %d, found: %d", getLocationName(locations, reader.getType()), expected, actual);
result = SchemaCompatibilityResult.incompatible(SchemaIncompatibilityType.FIXED_SIZE_MISMATCH, reader, writer,
message, asList(locations));
}
return result;
}
private SchemaCompatibilityResult checkSchemaNames(final Schema reader, final Schema writer,
final Deque<LocationInfo> locations) {
checkState(locations.size() > 0);
// NOTE: We're only going to validate schema names in following cases
// - This is a top-level schema (ie enclosing one)
// - This is a schema enclosed w/in a union (since in that case schemas could be
// reverse-looked up by their fully-qualified names)
boolean shouldCheckNames = checkNaming && (locations.size() == 1 || locations.peekLast().type == Type.UNION);
SchemaCompatibilityResult result = SchemaCompatibilityResult.compatible();
if (shouldCheckNames && !Objects.equals(reader.getFullName(), writer.getFullName())) {
String message = String.format("Reader schema name: '%s' is not compatible with writer schema name: '%s'", reader.getFullName(), writer.getFullName());
result = SchemaCompatibilityResult.incompatible(SchemaIncompatibilityType.NAME_MISMATCH, reader, writer,
message, asList(locations));
}
return result;
}
private SchemaCompatibilityResult typeMismatch(final Schema reader, final Schema writer,
final Deque<LocationInfo> locations) {
String message = String.format("reader type '%s' not compatible with writer type '%s' for field '%s'", reader.getType(),
writer.getType(), getLocationName(locations, reader.getType()));
return SchemaCompatibilityResult.incompatible(SchemaIncompatibilityType.TYPE_MISMATCH, reader, writer, message,
asList(locations));
}
public static class LocationInfo {
private final String name;
private final Type type;
public LocationInfo(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return String.format("%s:%s", name, type);
}
}
private static List<String> asList(Deque<LocationInfo> deque) {
List<String> list = deque.stream().map(locInfo -> locInfo.name).collect(Collectors.toList());
return Collections.unmodifiableList(list);
}
}
/**
* Identifies the type of schema compatibility result.
*/
public enum SchemaCompatibilityType {
COMPATIBLE, INCOMPATIBLE,
/**
* Used internally to tag a reader/writer schema pair and prevent recursion.
*/
RECURSION_IN_PROGRESS
}
public enum SchemaIncompatibilityType {
NAME_MISMATCH, FIXED_SIZE_MISMATCH, MISSING_ENUM_SYMBOLS, READER_FIELD_MISSING_DEFAULT_VALUE, TYPE_MISMATCH,
MISSING_UNION_BRANCH
}
/**
* Immutable class representing details about a particular schema pair
* compatibility check.
*/
public static final class SchemaCompatibilityResult {
/**
* Merges the current {@code SchemaCompatibilityResult} with the supplied result
* into a new instance, combining the list of
* {@code Incompatibility Incompatibilities} and regressing to the
* {@code SchemaCompatibilityType#INCOMPATIBLE INCOMPATIBLE} state if any
* incompatibilities are encountered.
*
* @param toMerge The {@code SchemaCompatibilityResult} to merge with the
* current instance.
* @return A {@code SchemaCompatibilityResult} that combines the state of the
* current and supplied instances.
*/
public SchemaCompatibilityResult mergedWith(SchemaCompatibilityResult toMerge) {
List<Incompatibility> mergedIncompatibilities = new ArrayList<>(mIncompatibilities);
mergedIncompatibilities.addAll(toMerge.getIncompatibilities());
SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE
? toMerge.mCompatibilityType
: SchemaCompatibilityType.INCOMPATIBLE;
return new SchemaCompatibilityResult(compatibilityType, mergedIncompatibilities);
}
private final SchemaCompatibilityType mCompatibilityType;
// the below fields are only valid if INCOMPATIBLE
private final List<Incompatibility> mIncompatibilities;
// cached objects for stateless details
private static final SchemaCompatibilityResult COMPATIBLE = new SchemaCompatibilityResult(
SchemaCompatibilityType.COMPATIBLE, Collections.emptyList());
private static final SchemaCompatibilityResult RECURSION_IN_PROGRESS = new SchemaCompatibilityResult(
SchemaCompatibilityType.RECURSION_IN_PROGRESS, Collections.emptyList());
private SchemaCompatibilityResult(SchemaCompatibilityType compatibilityType,
List<Incompatibility> incompatibilities) {
this.mCompatibilityType = compatibilityType;
this.mIncompatibilities = incompatibilities;
}
/**
* Returns a details object representing a compatible schema pair.
*
* @return a SchemaCompatibilityDetails object with COMPATIBLE
* SchemaCompatibilityType, and no other state.
*/
public static SchemaCompatibilityResult compatible() {
return COMPATIBLE;
}
/**
* Returns a details object representing a state indicating that recursion is in
* progress.
*
* @return a SchemaCompatibilityDetails object with RECURSION_IN_PROGRESS
* SchemaCompatibilityType, and no other state.
*/
public static SchemaCompatibilityResult recursionInProgress() {
return RECURSION_IN_PROGRESS;
}
/**
* Returns a details object representing an incompatible schema pair, including
* error details.
*
* @return a SchemaCompatibilityDetails object with INCOMPATIBLE
* SchemaCompatibilityType, and state representing the violating part.
*/
public static SchemaCompatibilityResult incompatible(SchemaIncompatibilityType incompatibilityType,
Schema readerFragment, Schema writerFragment, String message, List<String> location) {
Incompatibility incompatibility = new Incompatibility(incompatibilityType, readerFragment, writerFragment,
message, location);
return new SchemaCompatibilityResult(SchemaCompatibilityType.INCOMPATIBLE,
Collections.singletonList(incompatibility));
}
/**
* Returns the SchemaCompatibilityType, always non-null.
*
* @return a SchemaCompatibilityType instance, always non-null
*/
public SchemaCompatibilityType getCompatibility() {
return mCompatibilityType;
}
/**
* If the compatibility is INCOMPATIBLE, returns {@link Incompatibility
* Incompatibilities} found, otherwise an empty list.
*
* @return a list of {@link Incompatibility Incompatibilities}, may be empty,
* never null.
*/
public List<Incompatibility> getIncompatibilities() {
return mIncompatibilities;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mCompatibilityType == null) ? 0 : mCompatibilityType.hashCode());
result = prime * result + ((mIncompatibilities == null) ? 0 : mIncompatibilities.hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SchemaCompatibilityResult other = (SchemaCompatibilityResult) obj;
if (mIncompatibilities == null) {
if (other.mIncompatibilities != null) {
return false;
}
} else if (!mIncompatibilities.equals(other.mIncompatibilities)) {
return false;
}
return mCompatibilityType == other.mCompatibilityType;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("SchemaCompatibilityResult{compatibility:%s, incompatibilities:%s}", mCompatibilityType,
mIncompatibilities);
}
}
// -----------------------------------------------------------------------------------------------
public static final class Incompatibility {
private final SchemaIncompatibilityType mType;
private final Schema mReaderFragment;
private final Schema mWriterFragment;
private final String mMessage;
private final List<String> mLocation;
Incompatibility(SchemaIncompatibilityType type, Schema readerFragment, Schema writerFragment, String message,
List<String> location) {
super();
this.mType = type;
this.mReaderFragment = readerFragment;
this.mWriterFragment = writerFragment;
this.mMessage = message;
this.mLocation = location;
}
/**
* Returns the SchemaIncompatibilityType.
*
* @return a SchemaIncompatibilityType instance.
*/
public SchemaIncompatibilityType getType() {
return mType;
}
/**
* Returns the fragment of the reader schema that failed compatibility check.
*
* @return a Schema instance (fragment of the reader schema).
*/
public Schema getReaderFragment() {
return mReaderFragment;
}
/**
* Returns the fragment of the writer schema that failed compatibility check.
*
* @return a Schema instance (fragment of the writer schema).
*/
public Schema getWriterFragment() {
return mWriterFragment;
}
/**
* Returns a human-readable message with more details about what failed. Syntax
* depends on the SchemaIncompatibilityType.
*
* @return a String with details about the incompatibility.
* @see #getType()
*/
public String getMessage() {
return mMessage;
}
/**
* Returns a
* <a href="https://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-08">JSON
* Pointer</a> describing the node location within the schema's JSON document
* tree where the incompatibility was encountered.
*
* @return JSON Pointer encoded as a string.
*/
public String getLocation() {
StringBuilder s = new StringBuilder("/");
boolean first = true;
// ignore root element
for (String coordinate : mLocation.subList(1, mLocation.size())) {
if (first) {
first = false;
} else {
s.append('/');
}
// Apply JSON pointer escaping.
s.append(coordinate.replace("~", "~0").replace("/", "~1"));
}
return s.toString();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mType == null) ? 0 : mType.hashCode());
result = prime * result + ((mReaderFragment == null) ? 0 : mReaderFragment.hashCode());
result = prime * result + ((mWriterFragment == null) ? 0 : mWriterFragment.hashCode());
result = prime * result + ((mMessage == null) ? 0 : mMessage.hashCode());
result = prime * result + ((mLocation == null) ? 0 : mLocation.hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Incompatibility other = (Incompatibility) obj;
if (mType != other.mType) {
return false;
}
if (mReaderFragment == null) {
if (other.mReaderFragment != null) {
return false;
}
} else if (!mReaderFragment.equals(other.mReaderFragment)) {
return false;
}
if (mWriterFragment == null) {
if (other.mWriterFragment != null) {
return false;
}
} else if (!mWriterFragment.equals(other.mWriterFragment)) {
return false;
}
if (mMessage == null) {
if (other.mMessage != null) {
return false;
}
} else if (!mMessage.equals(other.mMessage)) {
return false;
}
if (mLocation == null) {
return other.mLocation == null;
} else {
return mLocation.equals(other.mLocation);
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("Incompatibility{type:%s, location:%s, message:%s, reader:%s, writer:%s}", mType,
getLocation(), mMessage, mReaderFragment, mWriterFragment);
}
}
// -----------------------------------------------------------------------------------------------
/**
* Provides information about the compatibility of a single reader and writer
* schema pair.
* <p>
* Note: This class represents a one-way relationship from the reader to the
* writer schema.
*/
public static final class SchemaPairCompatibility {
/**
* The details of this result.
*/
private final SchemaCompatibilityResult mResult;
/**
* Validated reader schema.
*/
private final Schema mReader;
/**
* Validated writer schema.
*/
private final Schema mWriter;
/**
* Human-readable description of this result.
*/
private final String mDescription;
/**
* Constructs a new instance.
*
* @param result The result of the compatibility check.
* @param reader schema that was validated.
* @param writer schema that was validated.
* @param description of this compatibility result.
*/
public SchemaPairCompatibility(SchemaCompatibilityResult result, Schema reader, Schema writer, String description) {
mResult = result;
mReader = reader;
mWriter = writer;
mDescription = description;
}
/**
* Gets the type of this result.
*
* @return the type of this result.
*/
public SchemaCompatibilityType getType() {
return mResult.getCompatibility();
}
/**
* Gets more details about the compatibility, in particular if getType() is
* INCOMPATIBLE.
*
* @return the details of this compatibility check.
*/
public SchemaCompatibilityResult getResult() {
return mResult;
}
/**
* Gets the reader schema that was validated.
*
* @return reader schema that was validated.
*/
public Schema getReader() {
return mReader;
}
/**
* Gets the writer schema that was validated.
*
* @return writer schema that was validated.
*/
public Schema getWriter() {
return mWriter;
}
/**
* Gets a human-readable description of this validation result.
*
* @return a human-readable description of this validation result.
*/
public String getDescription() {
return mDescription;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("SchemaPairCompatibility{result:%s, readerSchema:%s, writerSchema:%s, description:%s}",
mResult, mReader, mWriter, mDescription);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
if ((other instanceof SchemaPairCompatibility)) {
final SchemaPairCompatibility result = (SchemaPairCompatibility) other;
return objectsEqual(result.mResult, mResult) && objectsEqual(result.mReader, mReader)
&& objectsEqual(result.mWriter, mWriter) && objectsEqual(result.mDescription, mDescription);
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Arrays.hashCode(new Object[] {mResult, mReader, mWriter, mDescription});
}
}
/**
* Borrowed from Guava's Objects.equal(a, b)
*/
private static boolean objectsEqual(Object obj1, Object obj2) {
return Objects.equals(obj1, obj2);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.