repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
apache/hadoop
37,702
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/UsersManager.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractUsersManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.apache.hadoop.classification.VisibleForTesting; /** * {@link UsersManager} tracks users in the system and its respective data * structures. */ @Private public class UsersManager implements AbstractUsersManager { private static final Logger LOG = LoggerFactory.getLogger(UsersManager.class); /* * Member declaration for UsersManager class. */ private final AbstractLeafQueue lQueue; private final RMNodeLabelsManager labelManager; private final ResourceCalculator resourceCalculator; private Map<String, User> users = new ConcurrentHashMap<>(); private ResourceUsage totalResUsageForActiveUsers = new ResourceUsage(); private ResourceUsage totalResUsageForNonActiveUsers = new ResourceUsage(); private Set<String> activeUsersSet = new HashSet<String>(); private Set<String> nonActiveUsersSet = new HashSet<String>(); // Summation of consumed ratios for all users in queue private UsageRatios qUsageRatios; // To detect whether there is a change in user count for every user-limit // calculation. private long latestVersionOfUsersState = 0; private Map<String, Map<SchedulingMode, Long>> localVersionOfActiveUsersState = new HashMap<String, Map<SchedulingMode, Long>>(); private Map<String, Map<SchedulingMode, Long>> localVersionOfAllUsersState = new HashMap<String, Map<SchedulingMode, Long>>(); private volatile float userLimit; private volatile float userLimitFactor; private WriteLock writeLock; private ReadLock readLock; private final QueueMetrics metrics; private AtomicInteger activeUsers = new AtomicInteger(0); private AtomicInteger activeUsersWithOnlyPendingApps = new AtomicInteger(0); private Map<String, Set<ApplicationId>> usersApplications = new HashMap<String, Set<ApplicationId>>(); // Pre-computed list of user-limits. @VisibleForTesting Map<String, Map<SchedulingMode, Resource>> preComputedActiveUserLimit = new HashMap<>(); @VisibleForTesting Map<String, Map<SchedulingMode, Resource>> preComputedAllUserLimit = new HashMap<>(); private float activeUsersTimesWeights = 0.0f; private float allUsersTimesWeights = 0.0f; /** * UsageRatios will store the total used resources ratio across all users of * the queue. */ static private class UsageRatios { private Map<String, Float> usageRatios; private ReadLock readLock; private WriteLock writeLock; public UsageRatios() { ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); readLock = lock.readLock(); writeLock = lock.writeLock(); usageRatios = new HashMap<String, Float>(); } private void incUsageRatio(String label, float delta) { writeLock.lock(); try { float usage = 0f; if (usageRatios.containsKey(label)) { usage = usageRatios.get(label); } usage += delta; usageRatios.put(label, usage); } finally { writeLock.unlock(); } } private float getUsageRatio(String label) { readLock.lock(); try { Float f = usageRatios.get(label); if (null == f) { return 0.0f; } return f; } finally { readLock.unlock(); } } private void setUsageRatio(String label, float ratio) { writeLock.lock(); try { usageRatios.put(label, ratio); } finally { writeLock.unlock(); } } } /* End of UserRatios class */ /** * User class stores all user related resource usage, application details. */ @VisibleForTesting public static class User { ResourceUsage userResourceUsage = new ResourceUsage(); String userName = null; volatile Resource userResourceLimit = Resource.newInstance(0, 0); private volatile AtomicInteger pendingApplications = new AtomicInteger(0); private volatile AtomicInteger activeApplications = new AtomicInteger(0); private UsageRatios userUsageRatios = new UsageRatios(); private WriteLock writeLock; private float weight; public User(String name) { ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // Nobody uses read-lock now, will add it when necessary writeLock = lock.writeLock(); this.userName = name; } public ResourceUsage getResourceUsage() { return userResourceUsage; } public float setAndUpdateUsageRatio(ResourceCalculator resourceCalculator, Resource resource, String nodePartition) { writeLock.lock(); try { userUsageRatios.setUsageRatio(nodePartition, 0); return updateUsageRatio(resourceCalculator, resource, nodePartition); } finally { writeLock.unlock(); } } public float updateUsageRatio(ResourceCalculator resourceCalculator, Resource resource, String nodePartition) { writeLock.lock(); try { float delta; float newRatio = Resources.ratio(resourceCalculator, getUsed(nodePartition), resource); delta = newRatio - userUsageRatios.getUsageRatio(nodePartition); userUsageRatios.setUsageRatio(nodePartition, newRatio); return delta; } finally { writeLock.unlock(); } } public Resource getUsed() { return userResourceUsage.getUsed(); } public Resource getAllUsed() { return userResourceUsage.getAllUsed(); } public Resource getUsed(String label) { return userResourceUsage.getUsed(label); } public int getPendingApplications() { return pendingApplications.get(); } public int getActiveApplications() { return activeApplications.get(); } public Resource getConsumedAMResources() { return userResourceUsage.getAMUsed(); } public Resource getConsumedAMResources(String label) { return userResourceUsage.getAMUsed(label); } public int getTotalApplications() { return getPendingApplications() + getActiveApplications(); } public void submitApplication() { pendingApplications.incrementAndGet(); } public void activateApplication() { pendingApplications.decrementAndGet(); activeApplications.incrementAndGet(); } public void finishApplication(boolean wasActive) { if (wasActive) { activeApplications.decrementAndGet(); } else { pendingApplications.decrementAndGet(); } } public Resource getUserResourceLimit() { return userResourceLimit; } public void setUserResourceLimit(Resource userResourceLimit) { this.userResourceLimit = userResourceLimit; } public String getUserName() { return this.userName; } @VisibleForTesting public void setResourceUsage(ResourceUsage resourceUsage) { this.userResourceUsage = resourceUsage; } /** * @return the weight */ public float getWeight() { return weight; } /** * @param weight the weight to set */ public void setWeight(float weight) { this.weight = weight; } } /* End of User class */ /** * UsersManager Constructor. * * @param metrics * Queue Metrics * @param lQueue * Leaf Queue Object * @param labelManager * Label Manager instance * @param resourceCalculator * rc */ public UsersManager(QueueMetrics metrics, AbstractLeafQueue lQueue, RMNodeLabelsManager labelManager, ResourceCalculator resourceCalculator) { ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); this.lQueue = lQueue; this.labelManager = labelManager; this.resourceCalculator = resourceCalculator; this.qUsageRatios = new UsageRatios(); this.metrics = metrics; this.writeLock = lock.writeLock(); this.readLock = lock.readLock(); } /** * Get configured user-limit. * @return user limit */ public float getUserLimit() { return userLimit; } /** * Set configured user-limit. * @param userLimit user limit */ public void setUserLimit(float userLimit) { this.userLimit = userLimit; } /** * Get configured user-limit factor. * @return user-limit factor */ public float getUserLimitFactor() { return userLimitFactor; } /** * Set configured user-limit factor. * @param userLimitFactor User Limit factor. */ public void setUserLimitFactor(float userLimitFactor) { this.userLimitFactor = userLimitFactor; } @VisibleForTesting public float getUsageRatio(String label) { return qUsageRatios.getUsageRatio(label); } /** * Force UsersManager to recompute userlimit. */ public void userLimitNeedsRecompute() { // If latestVersionOfUsersState is negative due to overflow, ideally we need // to reset it. This method is invoked from UsersManager and LeafQueue and // all is happening within write/readLock. Below logic can help to set 0. writeLock.lock(); try { long value = ++latestVersionOfUsersState; if (value < 0) { latestVersionOfUsersState = 0; } } finally { writeLock.unlock(); } } /* * Get all users of queue. */ public Map<String, User> getUsers() { return users; } /** * Get user object for given user name. * * @param userName * User Name * @return User object */ public User getUser(String userName) { return users.get(userName); } /** * Remove user. * * @param userName * User Name */ public void removeUser(String userName) { writeLock.lock(); try { this.users.remove(userName); // Remove user from active/non-active list as well. activeUsersSet.remove(userName); nonActiveUsersSet.remove(userName); activeUsersTimesWeights = sumActiveUsersTimesWeights(); allUsersTimesWeights = sumAllUsersTimesWeights(); } finally { writeLock.unlock(); } } /** * Get and add user if absent. * * @param userName * User Name * @return User object */ public User getUserAndAddIfAbsent(String userName) { writeLock.lock(); try { User u = getUser(userName); if (null == u) { u = new User(userName); addUser(userName, u); // Add to nonActive list so that resourceUsage could be tracked if (!nonActiveUsersSet.contains(userName)) { nonActiveUsersSet.add(userName); } } return u; } finally { writeLock.unlock(); } } /* * Add a new user */ private void addUser(String userName, User user) { this.users.put(userName, user); user.setWeight(getUserWeightFromQueue(userName)); allUsersTimesWeights = sumAllUsersTimesWeights(); } /** * @return an ArrayList of UserInfo objects who are active in this queue */ public ArrayList<UserInfo> getUsersInfo() { readLock.lock(); try { ArrayList<UserInfo> usersToReturn = new ArrayList<UserInfo>(); for (Map.Entry<String, User> entry : getUsers().entrySet()) { User user = entry.getValue(); usersToReturn.add( new UserInfo(entry.getKey(), Resources.clone(user.getAllUsed()), user.getActiveApplications(), user.getPendingApplications(), Resources.clone(user.getConsumedAMResources()), Resources.clone(user.getUserResourceLimit()), user.getResourceUsage(), user.getWeight(), activeUsersSet.contains(user.userName))); } return usersToReturn; } finally { readLock.unlock(); } } private float getUserWeightFromQueue(String userName) { return lQueue.getUserWeights().getByUser(userName); } /** * Get computed user-limit for all ACTIVE users in this queue. If cached data * is invalidated due to resource change, this method also enforce to * recompute user-limit. * * @param userName * Name of user who has submitted one/more app to given queue. * @param clusterResource * total cluster resource * @param nodePartition * partition name * @param schedulingMode * scheduling mode * RESPECT_PARTITION_EXCLUSIVITY/IGNORE_PARTITION_EXCLUSIVITY * @return Computed User Limit */ public Resource getComputedResourceLimitForActiveUsers(String userName, Resource clusterResource, String nodePartition, SchedulingMode schedulingMode) { Map<SchedulingMode, Resource> userLimitPerSchedulingMode; writeLock.lock(); try { userLimitPerSchedulingMode = preComputedActiveUserLimit.get(nodePartition); if (isRecomputeNeeded(schedulingMode, nodePartition, true)) { // recompute userLimitPerSchedulingMode = reComputeUserLimits(userName, nodePartition, clusterResource, schedulingMode, true); // update user count to cache so that we can avoid recompute if no major // changes. setLocalVersionOfUsersState(nodePartition, schedulingMode, true); } } finally { writeLock.unlock(); } Resource userLimitResource = userLimitPerSchedulingMode.get(schedulingMode); User user = getUser(userName); float weight = (user == null) ? 1.0f : user.getWeight(); Resource userSpecificUserLimit = Resources.multiplyAndNormalizeDown(resourceCalculator, userLimitResource, weight, lQueue.getMinimumAllocation()); if (user != null) { user.setUserResourceLimit(userSpecificUserLimit); } LOG.debug("userLimit is fetched. userLimit={}, userSpecificUserLimit={}," + " schedulingMode={}, partition={}", userLimitResource, userSpecificUserLimit, schedulingMode, nodePartition); return userSpecificUserLimit; } /** * Get computed user-limit for all users in this queue. If cached data is * invalidated due to resource change, this method also enforce to recompute * user-limit. * * @param userName * Name of user who has submitted one/more app to given queue. * @param clusterResource * total cluster resource * @param nodePartition * partition name * @param schedulingMode * scheduling mode * RESPECT_PARTITION_EXCLUSIVITY/IGNORE_PARTITION_EXCLUSIVITY * @return Computed User Limit */ public Resource getComputedResourceLimitForAllUsers(String userName, Resource clusterResource, String nodePartition, SchedulingMode schedulingMode) { Map<SchedulingMode, Resource> userLimitPerSchedulingMode; writeLock.lock(); try { userLimitPerSchedulingMode = preComputedAllUserLimit.get(nodePartition); if (isRecomputeNeeded(schedulingMode, nodePartition, false)) { // recompute userLimitPerSchedulingMode = reComputeUserLimits(userName, nodePartition, clusterResource, schedulingMode, false); // update user count to cache so that we can avoid recompute if no major // changes. setLocalVersionOfUsersState(nodePartition, schedulingMode, false); } } finally { writeLock.unlock(); } Resource userLimitResource = userLimitPerSchedulingMode.get(schedulingMode); User user = getUser(userName); float weight = (user == null) ? 1.0f : user.getWeight(); Resource userSpecificUserLimit = Resources.multiplyAndNormalizeDown(resourceCalculator, userLimitResource, weight, lQueue.getMinimumAllocation()); LOG.debug("userLimit is fetched. userLimit={}, userSpecificUserLimit={}," + " schedulingMode={}, partition={}", userLimitResource, userSpecificUserLimit, schedulingMode, nodePartition); return userSpecificUserLimit; } protected long getLatestVersionOfUsersState() { readLock.lock(); try { return latestVersionOfUsersState; } finally { readLock.unlock(); } } /* * Recompute user-limit under following conditions: 1. cached user-limit does * not exist in local map. 2. Total User count doesn't match with local cached * version. */ private boolean isRecomputeNeeded(SchedulingMode schedulingMode, String nodePartition, boolean isActive) { readLock.lock(); try { return (getLocalVersionOfUsersState(nodePartition, schedulingMode, isActive) != latestVersionOfUsersState); } finally { readLock.unlock(); } } /* * Set Local version of user count per label to invalidate cache if needed. */ private void setLocalVersionOfUsersState(String nodePartition, SchedulingMode schedulingMode, boolean isActive) { writeLock.lock(); try { Map<String, Map<SchedulingMode, Long>> localVersionOfUsersState = (isActive) ? localVersionOfActiveUsersState : localVersionOfAllUsersState; Map<SchedulingMode, Long> localVersion = localVersionOfUsersState .get(nodePartition); if (null == localVersion) { localVersion = new HashMap<SchedulingMode, Long>(); localVersionOfUsersState.put(nodePartition, localVersion); } localVersion.put(schedulingMode, latestVersionOfUsersState); } finally { writeLock.unlock(); } } /* * Get Local version of user count per label to invalidate cache if needed. */ private long getLocalVersionOfUsersState(String nodePartition, SchedulingMode schedulingMode, boolean isActive) { this.readLock.lock(); try { Map<String, Map<SchedulingMode, Long>> localVersionOfUsersState = (isActive) ? localVersionOfActiveUsersState : localVersionOfAllUsersState; if (!localVersionOfUsersState.containsKey(nodePartition)) { return -1; } Map<SchedulingMode, Long> localVersion = localVersionOfUsersState .get(nodePartition); if (!localVersion.containsKey(schedulingMode)) { return -1; } return localVersion.get(schedulingMode); } finally { readLock.unlock(); } } private Map<SchedulingMode, Resource> reComputeUserLimits(String userName, String nodePartition, Resource clusterResource, SchedulingMode schedulingMode, boolean activeMode) { // preselect stored map as per active user-limit or all user computation. Map<String, Map<SchedulingMode, Resource>> computedMap = null; computedMap = (activeMode) ? preComputedActiveUserLimit : preComputedAllUserLimit; Map<SchedulingMode, Resource> userLimitPerSchedulingMode = computedMap .get(nodePartition); if (userLimitPerSchedulingMode == null) { userLimitPerSchedulingMode = new ConcurrentHashMap<>(); computedMap.put(nodePartition, userLimitPerSchedulingMode); } // compute user-limit per scheduling mode. Resource computedUserLimit = computeUserLimit(userName, clusterResource, nodePartition, schedulingMode, activeMode); // update in local storage userLimitPerSchedulingMode.put(schedulingMode, computedUserLimit); computeNumActiveUsersWithOnlyPendingApps(); return userLimitPerSchedulingMode; } // This method is called within the lock. private void computeNumActiveUsersWithOnlyPendingApps() { int numPendingUsers = 0; for (User user : users.values()) { if ((user.getPendingApplications() > 0) && (user.getActiveApplications() <= 0)) { numPendingUsers++; } } activeUsersWithOnlyPendingApps = new AtomicInteger(numPendingUsers); } @VisibleForTesting Resource computeUserLimit(String userName, Resource clusterResource, String nodePartition, SchedulingMode schedulingMode, boolean activeUser) { Resource partitionResource = labelManager.getResourceByLabel(nodePartition, clusterResource); /* * What is our current capacity? * * It is equal to the max(required, queue-capacity) if we're running * below capacity. The 'max' ensures that jobs in queues with miniscule * capacity (< 1 slot) make progress * * If we're running over capacity, then its (usedResources + required) * (which extra resources we are allocating) */ Resource queueCapacity = lQueue.getEffectiveCapacity(nodePartition); Resource originalCapacity = queueCapacity; /* * Assume we have required resource equals to minimumAllocation, this can * make sure user limit can continuously increase till queueMaxResource * reached. */ Resource required = lQueue.getMinimumAllocation(); // Allow progress for queues with miniscule capacity queueCapacity = Resources.max(resourceCalculator, partitionResource, queueCapacity, required); /* * We want to base the userLimit calculation on * max(queueCapacity, usedResources+required). However, we want * usedResources to be based on the combined ratios of all the users in the * queue so we use consumedRatio to calculate such. * The calculation is dependent on how the resourceCalculator calculates the * ratio between two Resources. DRF Example: If usedResources is greater * than queueCapacity and users have the following [mem,cpu] usages: * * User1: [10%,20%] - Dominant resource is 20% * User2: [30%,10%] - Dominant resource is 30% * Then total consumedRatio is then 20+30=50%. Yes, this value can be * larger than 100% but for the purposes of making sure all users are * getting their fair share, it works. */ Resource consumed = Resources.multiplyAndNormalizeUp(resourceCalculator, partitionResource, getUsageRatio(nodePartition), lQueue.getMinimumAllocation()); Resource currentCapacity = Resources.lessThan(resourceCalculator, partitionResource, consumed, queueCapacity) ? queueCapacity : Resources.add(consumed, required); /* * Never allow a single user to take more than the queue's configured * capacity * user-limit-factor. Also, the queue's configured capacity * should be higher than queue-hard-limit * ulMin */ float usersSummedByWeight = activeUsersTimesWeights; Resource resourceUsed = Resources.add( totalResUsageForActiveUsers.getUsed(nodePartition), required); // For non-activeUser calculation, consider all users count. if (!activeUser) { resourceUsed = currentCapacity; usersSummedByWeight = allUsersTimesWeights; } /* * User limit resource is determined by: max(currentCapacity / #activeUsers, * currentCapacity * user-limit-percentage%) */ Resource userLimitResource = Resources.max(resourceCalculator, partitionResource, Resources.divideAndCeil(resourceCalculator, resourceUsed, usersSummedByWeight), Resources.divideAndCeil(resourceCalculator, Resources.multiplyAndRoundDown(currentCapacity, getUserLimit()), 100)); // User limit is capped by maxUserLimit // - maxUserLimit = queueCapacity * user-limit-factor // (RESPECT_PARTITION_EXCLUSIVITY) // - maxUserLimit = total-partition-resource (IGNORE_PARTITION_EXCLUSIVITY) // // In IGNORE_PARTITION_EXCLUSIVITY mode, if a queue cannot access a // partition, its guaranteed resource on that partition is 0. And // user-limit-factor computation is based on queue's guaranteed capacity. So // we will not cap user-limit as well as used resource when doing // IGNORE_PARTITION_EXCLUSIVITY allocation. Resource maxUserLimit = Resources.none(); if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY) { if (getUserLimitFactor() == -1 || originalCapacity.equals(Resources.none())) { // If user-limit-factor set to -1, we should disable user limit. // // Also prevent incorrect maxUserLimit due to low queueCapacity // Can happen if dynamic queue has capacity = 0% maxUserLimit = lQueue. getEffectiveMaxCapacityDown( nodePartition, lQueue.getMinimumAllocation()); } else { maxUserLimit = Resources.multiplyAndRoundDown(queueCapacity, getUserLimitFactor()); } } else if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) { maxUserLimit = partitionResource; } // Cap final user limit with maxUserLimit userLimitResource = Resources .roundUp(resourceCalculator, Resources.min(resourceCalculator, partitionResource, userLimitResource, maxUserLimit), lQueue.getMinimumAllocation()); if (LOG.isDebugEnabled()) { float weight = lQueue.getUserWeights().getByUser(userName); LOG.debug("User limit computation for " + userName + ", in queue: " + lQueue.getQueuePath() + ", userLimitPercent=" + lQueue.getUserLimit() + ", userLimitFactor=" + lQueue.getUserLimitFactor() + ", required=" + required + ", consumed=" + consumed + ", user-limit-resource=" + userLimitResource + ", queueCapacity=" + queueCapacity + ", qconsumed=" + lQueue.getQueueResourceUsage().getUsed() + ", currentCapacity=" + currentCapacity + ", activeUsers=" + usersSummedByWeight + ", clusterCapacity=" + clusterResource + ", resourceByLabel=" + partitionResource + ", usageratio=" + getUsageRatio(nodePartition) + ", Partition=" + nodePartition + ", resourceUsed=" + resourceUsed + ", maxUserLimit=" + maxUserLimit + ", userWeight=" + weight ); } return userLimitResource; } /** * Update new usage ratio. * * @param partition Node partition * @param clusterResource cluster resource */ public void updateUsageRatio(String partition, Resource clusterResource) { writeLock.lock(); try { Resource resourceByLabel = labelManager.getResourceByLabel(partition, clusterResource); float consumed = 0; User user; for (Map.Entry<String, User> entry : getUsers().entrySet()) { user = entry.getValue(); consumed += user.setAndUpdateUsageRatio(resourceCalculator, resourceByLabel, partition); } qUsageRatios.setUsageRatio(partition, consumed); } finally { writeLock.unlock(); } } /* * Increment Queue Usage Ratio. */ private void incQueueUsageRatio(String nodePartition, float delta) { qUsageRatios.incUsageRatio(nodePartition, delta); } @Override public void activateApplication(String user, ApplicationId applicationId) { this.writeLock.lock(); try { User userDesc = getUser(user); if (userDesc != null && userDesc.getActiveApplications() <= 0) { return; } Set<ApplicationId> userApps = usersApplications.get(user); if (userApps == null) { userApps = new HashSet<ApplicationId>(); usersApplications.put(user, userApps); activeUsers.incrementAndGet(); metrics.incrActiveUsers(); // A user is added to active list. Invalidate user-limit cache. userLimitNeedsRecompute(); updateActiveUsersResourceUsage(user); LOG.debug("User {} added to activeUsers, currently: {}", user, activeUsers); } if (userApps.add(applicationId)) { metrics.activateApp(user); } } finally { this.writeLock.unlock(); } } @Override public void deactivateApplication(String user, ApplicationId applicationId) { this.writeLock.lock(); try { Set<ApplicationId> userApps = usersApplications.get(user); if (userApps != null) { if (userApps.remove(applicationId)) { metrics.deactivateApp(user); } if (userApps.isEmpty()) { usersApplications.remove(user); activeUsers.decrementAndGet(); metrics.decrActiveUsers(); // A user is removed from active list. Invalidate user-limit cache. userLimitNeedsRecompute(); updateNonActiveUsersResourceUsage(user); LOG.debug("User {} removed from activeUsers, currently: {}", user, activeUsers); } } } finally { this.writeLock.unlock(); } } @Override public int getNumActiveUsers() { return activeUsers.get() + activeUsersWithOnlyPendingApps.get(); } float sumActiveUsersTimesWeights() { float count = 0.0f; this.readLock.lock(); try { for (String u : activeUsersSet) { count += getUser(u).getWeight(); } return count; } finally { this.readLock.unlock(); } } float sumAllUsersTimesWeights() { float count = 0.0f; this.readLock.lock(); try { for (String u : users.keySet()) { count += getUser(u).getWeight(); } return count; } finally { this.readLock.unlock(); } } private void updateActiveUsersResourceUsage(String userName) { this.writeLock.lock(); try { // For UT case: We might need to add the user to users list. User user = getUserAndAddIfAbsent(userName); ResourceUsage resourceUsage = user.getResourceUsage(); // If User is moved to active list, moved resource usage from non-active // to active list. if (nonActiveUsersSet.contains(userName)) { nonActiveUsersSet.remove(userName); activeUsersSet.add(userName); activeUsersTimesWeights = sumActiveUsersTimesWeights(); // Update total resource usage of active and non-active after user // is moved from non-active to active. for (String partition : resourceUsage.getExistingNodeLabels()) { totalResUsageForNonActiveUsers.decUsed(partition, resourceUsage.getUsed(partition)); totalResUsageForActiveUsers.incUsed(partition, resourceUsage.getUsed(partition)); } if (LOG.isDebugEnabled()) { LOG.debug("User '" + userName + "' has become active. Hence move user to active list." + "Active users size = " + activeUsersSet.size() + "Non-active users size = " + nonActiveUsersSet.size() + "Total Resource usage for active users=" + totalResUsageForActiveUsers.getAllUsed() + "." + "Total Resource usage for non-active users=" + totalResUsageForNonActiveUsers.getAllUsed()); } } } finally { this.writeLock.unlock(); } } private void updateNonActiveUsersResourceUsage(String userName) { this.writeLock.lock(); try { // For UT case: We might need to add the user to users list. User user = getUser(userName); if (user == null) return; ResourceUsage resourceUsage = user.getResourceUsage(); // If User is moved to non-active list, moved resource usage from // non-active to active list. if (activeUsersSet.contains(userName)) { activeUsersSet.remove(userName); nonActiveUsersSet.add(userName); activeUsersTimesWeights = sumActiveUsersTimesWeights(); // Update total resource usage of active and non-active after user is // moved from active to non-active. for (String partition : resourceUsage.getExistingNodeLabels()) { totalResUsageForActiveUsers.decUsed(partition, resourceUsage.getUsed(partition)); totalResUsageForNonActiveUsers.incUsed(partition, resourceUsage.getUsed(partition)); if (LOG.isDebugEnabled()) { LOG.debug("User '" + userName + "' has become non-active.Hence move user to non-active list." + "Active users size = " + activeUsersSet.size() + "Non-active users size = " + nonActiveUsersSet.size() + "Total Resource usage for active users=" + totalResUsageForActiveUsers.getAllUsed() + "." + "Total Resource usage for non-active users=" + totalResUsageForNonActiveUsers.getAllUsed()); } } } } finally { this.writeLock.unlock(); } } private ResourceUsage getTotalResourceUsagePerUser(String userName) { if (nonActiveUsersSet.contains(userName)) { return totalResUsageForNonActiveUsers; } else if (activeUsersSet.contains(userName)) { return totalResUsageForActiveUsers; } else { LOG.warn("User '" + userName + "' is not present in active/non-active. This is highly unlikely." + "We can consider this user in non-active list in this case."); return totalResUsageForNonActiveUsers; } } /** * During container allocate/release, ensure that all user specific data * structures are updated. * * @param userName * Name of the user * @param resource * Resource to increment/decrement * @param clusterResource * Cluster resource (for testing purposes only) * @param nodePartition * Node label * @param isAllocate * Indicate whether to allocate or release resource * @return user */ public User updateUserResourceUsage(String userName, Resource resource, Resource clusterResource, String nodePartition, boolean isAllocate) { this.writeLock.lock(); try { // TODO, should use getUser, use this method just to avoid UT failure // which is caused by wrong invoking order, will fix UT separately User user = getUserAndAddIfAbsent(userName); // New container is allocated. Invalidate user-limit. updateResourceUsagePerUser(user, resource, nodePartition, isAllocate); userLimitNeedsRecompute(); // Update usage ratios Resource resourceByLabel = labelManager.getResourceByLabel(nodePartition, clusterResource); incQueueUsageRatio(nodePartition, user.updateUsageRatio( resourceCalculator, resourceByLabel, nodePartition)); return user; } finally { this.writeLock.unlock(); } } private void updateResourceUsagePerUser(User user, Resource resource, String nodePartition, boolean isAllocate) { ResourceUsage totalResourceUsageForUsers = getTotalResourceUsagePerUser( user.userName); if (isAllocate) { user.getResourceUsage().incUsed(nodePartition, resource); totalResourceUsageForUsers.incUsed(nodePartition, resource); } else { user.getResourceUsage().decUsed(nodePartition, resource); totalResourceUsageForUsers.decUsed(nodePartition, resource); } if (LOG.isDebugEnabled()) { LOG.debug( "User resource is updated." + "Total Resource usage for active users=" + totalResUsageForActiveUsers.getAllUsed() + "." + "Total Resource usage for non-active users=" + totalResUsageForNonActiveUsers.getAllUsed()); } } public void updateUserWeights() { this.writeLock.lock(); try { for (Map.Entry<String, User> ue : users.entrySet()) { ue.getValue().setWeight(getUserWeightFromQueue(ue.getKey())); } activeUsersTimesWeights = sumActiveUsersTimesWeights(); allUsersTimesWeights = sumAllUsersTimesWeights(); userLimitNeedsRecompute(); } finally { this.writeLock.unlock(); } } @VisibleForTesting public int getNumActiveUsersWithOnlyPendingApps() { return activeUsersWithOnlyPendingApps.get(); } @VisibleForTesting void setUsageRatio(String label, float usage) { qUsageRatios.usageRatios.put(label, usage); } }
googleapis/google-cloud-java
37,745
java-shopping-merchant-reports/proto-google-shopping-merchant-reports-v1/src/main/java/com/google/shopping/merchant/reports/v1/SearchRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/merchant/reports/v1/reports.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.reports.v1; /** * * * <pre> * Request message for the `ReportService.Search` method. * </pre> * * Protobuf type {@code google.shopping.merchant.reports.v1.SearchRequest} */ public final class SearchRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.reports.v1.SearchRequest) SearchRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SearchRequest.newBuilder() to construct. private SearchRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchRequest() { parent_ = ""; query_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.reports.v1.ReportsProto .internal_static_google_shopping_merchant_reports_v1_SearchRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.reports.v1.ReportsProto .internal_static_google_shopping_merchant_reports_v1_SearchRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.reports.v1.SearchRequest.class, com.google.shopping.merchant.reports.v1.SearchRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int QUERY_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object query_ = ""; /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The query. */ @java.lang.Override public java.lang.String getQuery() { java.lang.Object ref = query_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); query_ = s; return s; } } /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for query. */ @java.lang.Override public com.google.protobuf.ByteString getQueryBytes() { java.lang.Object ref = query_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); query_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 3; private int pageSize_ = 0; /** * * * <pre> * Optional. Number of `ReportRows` to retrieve in a single page. Defaults to * 1000. Values above 5000 are coerced to 5000. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(query_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, query_); } if (pageSize_ != 0) { output.writeInt32(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(query_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, query_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.merchant.reports.v1.SearchRequest)) { return super.equals(obj); } com.google.shopping.merchant.reports.v1.SearchRequest other = (com.google.shopping.merchant.reports.v1.SearchRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getQuery().equals(other.getQuery())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + QUERY_FIELD_NUMBER; hash = (53 * hash) + getQuery().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.reports.v1.SearchRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.shopping.merchant.reports.v1.SearchRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the `ReportService.Search` method. * </pre> * * Protobuf type {@code google.shopping.merchant.reports.v1.SearchRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.reports.v1.SearchRequest) com.google.shopping.merchant.reports.v1.SearchRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.reports.v1.ReportsProto .internal_static_google_shopping_merchant_reports_v1_SearchRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.reports.v1.ReportsProto .internal_static_google_shopping_merchant_reports_v1_SearchRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.reports.v1.SearchRequest.class, com.google.shopping.merchant.reports.v1.SearchRequest.Builder.class); } // Construct using com.google.shopping.merchant.reports.v1.SearchRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; query_ = ""; pageSize_ = 0; pageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.reports.v1.ReportsProto .internal_static_google_shopping_merchant_reports_v1_SearchRequest_descriptor; } @java.lang.Override public com.google.shopping.merchant.reports.v1.SearchRequest getDefaultInstanceForType() { return com.google.shopping.merchant.reports.v1.SearchRequest.getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.reports.v1.SearchRequest build() { com.google.shopping.merchant.reports.v1.SearchRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.reports.v1.SearchRequest buildPartial() { com.google.shopping.merchant.reports.v1.SearchRequest result = new com.google.shopping.merchant.reports.v1.SearchRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.shopping.merchant.reports.v1.SearchRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.query_ = query_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.pageToken_ = pageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.shopping.merchant.reports.v1.SearchRequest) { return mergeFrom((com.google.shopping.merchant.reports.v1.SearchRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.shopping.merchant.reports.v1.SearchRequest other) { if (other == com.google.shopping.merchant.reports.v1.SearchRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getQuery().isEmpty()) { query_ = other.query_; bitField0_ |= 0x00000002; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { query_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Id of the account making the call. Must be a standalone account * or an MCA subaccount. Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object query_ = ""; /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The query. */ public java.lang.String getQuery() { java.lang.Object ref = query_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); query_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for query. */ public com.google.protobuf.ByteString getQueryBytes() { java.lang.Object ref = query_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); query_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The query to set. * @return This builder for chaining. */ public Builder setQuery(java.lang.String value) { if (value == null) { throw new NullPointerException(); } query_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearQuery() { query_ = getDefaultInstance().getQuery(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Query that defines a report to be retrieved. * * For details on how to construct your query, see the [Query Language * guide](/merchant/api/guides/reports/query-language). For the full list of * available tables and fields, see the [Available * fields](/merchant/api/reference/rest/reports_v1/accounts.reports). * </pre> * * <code>string query = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for query to set. * @return This builder for chaining. */ public Builder setQueryBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); query_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Number of `ReportRows` to retrieve in a single page. Defaults to * 1000. Values above 5000 are coerced to 5000. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Number of `ReportRows` to retrieve in a single page. Defaults to * 1000. Values above 5000 are coerced to 5000. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Number of `ReportRows` to retrieve in a single page. Defaults to * 1000. Values above 5000 are coerced to 5000. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000004); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. Token of the page to retrieve. If not specified, the first page * of results is returned. In order to request the next page of results, the * value obtained from `next_page_token` in the previous response should be * used. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.merchant.reports.v1.SearchRequest) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.reports.v1.SearchRequest) private static final com.google.shopping.merchant.reports.v1.SearchRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.reports.v1.SearchRequest(); } public static com.google.shopping.merchant.reports.v1.SearchRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchRequest> PARSER = new com.google.protobuf.AbstractParser<SearchRequest>() { @java.lang.Override public SearchRequest 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<SearchRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.reports.v1.SearchRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/directory-studio
38,109
plugins/ldapbrowser.core/src/main/java/org/apache/directory/studio/ldapbrowser/core/jobs/SearchRunnable.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.ldapbrowser.core.jobs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.naming.directory.SearchControls; import org.apache.commons.lang3.ArrayUtils; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.message.controls.PagedResults; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.url.LdapUrl; import org.apache.directory.api.util.Strings; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Controls; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.connection.core.StudioControl; import org.apache.directory.studio.connection.core.io.api.StudioSearchResult; import org.apache.directory.studio.connection.core.io.api.StudioSearchResultEnumeration; import org.apache.directory.studio.connection.core.jobs.StudioConnectionBulkRunnableWithProgress; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent; import org.apache.directory.studio.ldapbrowser.core.model.AttributeHierarchy; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.ISearch; import org.apache.directory.studio.ldapbrowser.core.model.ISearchResult; import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter; import org.apache.directory.studio.ldapbrowser.core.model.impl.BaseDNEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.ContinuedSearchResultEntry; import org.apache.directory.studio.ldapbrowser.core.model.impl.Entry; import org.apache.directory.studio.ldapbrowser.core.model.impl.SearchContinuation; import org.apache.directory.studio.ldapbrowser.core.model.impl.Value; import org.apache.directory.studio.ldapbrowser.core.utils.JNDIUtils; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; /** * Runnable to perform search operations. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class SearchRunnable implements StudioConnectionBulkRunnableWithProgress { /** The searches. */ protected ISearch[] searches; /** The searches to perform. */ protected ISearch[] searchesToPerform; /** * Creates a new instance of SearchRunnable. * * @param searches the searches */ public SearchRunnable( ISearch[] searches ) { this.searches = searches; this.searchesToPerform = searches; } /** * Creates a new instance of SearchRunnable. * * @param search the search * @param searchToPerform the search to perform */ private SearchRunnable( ISearch search, ISearch searchToPerform ) { this.searches = new ISearch[] { search }; this.searchesToPerform = new ISearch[] { searchToPerform }; } /** * {@inheritDoc} */ public Connection[] getConnections() { Connection[] connections = new Connection[searches.length]; for ( int i = 0; i < connections.length; i++ ) { connections[i] = searches[i].getBrowserConnection().getConnection(); } return connections; } /** * {@inheritDoc} */ public String getName() { return BrowserCoreMessages.jobs__search_name; } /** * {@inheritDoc} */ public Object[] getLockedObjects() { List<Object> l = new ArrayList<Object>(); l.addAll( Arrays.asList( searches ) ); return l.toArray(); } /** * {@inheritDoc} */ public String getErrorMessage() { return searches.length == 1 ? BrowserCoreMessages.jobs__search_error_1 : BrowserCoreMessages.jobs__search_error_n; } /** * {@inheritDoc} */ public void run( StudioProgressMonitor monitor ) { monitor.beginTask( " ", searches.length + 1 ); //$NON-NLS-1$ monitor.reportProgress( " " ); //$NON-NLS-1$ for ( int pi = 0; pi < searches.length; pi++ ) { ISearch search = searches[pi]; ISearch searchToPerform = searchesToPerform[pi]; monitor.setTaskName( BrowserCoreMessages.bind( BrowserCoreMessages.jobs__search_task, new String[] { search.getName() } ) ); monitor.worked( 1 ); if ( search.getBrowserConnection() != null ) { // reset search results search.setSearchResults( new ISearchResult[0] ); search.getResponseControls().clear(); search.setNextPageSearchRunnable( null ); search.setTopPageSearchRunnable( null ); searchToPerform.setSearchResults( new ISearchResult[0] ); searchToPerform.setNextPageSearchRunnable( null ); searchToPerform.setTopPageSearchRunnable( null ); searchToPerform.getResponseControls().clear(); do { // perform search searchAndUpdateModel( searchToPerform.getBrowserConnection(), searchToPerform, monitor ); if ( search != searchToPerform ) { // merge search results ISearchResult[] sr1 = search.getSearchResults(); ISearchResult[] sr2 = searchToPerform.getSearchResults(); ISearchResult[] sr = new ISearchResult[sr1.length + sr2.length]; System.arraycopy( sr1, 0, sr, 0, sr1.length ); System.arraycopy( sr2, 0, sr, sr1.length, sr2.length ); search.setSearchResults( sr ); } else { // set search results search.setSearchResults( searchToPerform.getSearchResults() ); } // check response controls ISearch clonedSearch = ( ISearch ) searchToPerform.clone(); clonedSearch.getResponseControls().clear(); PagedResults prResponseControl = null; PagedResults prRequestControl = null; for ( org.apache.directory.api.ldap.model.message.Control responseControl : searchToPerform .getResponseControls() ) { if ( responseControl instanceof PagedResults ) { prResponseControl = ( PagedResults ) responseControl; } } for ( Iterator<Control> it = clonedSearch.getControls().iterator(); it.hasNext(); ) { Control requestControl = it.next(); if ( requestControl instanceof PagedResults ) { prRequestControl = ( PagedResults ) requestControl; it.remove(); } } searchToPerform = null; // paged search if ( prResponseControl != null && prRequestControl != null ) { PagedResults nextPrc = Controls.newPagedResultsControl( prRequestControl.getSize(), prResponseControl.getCookie() ); ISearch nextPageSearch = ( ISearch ) clonedSearch.clone(); nextPageSearch.getResponseControls().clear(); nextPageSearch.getControls().add( nextPrc ); if ( search.isPagedSearchScrollMode() ) { if ( ArrayUtils.isNotEmpty( prRequestControl.getCookie() ) ) { // create top page search runnable, same as original search ISearch topPageSearch = ( ISearch ) search.clone(); topPageSearch.getResponseControls().clear(); SearchRunnable topPageSearchRunnable = new SearchRunnable( search, topPageSearch ); search.setTopPageSearchRunnable( topPageSearchRunnable ); } if ( ArrayUtils.isNotEmpty( prResponseControl.getCookie() ) ) { // create next page search runnable SearchRunnable nextPageSearchRunnable = new SearchRunnable( search, nextPageSearch ); search.setNextPageSearchRunnable( nextPageSearchRunnable ); } } else { // transparently continue search, till count limit is reached if ( ArrayUtils.isNotEmpty( prResponseControl.getCookie() ) && ( search.getCountLimit() == 0 || search.getSearchResults().length < search .getCountLimit() ) ) { searchToPerform = nextPageSearch; } } } } while ( searchToPerform != null ); } } } /** * {@inheritDoc} */ public void runNotification( StudioProgressMonitor monitor ) { for ( int pi = 0; pi < searches.length; pi++ ) { EventRegistry.fireSearchUpdated( new SearchUpdateEvent( searches[pi], SearchUpdateEvent.EventDetail.SEARCH_PERFORMED ), this ); } } /** * Searches the directory and updates the browser model. * * @param browserConnection the browser connection * @param search the search * @param monitor the progress monitor */ public static void searchAndUpdateModel( IBrowserConnection browserConnection, ISearch search, StudioProgressMonitor monitor ) { if ( browserConnection.getConnection() == null ) { return; } try { if ( !monitor.isCanceled() ) { // add returning attributes for children and alias detection SearchParameter searchParameter = getSearchParameter( search ); ArrayList<ISearchResult> searchResultList = new ArrayList<ISearchResult>(); ArrayList<SearchContinuation> searchContinuationList = new ArrayList<SearchContinuation>(); StudioSearchResultEnumeration enumeration = null; // search try { enumeration = search( browserConnection, searchParameter, monitor ); // iterate through the search result while ( !monitor.isCanceled() && enumeration != null && enumeration.hasMore() ) { StudioSearchResult sr = enumeration.next(); boolean isContinuedSearchResult = sr.isContinuedSearchResult(); LdapUrl searchContinuationUrl = sr.getSearchContinuationUrl(); if ( searchContinuationUrl == null ) { Dn dn = sr.getDn(); IEntry entry = null; Connection resultConnection = sr.getConnection(); IBrowserConnection resultBrowserConnection = BrowserCorePlugin.getDefault() .getConnectionManager().getBrowserConnection( resultConnection ); if ( resultBrowserConnection == null ) { resultBrowserConnection = browserConnection; } // get entry from cache or create it entry = resultBrowserConnection.getEntryFromCache( dn ); if ( entry == null ) { entry = createAndCacheEntry( resultBrowserConnection, dn, monitor ); // If the entry is still null, we return // See https://issues.apache.org/jira/browse/DIRSTUDIO-865 if ( entry == null ) { return; } } // initialize special flags initFlags( entry, sr, searchParameter ); // fill the attributes fillAttributes( entry, sr, search.getSearchParameter() ); if ( isContinuedSearchResult ) { // the result is from a continued search // we create a special entry that displays the URL of the entry entry = new ContinuedSearchResultEntry( resultBrowserConnection, dn ); } searchResultList .add( new org.apache.directory.studio.ldapbrowser.core.model.impl.SearchResult( entry, search ) ); } else { //entry = new ContinuedSearchResultEntry( resultBrowserConnection, dn ); SearchContinuation searchContinuation = new SearchContinuation( search, searchContinuationUrl ); searchContinuationList.add( searchContinuation ); } monitor .reportProgress( searchResultList.size() == 1 ? BrowserCoreMessages.model__retrieved_1_entry : BrowserCoreMessages.bind( BrowserCoreMessages.model__retrieved_n_entries, new String[] { Integer.toString( searchResultList.size() ) } ) ); } } catch ( Exception e ) { int ldapStatusCode = JNDIUtils.getLdapStatusCode( e ); if ( ldapStatusCode == 3 || ldapStatusCode == 4 || ldapStatusCode == 11 ) { search.setCountLimitExceeded( true ); } else { monitor.reportError( e ); } } // check for response controls try { if ( enumeration != null ) { for ( org.apache.directory.api.ldap.model.message.Control control : enumeration .getResponseControls() ) { search.getResponseControls().add( control ); if ( control instanceof PagedResults ) { search.setCountLimitExceeded( ArrayUtils.isNotEmpty( ( ( PagedResults ) control ).getCookie() ) ); } } } } catch ( Exception e ) { monitor.reportError( e ); } monitor.reportProgress( searchResultList.size() == 1 ? BrowserCoreMessages.model__retrieved_1_entry : BrowserCoreMessages.bind( BrowserCoreMessages.model__retrieved_n_entries, new String[] { Integer.toString( searchResultList.size() ) } ) ); monitor.worked( 1 ); search.setSearchResults( ( ISearchResult[] ) searchResultList .toArray( new ISearchResult[searchResultList.size()] ) ); search.setSearchContinuations( ( SearchContinuation[] ) searchContinuationList .toArray( new SearchContinuation[searchContinuationList.size()] ) ); } } catch ( Exception e ) { if ( search != null ) { search.setSearchResults( new ISearchResult[0] ); } monitor.reportError( e ); } } public static StudioSearchResultEnumeration search( IBrowserConnection browserConnection, SearchParameter parameter, StudioProgressMonitor monitor ) { if ( browserConnection == null ) { return null; } String searchBase = parameter.getSearchBase().getName(); SearchControls searchControls = new SearchControls(); SearchScope scope = parameter.getScope(); switch ( scope ) { case OBJECT: searchControls.setSearchScope( SearchControls.OBJECT_SCOPE ); break; case ONELEVEL: searchControls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); break; case SUBTREE: searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE ); break; default: searchControls.setSearchScope( SearchControls.ONELEVEL_SCOPE ); } searchControls.setReturningAttributes( parameter.getReturningAttributes() ); searchControls.setCountLimit( parameter.getCountLimit() ); int timeLimit = parameter.getTimeLimit() * 1000; if ( timeLimit > 1 ) { timeLimit--; } searchControls.setTimeLimit( timeLimit ); String filter = parameter.getFilter(); AliasDereferencingMethod aliasesDereferencingMethod = parameter.getAliasesDereferencingMethod(); ReferralHandlingMethod referralsHandlingMethod = parameter.getReferralsHandlingMethod(); Control[] controls = null; if ( parameter.getControls() != null ) { controls = parameter.getControls().toArray( new Control[0] ); } StudioSearchResultEnumeration result = browserConnection .getConnection() .getConnectionWrapper() .search( searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, monitor, null ); return result; } private static SearchParameter getSearchParameter( ISearch search ) { SearchParameter searchParameter = ( SearchParameter ) search.getSearchParameter().clone(); // add children detetion attributes if ( search.isInitHasChildrenFlag() ) { if ( search.getBrowserConnection().getSchema() .hasAttributeTypeDescription( SchemaConstants.HAS_SUBORDINATES_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.HAS_SUBORDINATES_AT ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.HAS_SUBORDINATES_AT; searchParameter.setReturningAttributes( returningAttributes ); } else if ( search.getBrowserConnection().getSchema() .hasAttributeTypeDescription( SchemaConstants.NUM_SUBORDINATES_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.NUM_SUBORDINATES_AT ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.NUM_SUBORDINATES_AT; searchParameter.setReturningAttributes( returningAttributes ); } else if ( search.getBrowserConnection().getSchema() .hasAttributeTypeDescription( SchemaConstants.SUBORDINATE_COUNT_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.SUBORDINATE_COUNT_AT ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.SUBORDINATE_COUNT_AT; searchParameter.setReturningAttributes( returningAttributes ); } } // always add the objectClass attribute, we need it // - to detect alias and referral entries // - to determine the entry's icon // - to determine must and may attributes if ( !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.OBJECT_CLASS_AT ) && !Utils.containsIgnoreCase( Arrays.asList( searchParameter.getReturningAttributes() ), SchemaConstants.ALL_USER_ATTRIBUTES ) ) { String[] returningAttributes = new String[searchParameter.getReturningAttributes().length + 1]; System.arraycopy( searchParameter.getReturningAttributes(), 0, returningAttributes, 0, searchParameter.getReturningAttributes().length ); returningAttributes[returningAttributes.length - 1] = SchemaConstants.OBJECT_CLASS_AT; searchParameter.setReturningAttributes( returningAttributes ); } // filter controls if not supported by server if ( searchParameter.getControls() != null ) { IBrowserConnection connection = search.getBrowserConnection(); Set<String> supportedConrolSet = new HashSet<String>(); if ( connection.getRootDSE() != null && connection.getRootDSE().getAttribute( SchemaConstants.SUPPORTED_CONTROL_AT ) != null ) { IAttribute scAttribute = connection.getRootDSE().getAttribute( SchemaConstants.SUPPORTED_CONTROL_AT ); String[] supportedControls = scAttribute.getStringValues(); for ( int i = 0; i < supportedControls.length; i++ ) { supportedConrolSet.add( Strings.toLowerCase( supportedControls[i] ) ); } } List<Control> controls = searchParameter.getControls(); for ( Iterator<Control> it = controls.iterator(); it.hasNext(); ) { Control control = it.next(); if ( !supportedConrolSet.contains( Strings.toLowerCase( control.getOid() ) ) ) { it.remove(); } } } return searchParameter; } /** * Creates the entry and puts it into the BrowserConnection's entry cache. * * @param browserConnection the browser connection * @param dn the Dn of the entry * @param monitor * * @return the created entry */ private static IEntry createAndCacheEntry( IBrowserConnection browserConnection, Dn dn, StudioProgressMonitor monitor ) { StudioProgressMonitor dummyMonitor = new StudioProgressMonitor( monitor ); IEntry entry = null; // build tree to parent LinkedList<Dn> parentDnList = new LinkedList<Dn>(); Dn parentDn = dn; while ( parentDn != null && browserConnection.getEntryFromCache( parentDn ) == null ) { parentDnList.addFirst( parentDn ); parentDn = parentDn.getParent(); } for ( Dn aDn : parentDnList ) { parentDn = aDn.getParent(); if ( parentDn == null ) { // only the root DSE has a null parent entry = browserConnection.getRootDSE(); } else if ( !parentDn.isEmpty() && browserConnection.getEntryFromCache( parentDn ) != null ) { // a normal entry has a parent but the parent isn't the rootDSE IEntry parentEntry = browserConnection.getEntryFromCache( parentDn ); entry = new Entry( parentEntry, aDn.getRdn() ); entry.setDirectoryEntry( true ); parentEntry.addChild( entry ); parentEntry.setChildrenInitialized( true ); parentEntry.setHasMoreChildren( true ); parentEntry.setHasChildrenHint( true ); browserConnection.cacheEntry( entry ); } else { // we have a base Dn, check if the entry really exists in LDAP // this is to avoid that a node "dc=com" is created for "dc=example,dc=com" context entry SearchParameter searchParameter = new SearchParameter(); searchParameter.setSearchBase( aDn ); searchParameter.setFilter( null ); searchParameter.setReturningAttributes( ISearch.NO_ATTRIBUTES ); searchParameter.setScope( SearchScope.OBJECT ); searchParameter.setCountLimit( 1 ); searchParameter.setTimeLimit( 0 ); searchParameter.setAliasesDereferencingMethod( browserConnection.getAliasesDereferencingMethod() ); searchParameter.setReferralsHandlingMethod( browserConnection.getReferralsHandlingMethod() ); searchParameter.setInitHasChildrenFlag( true ); dummyMonitor.reset(); StudioSearchResultEnumeration enumeration = search( browserConnection, searchParameter, dummyMonitor ); try { if ( enumeration != null && enumeration.hasMore() ) { // create base Dn entry entry = new BaseDNEntry( aDn, browserConnection ); browserConnection.getRootDSE().addChild( entry ); browserConnection.cacheEntry( entry ); enumeration.close(); } } catch ( LdapException e ) { } } } return entry; } /** * Initializes the following flags of the entry: * <ul> * <li>hasChildren</li> * <li>isAlias</li> * <li>isReferral</li> * <li>isSubentry</li> * </ul> * * @param entry the entry * @param sr the the JNDI search result * @param searchParameter the search parameters */ private static void initFlags( IEntry entry, StudioSearchResult sr, SearchParameter searchParameter ) { for ( Attribute attribute : sr.getEntry() ) { if ( attribute != null ) { String attributeDescription = attribute.getUpId(); if ( SchemaConstants.OBJECT_CLASS_AT.equalsIgnoreCase( attributeDescription ) ) { if ( entry.getAttribute( attributeDescription ) != null ) { entry.deleteAttribute( entry.getAttribute( attributeDescription ) ); } entry.addAttribute( new org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute( entry, attributeDescription ) ); } for ( org.apache.directory.api.ldap.model.entry.Value valueObject : attribute ) { if ( valueObject.isHumanReadable() ) { String value = valueObject.getString(); if ( searchParameter.isInitHasChildrenFlag() ) { // hasChildren flag if ( SchemaConstants.HAS_SUBORDINATES_AT.equalsIgnoreCase( attributeDescription ) ) { if ( "FALSE".equalsIgnoreCase( value ) ) //$NON-NLS-1$ { entry.setHasChildrenHint( false ); } } if ( SchemaConstants.NUM_SUBORDINATES_AT.equalsIgnoreCase( attributeDescription ) ) { if ( "0".equalsIgnoreCase( value ) ) //$NON-NLS-1$ { entry.setHasChildrenHint( false ); } } if ( SchemaConstants.SUBORDINATE_COUNT_AT.equalsIgnoreCase( attributeDescription ) ) { if ( "0".equalsIgnoreCase( value ) ) //$NON-NLS-1$ { entry.setHasChildrenHint( false ); } } } if ( SchemaConstants.OBJECT_CLASS_AT.equalsIgnoreCase( attributeDescription ) ) { if ( SchemaConstants.ALIAS_OC.equalsIgnoreCase( value ) ) { entry.setAlias( true ); entry.setHasChildrenHint( false ); } if ( SchemaConstants.REFERRAL_OC.equalsIgnoreCase( value ) ) { entry.setReferral( true ); entry.setHasChildrenHint( false ); } IAttribute ocAttribute = entry.getAttribute( attributeDescription ); Value ocValue = new Value( ocAttribute, value ); ocAttribute.addValue( ocValue ); } } } } } if ( ( searchParameter.getControls() != null && searchParameter.getControls().contains( StudioControl.SUBENTRIES_CONTROL ) ) || ISearch.FILTER_SUBENTRY.equalsIgnoreCase( searchParameter.getFilter() ) ) { entry.setSubentry( true ); entry.setHasChildrenHint( false ); } } /** * Fills the attributes and values of the search result into the entry. * Clears existing attributes and values in the entry. * * @param entry the entry * @param sr the JNDI search result * @param searchParameter the search parameters */ private static void fillAttributes( IEntry entry, StudioSearchResult sr, SearchParameter searchParameter ) { if ( searchParameter.getReturningAttributes() == null || searchParameter.getReturningAttributes().length > 0 ) { // clear old attributes defined as returning attributes or clear all if ( searchParameter.getReturningAttributes() != null ) { String[] ras = searchParameter.getReturningAttributes(); // special case * if ( Arrays.asList( ras ).contains( SchemaConstants.ALL_USER_ATTRIBUTES ) ) { // clear all user attributes IAttribute[] oldAttributes = entry.getAttributes(); for ( int i = 0; oldAttributes != null && i < oldAttributes.length; i++ ) { if ( !oldAttributes[i].isOperationalAttribute() ) { entry.deleteAttribute( oldAttributes[i] ); } } } // special case + if ( Arrays.asList( ras ).contains( SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES ) ) { // clear all operational attributes IAttribute[] oldAttributes = entry.getAttributes(); for ( int i = 0; oldAttributes != null && i < oldAttributes.length; i++ ) { if ( oldAttributes[i].isOperationalAttribute() ) { entry.deleteAttribute( oldAttributes[i] ); } } } for ( int r = 0; r < ras.length; r++ ) { // clear attributes requested from server, also include sub-types AttributeHierarchy ah = entry.getAttributeWithSubtypes( ras[r] ); if ( ah != null ) { for ( Iterator<IAttribute> it = ah.iterator(); it.hasNext(); ) { IAttribute attribute = it.next(); entry.deleteAttribute( attribute ); } } } } else { // clear all IAttribute[] oldAttributes = entry.getAttributes(); for ( int i = 0; oldAttributes != null && i < oldAttributes.length; i++ ) { entry.deleteAttribute( oldAttributes[i] ); } } // additional clear old attributes if the record contains the attribute for ( Attribute attribute : sr.getEntry() ) { String attributeDescription = attribute.getUpId(); IAttribute oldAttribute = entry.getAttribute( attributeDescription ); if ( oldAttribute != null ) { entry.deleteAttribute( oldAttribute ); } } // set new attributes and values for ( Attribute attribute : sr.getEntry() ) { String attributeDescription = attribute.getUpId(); if ( attribute.iterator().hasNext() ) { IAttribute studioAttribute = null; if ( entry.getAttribute( attributeDescription ) == null ) { studioAttribute = new org.apache.directory.studio.ldapbrowser.core.model.impl.Attribute( entry, attributeDescription ); entry.addAttribute( studioAttribute ); } else { studioAttribute = entry.getAttribute( attributeDescription ); } for ( org.apache.directory.api.ldap.model.entry.Value value : attribute ) { if ( value.isHumanReadable() ) { studioAttribute.addValue( new Value( studioAttribute, value.getString() ) ); } else { studioAttribute.addValue( new Value( studioAttribute, value.getBytes() ) ); } } } } } } }
googleapis/google-cloud-java
37,870
java-managedkafka/proto-google-cloud-managedkafka-v1/src/main/java/com/google/cloud/managedkafka/v1/UpdateConsumerGroupRequest.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/managedkafka/v1/managed_kafka.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.managedkafka.v1; /** * * * <pre> * Request for UpdateConsumerGroup. * </pre> * * Protobuf type {@code google.cloud.managedkafka.v1.UpdateConsumerGroupRequest} */ public final class UpdateConsumerGroupRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.managedkafka.v1.UpdateConsumerGroupRequest) UpdateConsumerGroupRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateConsumerGroupRequest.newBuilder() to construct. private UpdateConsumerGroupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateConsumerGroupRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateConsumerGroupRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.managedkafka.v1.ManagedKafkaProto .internal_static_google_cloud_managedkafka_v1_UpdateConsumerGroupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.managedkafka.v1.ManagedKafkaProto .internal_static_google_cloud_managedkafka_v1_UpdateConsumerGroupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.class, com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.Builder.class); } private int bitField0_; public static final int UPDATE_MASK_FIELD_NUMBER = 1; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int CONSUMER_GROUP_FIELD_NUMBER = 2; private com.google.cloud.managedkafka.v1.ConsumerGroup consumerGroup_; /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the consumerGroup field is set. */ @java.lang.Override public boolean hasConsumerGroup() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The consumerGroup. */ @java.lang.Override public com.google.cloud.managedkafka.v1.ConsumerGroup getConsumerGroup() { return consumerGroup_ == null ? com.google.cloud.managedkafka.v1.ConsumerGroup.getDefaultInstance() : consumerGroup_; } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.managedkafka.v1.ConsumerGroupOrBuilder getConsumerGroupOrBuilder() { return consumerGroup_ == null ? com.google.cloud.managedkafka.v1.ConsumerGroup.getDefaultInstance() : consumerGroup_; } 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, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getConsumerGroup()); } 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, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getConsumerGroup()); } 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.managedkafka.v1.UpdateConsumerGroupRequest)) { return super.equals(obj); } com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest other = (com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (hasConsumerGroup() != other.hasConsumerGroup()) return false; if (hasConsumerGroup()) { if (!getConsumerGroup().equals(other.getConsumerGroup())) 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 (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } if (hasConsumerGroup()) { hash = (37 * hash) + CONSUMER_GROUP_FIELD_NUMBER; hash = (53 * hash) + getConsumerGroup().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest 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.managedkafka.v1.UpdateConsumerGroupRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest 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.managedkafka.v1.UpdateConsumerGroupRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest 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.managedkafka.v1.UpdateConsumerGroupRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest 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.managedkafka.v1.UpdateConsumerGroupRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest 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.managedkafka.v1.UpdateConsumerGroupRequest 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 UpdateConsumerGroup. * </pre> * * Protobuf type {@code google.cloud.managedkafka.v1.UpdateConsumerGroupRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.managedkafka.v1.UpdateConsumerGroupRequest) com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.managedkafka.v1.ManagedKafkaProto .internal_static_google_cloud_managedkafka_v1_UpdateConsumerGroupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.managedkafka.v1.ManagedKafkaProto .internal_static_google_cloud_managedkafka_v1_UpdateConsumerGroupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.class, com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.Builder.class); } // Construct using com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getUpdateMaskFieldBuilder(); getConsumerGroupFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } consumerGroup_ = null; if (consumerGroupBuilder_ != null) { consumerGroupBuilder_.dispose(); consumerGroupBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.managedkafka.v1.ManagedKafkaProto .internal_static_google_cloud_managedkafka_v1_UpdateConsumerGroupRequest_descriptor; } @java.lang.Override public com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest getDefaultInstanceForType() { return com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest build() { com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest buildPartial() { com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest result = new com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.consumerGroup_ = consumerGroupBuilder_ == null ? consumerGroup_ : consumerGroupBuilder_.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.managedkafka.v1.UpdateConsumerGroupRequest) { return mergeFrom((com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest other) { if (other == com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.hasConsumerGroup()) { mergeConsumerGroup(other.getConsumerGroup()); } 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(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getConsumerGroupFieldBuilder().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.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000001); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000001; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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. Field mask is used to specify the fields to be overwritten in the * ConsumerGroup resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. The * mask is required and a value of * will update all fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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_; } private com.google.cloud.managedkafka.v1.ConsumerGroup consumerGroup_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.managedkafka.v1.ConsumerGroup, com.google.cloud.managedkafka.v1.ConsumerGroup.Builder, com.google.cloud.managedkafka.v1.ConsumerGroupOrBuilder> consumerGroupBuilder_; /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the consumerGroup field is set. */ public boolean hasConsumerGroup() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The consumerGroup. */ public com.google.cloud.managedkafka.v1.ConsumerGroup getConsumerGroup() { if (consumerGroupBuilder_ == null) { return consumerGroup_ == null ? com.google.cloud.managedkafka.v1.ConsumerGroup.getDefaultInstance() : consumerGroup_; } else { return consumerGroupBuilder_.getMessage(); } } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConsumerGroup(com.google.cloud.managedkafka.v1.ConsumerGroup value) { if (consumerGroupBuilder_ == null) { if (value == null) { throw new NullPointerException(); } consumerGroup_ = value; } else { consumerGroupBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConsumerGroup( com.google.cloud.managedkafka.v1.ConsumerGroup.Builder builderForValue) { if (consumerGroupBuilder_ == null) { consumerGroup_ = builderForValue.build(); } else { consumerGroupBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeConsumerGroup(com.google.cloud.managedkafka.v1.ConsumerGroup value) { if (consumerGroupBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && consumerGroup_ != null && consumerGroup_ != com.google.cloud.managedkafka.v1.ConsumerGroup.getDefaultInstance()) { getConsumerGroupBuilder().mergeFrom(value); } else { consumerGroup_ = value; } } else { consumerGroupBuilder_.mergeFrom(value); } if (consumerGroup_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearConsumerGroup() { bitField0_ = (bitField0_ & ~0x00000002); consumerGroup_ = null; if (consumerGroupBuilder_ != null) { consumerGroupBuilder_.dispose(); consumerGroupBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.managedkafka.v1.ConsumerGroup.Builder getConsumerGroupBuilder() { bitField0_ |= 0x00000002; onChanged(); return getConsumerGroupFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.managedkafka.v1.ConsumerGroupOrBuilder getConsumerGroupOrBuilder() { if (consumerGroupBuilder_ != null) { return consumerGroupBuilder_.getMessageOrBuilder(); } else { return consumerGroup_ == null ? com.google.cloud.managedkafka.v1.ConsumerGroup.getDefaultInstance() : consumerGroup_; } } /** * * * <pre> * Required. The consumer group to update. Its `name` field must be populated. * </pre> * * <code> * .google.cloud.managedkafka.v1.ConsumerGroup consumer_group = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.managedkafka.v1.ConsumerGroup, com.google.cloud.managedkafka.v1.ConsumerGroup.Builder, com.google.cloud.managedkafka.v1.ConsumerGroupOrBuilder> getConsumerGroupFieldBuilder() { if (consumerGroupBuilder_ == null) { consumerGroupBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.managedkafka.v1.ConsumerGroup, com.google.cloud.managedkafka.v1.ConsumerGroup.Builder, com.google.cloud.managedkafka.v1.ConsumerGroupOrBuilder>( getConsumerGroup(), getParentForChildren(), isClean()); consumerGroup_ = null; } return consumerGroupBuilder_; } @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.managedkafka.v1.UpdateConsumerGroupRequest) } // @@protoc_insertion_point(class_scope:google.cloud.managedkafka.v1.UpdateConsumerGroupRequest) private static final com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest(); } public static com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateConsumerGroupRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateConsumerGroupRequest>() { @java.lang.Override public UpdateConsumerGroupRequest 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<UpdateConsumerGroupRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateConsumerGroupRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.managedkafka.v1.UpdateConsumerGroupRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,879
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteSnapshotRequest.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 Snapshots.Delete. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.DeleteSnapshotRequest} */ public final class DeleteSnapshotRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteSnapshotRequest) DeleteSnapshotRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteSnapshotRequest.newBuilder() to construct. private DeleteSnapshotRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteSnapshotRequest() { project_ = ""; requestId_ = ""; snapshot_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteSnapshotRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteSnapshotRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteSnapshotRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.DeleteSnapshotRequest.class, com.google.cloud.compute.v1.DeleteSnapshotRequest.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 SNAPSHOT_FIELD_NUMBER = 284874180; @SuppressWarnings("serial") private volatile java.lang.Object snapshot_ = ""; /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The snapshot. */ @java.lang.Override public java.lang.String getSnapshot() { java.lang.Object ref = snapshot_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); snapshot_ = s; return s; } } /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for snapshot. */ @java.lang.Override public com.google.protobuf.ByteString getSnapshotBytes() { java.lang.Object ref = snapshot_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); snapshot_ = 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(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(snapshot_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 284874180, snapshot_); } 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(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(snapshot_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(284874180, snapshot_); } 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.DeleteSnapshotRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.DeleteSnapshotRequest other = (com.google.cloud.compute.v1.DeleteSnapshotRequest) obj; if (!getProject().equals(other.getProject())) return false; if (hasRequestId() != other.hasRequestId()) return false; if (hasRequestId()) { if (!getRequestId().equals(other.getRequestId())) return false; } if (!getSnapshot().equals(other.getSnapshot())) 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) + SNAPSHOT_FIELD_NUMBER; hash = (53 * hash) + getSnapshot().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.DeleteSnapshotRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.DeleteSnapshotRequest 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.DeleteSnapshotRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.DeleteSnapshotRequest 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.DeleteSnapshotRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.DeleteSnapshotRequest 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.DeleteSnapshotRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.DeleteSnapshotRequest 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.DeleteSnapshotRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.DeleteSnapshotRequest 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.DeleteSnapshotRequest 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.DeleteSnapshotRequest 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.DeleteSnapshotRequest 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 Snapshots.Delete. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.DeleteSnapshotRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteSnapshotRequest) com.google.cloud.compute.v1.DeleteSnapshotRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteSnapshotRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteSnapshotRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.DeleteSnapshotRequest.class, com.google.cloud.compute.v1.DeleteSnapshotRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.DeleteSnapshotRequest.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_ = ""; snapshot_ = ""; 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_DeleteSnapshotRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.DeleteSnapshotRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.DeleteSnapshotRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.DeleteSnapshotRequest build() { com.google.cloud.compute.v1.DeleteSnapshotRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.DeleteSnapshotRequest buildPartial() { com.google.cloud.compute.v1.DeleteSnapshotRequest result = new com.google.cloud.compute.v1.DeleteSnapshotRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.DeleteSnapshotRequest 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.snapshot_ = snapshot_; } 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.DeleteSnapshotRequest) { return mergeFrom((com.google.cloud.compute.v1.DeleteSnapshotRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.DeleteSnapshotRequest other) { if (other == com.google.cloud.compute.v1.DeleteSnapshotRequest.getDefaultInstance()) return this; if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasRequestId()) { requestId_ = other.requestId_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getSnapshot().isEmpty()) { snapshot_ = other.snapshot_; 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 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 1820481738 case -2015973854: { snapshot_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case -2015973854 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 snapshot_ = ""; /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The snapshot. */ public java.lang.String getSnapshot() { java.lang.Object ref = snapshot_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); snapshot_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for snapshot. */ public com.google.protobuf.ByteString getSnapshotBytes() { java.lang.Object ref = snapshot_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); snapshot_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The snapshot to set. * @return This builder for chaining. */ public Builder setSnapshot(java.lang.String value) { if (value == null) { throw new NullPointerException(); } snapshot_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearSnapshot() { snapshot_ = getDefaultInstance().getSnapshot(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Name of the Snapshot resource to delete. * </pre> * * <code>string snapshot = 284874180 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for snapshot to set. * @return This builder for chaining. */ public Builder setSnapshotBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); snapshot_ = 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.DeleteSnapshotRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteSnapshotRequest) private static final com.google.cloud.compute.v1.DeleteSnapshotRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteSnapshotRequest(); } public static com.google.cloud.compute.v1.DeleteSnapshotRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteSnapshotRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteSnapshotRequest>() { @java.lang.Override public DeleteSnapshotRequest 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<DeleteSnapshotRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteSnapshotRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.DeleteSnapshotRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,932
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/CampaignAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/resources/campaign_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.resources; /** * <pre> * CampaignAssetSet is the linkage between a campaign and an asset set. * Adding a CampaignAssetSet links an asset set with a campaign. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.CampaignAssetSet} */ public final class CampaignAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.resources.CampaignAssetSet) CampaignAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use CampaignAssetSet.newBuilder() to construct. private CampaignAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CampaignAssetSet() { resourceName_ = ""; campaign_ = ""; assetSet_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CampaignAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v19_resources_CampaignAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v19_resources_CampaignAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.CampaignAssetSet.class, com.google.ads.googleads.v19.resources.CampaignAssetSet.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 campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CAMPAIGN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object campaign_ = ""; /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ @java.lang.Override public java.lang.String getCampaign() { java.lang.Object ref = campaign_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); campaign_ = s; return s; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ @java.lang.Override public com.google.protobuf.ByteString getCampaignBytes() { java.lang.Object ref = campaign_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); campaign_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(campaign_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, campaign_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, assetSet_); } if (status_ != com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(campaign_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, campaign_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, assetSet_); } if (status_ != com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v19.resources.CampaignAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v19.resources.CampaignAssetSet other = (com.google.ads.googleads.v19.resources.CampaignAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getCampaign() .equals(other.getCampaign())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (status_ != other.status_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + CAMPAIGN_FIELD_NUMBER; hash = (53 * hash) + getCampaign().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.resources.CampaignAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CampaignAssetSet 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.CampaignAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CampaignAssetSet 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.CampaignAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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> * CampaignAssetSet is the linkage between a campaign and an asset set. * Adding a CampaignAssetSet links an asset set with a campaign. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.CampaignAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.resources.CampaignAssetSet) com.google.ads.googleads.v19.resources.CampaignAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v19_resources_CampaignAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v19_resources_CampaignAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.CampaignAssetSet.class, com.google.ads.googleads.v19.resources.CampaignAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v19.resources.CampaignAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; campaign_ = ""; assetSet_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v19_resources_CampaignAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.resources.CampaignAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v19.resources.CampaignAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.resources.CampaignAssetSet build() { com.google.ads.googleads.v19.resources.CampaignAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.resources.CampaignAssetSet buildPartial() { com.google.ads.googleads.v19.resources.CampaignAssetSet result = new com.google.ads.googleads.v19.resources.CampaignAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.resources.CampaignAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.campaign_ = campaign_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v19.resources.CampaignAssetSet) { return mergeFrom((com.google.ads.googleads.v19.resources.CampaignAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.resources.CampaignAssetSet other) { if (other == com.google.ads.googleads.v19.resources.CampaignAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getCampaign().isEmpty()) { campaign_ = other.campaign_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { campaign_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = input.readEnum(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object campaign_ = ""; /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ public java.lang.String getCampaign() { java.lang.Object ref = campaign_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); campaign_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ public com.google.protobuf.ByteString getCampaignBytes() { java.lang.Object ref = campaign_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); campaign_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The campaign to set. * @return This builder for chaining. */ public Builder setCampaign( java.lang.String value) { if (value == null) { throw new NullPointerException(); } campaign_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearCampaign() { campaign_ = getDefaultInstance().getCampaign(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for campaign to set. * @return This builder for chaining. */ public Builder setCampaignBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); campaign_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.resources.CampaignAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.resources.CampaignAssetSet) private static final com.google.ads.googleads.v19.resources.CampaignAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.resources.CampaignAssetSet(); } public static com.google.ads.googleads.v19.resources.CampaignAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CampaignAssetSet> PARSER = new com.google.protobuf.AbstractParser<CampaignAssetSet>() { @java.lang.Override public CampaignAssetSet 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<CampaignAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CampaignAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.resources.CampaignAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,932
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/CampaignAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/resources/campaign_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.resources; /** * <pre> * CampaignAssetSet is the linkage between a campaign and an asset set. * Adding a CampaignAssetSet links an asset set with a campaign. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.CampaignAssetSet} */ public final class CampaignAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.resources.CampaignAssetSet) CampaignAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use CampaignAssetSet.newBuilder() to construct. private CampaignAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CampaignAssetSet() { resourceName_ = ""; campaign_ = ""; assetSet_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CampaignAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v20_resources_CampaignAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v20_resources_CampaignAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.CampaignAssetSet.class, com.google.ads.googleads.v20.resources.CampaignAssetSet.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 campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CAMPAIGN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object campaign_ = ""; /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ @java.lang.Override public java.lang.String getCampaign() { java.lang.Object ref = campaign_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); campaign_ = s; return s; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ @java.lang.Override public com.google.protobuf.ByteString getCampaignBytes() { java.lang.Object ref = campaign_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); campaign_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(campaign_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, campaign_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, assetSet_); } if (status_ != com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(campaign_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, campaign_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, assetSet_); } if (status_ != com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v20.resources.CampaignAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v20.resources.CampaignAssetSet other = (com.google.ads.googleads.v20.resources.CampaignAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getCampaign() .equals(other.getCampaign())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (status_ != other.status_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + CAMPAIGN_FIELD_NUMBER; hash = (53 * hash) + getCampaign().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.resources.CampaignAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CampaignAssetSet 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.CampaignAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CampaignAssetSet 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.CampaignAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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> * CampaignAssetSet is the linkage between a campaign and an asset set. * Adding a CampaignAssetSet links an asset set with a campaign. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.CampaignAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.resources.CampaignAssetSet) com.google.ads.googleads.v20.resources.CampaignAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v20_resources_CampaignAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v20_resources_CampaignAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.CampaignAssetSet.class, com.google.ads.googleads.v20.resources.CampaignAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v20.resources.CampaignAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; campaign_ = ""; assetSet_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v20_resources_CampaignAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.resources.CampaignAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v20.resources.CampaignAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.resources.CampaignAssetSet build() { com.google.ads.googleads.v20.resources.CampaignAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.resources.CampaignAssetSet buildPartial() { com.google.ads.googleads.v20.resources.CampaignAssetSet result = new com.google.ads.googleads.v20.resources.CampaignAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.resources.CampaignAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.campaign_ = campaign_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v20.resources.CampaignAssetSet) { return mergeFrom((com.google.ads.googleads.v20.resources.CampaignAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.resources.CampaignAssetSet other) { if (other == com.google.ads.googleads.v20.resources.CampaignAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getCampaign().isEmpty()) { campaign_ = other.campaign_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { campaign_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = input.readEnum(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object campaign_ = ""; /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ public java.lang.String getCampaign() { java.lang.Object ref = campaign_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); campaign_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ public com.google.protobuf.ByteString getCampaignBytes() { java.lang.Object ref = campaign_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); campaign_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The campaign to set. * @return This builder for chaining. */ public Builder setCampaign( java.lang.String value) { if (value == null) { throw new NullPointerException(); } campaign_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearCampaign() { campaign_ = getDefaultInstance().getCampaign(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for campaign to set. * @return This builder for chaining. */ public Builder setCampaignBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); campaign_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.resources.CampaignAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.resources.CampaignAssetSet) private static final com.google.ads.googleads.v20.resources.CampaignAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.resources.CampaignAssetSet(); } public static com.google.ads.googleads.v20.resources.CampaignAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CampaignAssetSet> PARSER = new com.google.protobuf.AbstractParser<CampaignAssetSet>() { @java.lang.Override public CampaignAssetSet 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<CampaignAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CampaignAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.resources.CampaignAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,932
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/CampaignAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/resources/campaign_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.resources; /** * <pre> * CampaignAssetSet is the linkage between a campaign and an asset set. * Adding a CampaignAssetSet links an asset set with a campaign. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.CampaignAssetSet} */ public final class CampaignAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.CampaignAssetSet) CampaignAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use CampaignAssetSet.newBuilder() to construct. private CampaignAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CampaignAssetSet() { resourceName_ = ""; campaign_ = ""; assetSet_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CampaignAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v21_resources_CampaignAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v21_resources_CampaignAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.CampaignAssetSet.class, com.google.ads.googleads.v21.resources.CampaignAssetSet.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 campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CAMPAIGN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object campaign_ = ""; /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ @java.lang.Override public java.lang.String getCampaign() { java.lang.Object ref = campaign_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); campaign_ = s; return s; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ @java.lang.Override public com.google.protobuf.ByteString getCampaignBytes() { java.lang.Object ref = campaign_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); campaign_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(campaign_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, campaign_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, assetSet_); } if (status_ != com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(campaign_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, campaign_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, assetSet_); } if (status_ != com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v21.resources.CampaignAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v21.resources.CampaignAssetSet other = (com.google.ads.googleads.v21.resources.CampaignAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getCampaign() .equals(other.getCampaign())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (status_ != other.status_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + CAMPAIGN_FIELD_NUMBER; hash = (53 * hash) + getCampaign().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.resources.CampaignAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CampaignAssetSet 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.CampaignAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CampaignAssetSet 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.CampaignAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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.CampaignAssetSet 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> * CampaignAssetSet is the linkage between a campaign and an asset set. * Adding a CampaignAssetSet links an asset set with a campaign. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.CampaignAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.CampaignAssetSet) com.google.ads.googleads.v21.resources.CampaignAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v21_resources_CampaignAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v21_resources_CampaignAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.CampaignAssetSet.class, com.google.ads.googleads.v21.resources.CampaignAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v21.resources.CampaignAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; campaign_ = ""; assetSet_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.resources.CampaignAssetSetProto.internal_static_google_ads_googleads_v21_resources_CampaignAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.resources.CampaignAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v21.resources.CampaignAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.resources.CampaignAssetSet build() { com.google.ads.googleads.v21.resources.CampaignAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.resources.CampaignAssetSet buildPartial() { com.google.ads.googleads.v21.resources.CampaignAssetSet result = new com.google.ads.googleads.v21.resources.CampaignAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.resources.CampaignAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.campaign_ = campaign_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v21.resources.CampaignAssetSet) { return mergeFrom((com.google.ads.googleads.v21.resources.CampaignAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.resources.CampaignAssetSet other) { if (other == com.google.ads.googleads.v21.resources.CampaignAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getCampaign().isEmpty()) { campaign_ = other.campaign_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { campaign_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = input.readEnum(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the campaign asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object campaign_ = ""; /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ public java.lang.String getCampaign() { java.lang.Object ref = campaign_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); campaign_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ public com.google.protobuf.ByteString getCampaignBytes() { java.lang.Object ref = campaign_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); campaign_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The campaign to set. * @return This builder for chaining. */ public Builder setCampaign( java.lang.String value) { if (value == null) { throw new NullPointerException(); } campaign_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearCampaign() { campaign_ = getDefaultInstance().getCampaign(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The campaign to which this asset set is linked. * </pre> * * <code>string campaign = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for campaign to set. * @return This builder for chaining. */ public Builder setCampaignBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); campaign_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the campaign. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the campaign asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.resources.CampaignAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.CampaignAssetSet) private static final com.google.ads.googleads.v21.resources.CampaignAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.CampaignAssetSet(); } public static com.google.ads.googleads.v21.resources.CampaignAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CampaignAssetSet> PARSER = new com.google.protobuf.AbstractParser<CampaignAssetSet>() { @java.lang.Override public CampaignAssetSet 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<CampaignAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CampaignAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.resources.CampaignAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,807
java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/UpdateDataAttributeBindingRequest.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/data_taxonomy.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataplex.v1; /** * * * <pre> * Update DataAttributeBinding request. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest} */ public final class UpdateDataAttributeBindingRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) UpdateDataAttributeBindingRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateDataAttributeBindingRequest.newBuilder() to construct. private UpdateDataAttributeBindingRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateDataAttributeBindingRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateDataAttributeBindingRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.DataTaxonomyProto .internal_static_google_cloud_dataplex_v1_UpdateDataAttributeBindingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.DataTaxonomyProto .internal_static_google_cloud_dataplex_v1_UpdateDataAttributeBindingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.class, com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.Builder.class); } private int bitField0_; public static final int UPDATE_MASK_FIELD_NUMBER = 1; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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 of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int DATA_ATTRIBUTE_BINDING_FIELD_NUMBER = 2; private com.google.cloud.dataplex.v1.DataAttributeBinding dataAttributeBinding_; /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the dataAttributeBinding field is set. */ @java.lang.Override public boolean hasDataAttributeBinding() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The dataAttributeBinding. */ @java.lang.Override public com.google.cloud.dataplex.v1.DataAttributeBinding getDataAttributeBinding() { return dataAttributeBinding_ == null ? com.google.cloud.dataplex.v1.DataAttributeBinding.getDefaultInstance() : dataAttributeBinding_; } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.dataplex.v1.DataAttributeBindingOrBuilder getDataAttributeBindingOrBuilder() { return dataAttributeBinding_ == null ? com.google.cloud.dataplex.v1.DataAttributeBinding.getDefaultInstance() : dataAttributeBinding_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_ = false; /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getDataAttributeBinding()); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getDataAttributeBinding()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest)) { return super.equals(obj); } com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest other = (com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (hasDataAttributeBinding() != other.hasDataAttributeBinding()) return false; if (hasDataAttributeBinding()) { if (!getDataAttributeBinding().equals(other.getDataAttributeBinding())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } if (hasDataAttributeBinding()) { hash = (37 * hash) + DATA_ATTRIBUTE_BINDING_FIELD_NUMBER; hash = (53 * hash) + getDataAttributeBinding().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest 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.UpdateDataAttributeBindingRequest 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> * Update DataAttributeBinding request. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.DataTaxonomyProto .internal_static_google_cloud_dataplex_v1_UpdateDataAttributeBindingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.DataTaxonomyProto .internal_static_google_cloud_dataplex_v1_UpdateDataAttributeBindingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.class, com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.Builder.class); } // Construct using com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getUpdateMaskFieldBuilder(); getDataAttributeBindingFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } dataAttributeBinding_ = null; if (dataAttributeBindingBuilder_ != null) { dataAttributeBindingBuilder_.dispose(); dataAttributeBindingBuilder_ = null; } validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataplex.v1.DataTaxonomyProto .internal_static_google_cloud_dataplex_v1_UpdateDataAttributeBindingRequest_descriptor; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest getDefaultInstanceForType() { return com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest build() { com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest buildPartial() { com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest result = new com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.dataAttributeBinding_ = dataAttributeBindingBuilder_ == null ? dataAttributeBinding_ : dataAttributeBindingBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) { return mergeFrom((com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest other) { if (other == com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.hasDataAttributeBinding()) { mergeDataAttributeBinding(other.getDataAttributeBinding()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( getDataAttributeBindingFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 24: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private 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 of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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 of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000001); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000001; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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 of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.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_; } private com.google.cloud.dataplex.v1.DataAttributeBinding dataAttributeBinding_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.DataAttributeBinding, com.google.cloud.dataplex.v1.DataAttributeBinding.Builder, com.google.cloud.dataplex.v1.DataAttributeBindingOrBuilder> dataAttributeBindingBuilder_; /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the dataAttributeBinding field is set. */ public boolean hasDataAttributeBinding() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The dataAttributeBinding. */ public com.google.cloud.dataplex.v1.DataAttributeBinding getDataAttributeBinding() { if (dataAttributeBindingBuilder_ == null) { return dataAttributeBinding_ == null ? com.google.cloud.dataplex.v1.DataAttributeBinding.getDefaultInstance() : dataAttributeBinding_; } else { return dataAttributeBindingBuilder_.getMessage(); } } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDataAttributeBinding( com.google.cloud.dataplex.v1.DataAttributeBinding value) { if (dataAttributeBindingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } dataAttributeBinding_ = value; } else { dataAttributeBindingBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDataAttributeBinding( com.google.cloud.dataplex.v1.DataAttributeBinding.Builder builderForValue) { if (dataAttributeBindingBuilder_ == null) { dataAttributeBinding_ = builderForValue.build(); } else { dataAttributeBindingBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeDataAttributeBinding( com.google.cloud.dataplex.v1.DataAttributeBinding value) { if (dataAttributeBindingBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && dataAttributeBinding_ != null && dataAttributeBinding_ != com.google.cloud.dataplex.v1.DataAttributeBinding.getDefaultInstance()) { getDataAttributeBindingBuilder().mergeFrom(value); } else { dataAttributeBinding_ = value; } } else { dataAttributeBindingBuilder_.mergeFrom(value); } if (dataAttributeBinding_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearDataAttributeBinding() { bitField0_ = (bitField0_ & ~0x00000002); dataAttributeBinding_ = null; if (dataAttributeBindingBuilder_ != null) { dataAttributeBindingBuilder_.dispose(); dataAttributeBindingBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dataplex.v1.DataAttributeBinding.Builder getDataAttributeBindingBuilder() { bitField0_ |= 0x00000002; onChanged(); return getDataAttributeBindingFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dataplex.v1.DataAttributeBindingOrBuilder getDataAttributeBindingOrBuilder() { if (dataAttributeBindingBuilder_ != null) { return dataAttributeBindingBuilder_.getMessageOrBuilder(); } else { return dataAttributeBinding_ == null ? com.google.cloud.dataplex.v1.DataAttributeBinding.getDefaultInstance() : dataAttributeBinding_; } } /** * * * <pre> * Required. Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.DataAttributeBinding data_attribute_binding = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.DataAttributeBinding, com.google.cloud.dataplex.v1.DataAttributeBinding.Builder, com.google.cloud.dataplex.v1.DataAttributeBindingOrBuilder> getDataAttributeBindingFieldBuilder() { if (dataAttributeBindingBuilder_ == null) { dataAttributeBindingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.DataAttributeBinding, com.google.cloud.dataplex.v1.DataAttributeBinding.Builder, com.google.cloud.dataplex.v1.DataAttributeBindingOrBuilder>( getDataAttributeBinding(), getParentForChildren(), isClean()); dataAttributeBinding_ = null; } return dataAttributeBindingBuilder_; } private boolean validateOnly_; /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest) private static final com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest(); } public static com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateDataAttributeBindingRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateDataAttributeBindingRequest>() { @java.lang.Override public UpdateDataAttributeBindingRequest 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<UpdateDataAttributeBindingRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateDataAttributeBindingRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateDataAttributeBindingRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
38,073
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonPacketMirroringsStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1.stub; import static com.google.cloud.compute.v1.PacketMirroringsClient.AggregatedListPagedResponse; import static com.google.cloud.compute.v1.PacketMirroringsClient.ListPagedResponse; import com.google.api.core.InternalApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.httpjson.ApiMethodDescriptor; import com.google.api.gax.httpjson.HttpJsonCallSettings; import com.google.api.gax.httpjson.HttpJsonOperationSnapshot; import com.google.api.gax.httpjson.HttpJsonStubCallableFactory; import com.google.api.gax.httpjson.ProtoMessageRequestFormatter; import com.google.api.gax.httpjson.ProtoMessageResponseParser; import com.google.api.gax.httpjson.ProtoRestSerializer; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.AggregatedListPacketMirroringsRequest; import com.google.cloud.compute.v1.DeletePacketMirroringRequest; import com.google.cloud.compute.v1.GetPacketMirroringRequest; import com.google.cloud.compute.v1.InsertPacketMirroringRequest; import com.google.cloud.compute.v1.ListPacketMirroringsRequest; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.Operation.Status; import com.google.cloud.compute.v1.PacketMirroring; import com.google.cloud.compute.v1.PacketMirroringAggregatedList; import com.google.cloud.compute.v1.PacketMirroringList; import com.google.cloud.compute.v1.PatchPacketMirroringRequest; import com.google.cloud.compute.v1.TestIamPermissionsPacketMirroringRequest; import com.google.cloud.compute.v1.TestPermissionsResponse; import com.google.protobuf.TypeRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * REST stub implementation for the PacketMirrorings service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonPacketMirroringsStub extends PacketMirroringsStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder().add(Operation.getDescriptor()).build(); private static final ApiMethodDescriptor< AggregatedListPacketMirroringsRequest, PacketMirroringAggregatedList> aggregatedListMethodDescriptor = ApiMethodDescriptor .<AggregatedListPacketMirroringsRequest, PacketMirroringAggregatedList>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/AggregatedList") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<AggregatedListPacketMirroringsRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/aggregated/packetMirrorings", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<AggregatedListPacketMirroringsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<AggregatedListPacketMirroringsRequest> serializer = ProtoRestSerializer.create(); if (request.hasFilter()) { serializer.putQueryParam(fields, "filter", request.getFilter()); } if (request.hasIncludeAllScopes()) { serializer.putQueryParam( fields, "includeAllScopes", request.getIncludeAllScopes()); } if (request.hasMaxResults()) { serializer.putQueryParam( fields, "maxResults", request.getMaxResults()); } if (request.hasOrderBy()) { serializer.putQueryParam(fields, "orderBy", request.getOrderBy()); } if (request.hasPageToken()) { serializer.putQueryParam(fields, "pageToken", request.getPageToken()); } if (request.hasReturnPartialSuccess()) { serializer.putQueryParam( fields, "returnPartialSuccess", request.getReturnPartialSuccess()); } if (request.hasServiceProjectNumber()) { serializer.putQueryParam( fields, "serviceProjectNumber", request.getServiceProjectNumber()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<PacketMirroringAggregatedList>newBuilder() .setDefaultInstance(PacketMirroringAggregatedList.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<DeletePacketMirroringRequest, Operation> deleteMethodDescriptor = ApiMethodDescriptor.<DeletePacketMirroringRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/Delete") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeletePacketMirroringRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/regions/{region}/packetMirrorings/{packetMirroring}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeletePacketMirroringRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "packetMirroring", request.getPacketMirroring()); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "region", request.getRegion()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeletePacketMirroringRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeletePacketMirroringRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getRegion()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<GetPacketMirroringRequest, PacketMirroring> getMethodDescriptor = ApiMethodDescriptor.<GetPacketMirroringRequest, PacketMirroring>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/Get") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetPacketMirroringRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/regions/{region}/packetMirrorings/{packetMirroring}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetPacketMirroringRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "packetMirroring", request.getPacketMirroring()); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "region", request.getRegion()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetPacketMirroringRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<PacketMirroring>newBuilder() .setDefaultInstance(PacketMirroring.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<InsertPacketMirroringRequest, Operation> insertMethodDescriptor = ApiMethodDescriptor.<InsertPacketMirroringRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/Insert") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<InsertPacketMirroringRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/regions/{region}/packetMirrorings", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<InsertPacketMirroringRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "region", request.getRegion()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<InsertPacketMirroringRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "packetMirroringResource", request.getPacketMirroringResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (InsertPacketMirroringRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getRegion()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<ListPacketMirroringsRequest, PacketMirroringList> listMethodDescriptor = ApiMethodDescriptor.<ListPacketMirroringsRequest, PacketMirroringList>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/List") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListPacketMirroringsRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/regions/{region}/packetMirrorings", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListPacketMirroringsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "region", request.getRegion()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListPacketMirroringsRequest> serializer = ProtoRestSerializer.create(); if (request.hasFilter()) { serializer.putQueryParam(fields, "filter", request.getFilter()); } if (request.hasMaxResults()) { serializer.putQueryParam( fields, "maxResults", request.getMaxResults()); } if (request.hasOrderBy()) { serializer.putQueryParam(fields, "orderBy", request.getOrderBy()); } if (request.hasPageToken()) { serializer.putQueryParam(fields, "pageToken", request.getPageToken()); } if (request.hasReturnPartialSuccess()) { serializer.putQueryParam( fields, "returnPartialSuccess", request.getReturnPartialSuccess()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<PacketMirroringList>newBuilder() .setDefaultInstance(PacketMirroringList.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<PatchPacketMirroringRequest, Operation> patchMethodDescriptor = ApiMethodDescriptor.<PatchPacketMirroringRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/Patch") .setHttpMethod("PATCH") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<PatchPacketMirroringRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/regions/{region}/packetMirrorings/{packetMirroring}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<PatchPacketMirroringRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "packetMirroring", request.getPacketMirroring()); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "region", request.getRegion()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<PatchPacketMirroringRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "packetMirroringResource", request.getPacketMirroringResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (PatchPacketMirroringRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); opName.append(":").append(request.getRegion()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor< TestIamPermissionsPacketMirroringRequest, TestPermissionsResponse> testIamPermissionsMethodDescriptor = ApiMethodDescriptor .<TestIamPermissionsPacketMirroringRequest, TestPermissionsResponse>newBuilder() .setFullMethodName("google.cloud.compute.v1.PacketMirrorings/TestIamPermissions") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter .<TestIamPermissionsPacketMirroringRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/regions/{region}/packetMirrorings/{resource}/testIamPermissions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsPacketMirroringRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "region", request.getRegion()); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsPacketMirroringRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "testPermissionsRequestResource", request.getTestPermissionsRequestResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<TestPermissionsResponse>newBuilder() .setDefaultInstance(TestPermissionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<AggregatedListPacketMirroringsRequest, PacketMirroringAggregatedList> aggregatedListCallable; private final UnaryCallable<AggregatedListPacketMirroringsRequest, AggregatedListPagedResponse> aggregatedListPagedCallable; private final UnaryCallable<DeletePacketMirroringRequest, Operation> deleteCallable; private final OperationCallable<DeletePacketMirroringRequest, Operation, Operation> deleteOperationCallable; private final UnaryCallable<GetPacketMirroringRequest, PacketMirroring> getCallable; private final UnaryCallable<InsertPacketMirroringRequest, Operation> insertCallable; private final OperationCallable<InsertPacketMirroringRequest, Operation, Operation> insertOperationCallable; private final UnaryCallable<ListPacketMirroringsRequest, PacketMirroringList> listCallable; private final UnaryCallable<ListPacketMirroringsRequest, ListPagedResponse> listPagedCallable; private final UnaryCallable<PatchPacketMirroringRequest, Operation> patchCallable; private final OperationCallable<PatchPacketMirroringRequest, Operation, Operation> patchOperationCallable; private final UnaryCallable<TestIamPermissionsPacketMirroringRequest, TestPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final HttpJsonRegionOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonPacketMirroringsStub create(PacketMirroringsStubSettings settings) throws IOException { return new HttpJsonPacketMirroringsStub(settings, ClientContext.create(settings)); } public static final HttpJsonPacketMirroringsStub create(ClientContext clientContext) throws IOException { return new HttpJsonPacketMirroringsStub( PacketMirroringsStubSettings.newBuilder().build(), clientContext); } public static final HttpJsonPacketMirroringsStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonPacketMirroringsStub( PacketMirroringsStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonPacketMirroringsStub, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected HttpJsonPacketMirroringsStub( PacketMirroringsStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonPacketMirroringsCallableFactory()); } /** * Constructs an instance of HttpJsonPacketMirroringsStub, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected HttpJsonPacketMirroringsStub( PacketMirroringsStubSettings settings, ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.httpJsonOperationsStub = HttpJsonRegionOperationsStub.create(clientContext, callableFactory); HttpJsonCallSettings<AggregatedListPacketMirroringsRequest, PacketMirroringAggregatedList> aggregatedListTransportSettings = HttpJsonCallSettings .<AggregatedListPacketMirroringsRequest, PacketMirroringAggregatedList>newBuilder() .setMethodDescriptor(aggregatedListMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); return builder.build(); }) .build(); HttpJsonCallSettings<DeletePacketMirroringRequest, Operation> deleteTransportSettings = HttpJsonCallSettings.<DeletePacketMirroringRequest, Operation>newBuilder() .setMethodDescriptor(deleteMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("packet_mirroring", String.valueOf(request.getPacketMirroring())); builder.add("project", String.valueOf(request.getProject())); builder.add("region", String.valueOf(request.getRegion())); return builder.build(); }) .build(); HttpJsonCallSettings<GetPacketMirroringRequest, PacketMirroring> getTransportSettings = HttpJsonCallSettings.<GetPacketMirroringRequest, PacketMirroring>newBuilder() .setMethodDescriptor(getMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("packet_mirroring", String.valueOf(request.getPacketMirroring())); builder.add("project", String.valueOf(request.getProject())); builder.add("region", String.valueOf(request.getRegion())); return builder.build(); }) .build(); HttpJsonCallSettings<InsertPacketMirroringRequest, Operation> insertTransportSettings = HttpJsonCallSettings.<InsertPacketMirroringRequest, Operation>newBuilder() .setMethodDescriptor(insertMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("region", String.valueOf(request.getRegion())); return builder.build(); }) .build(); HttpJsonCallSettings<ListPacketMirroringsRequest, PacketMirroringList> listTransportSettings = HttpJsonCallSettings.<ListPacketMirroringsRequest, PacketMirroringList>newBuilder() .setMethodDescriptor(listMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("region", String.valueOf(request.getRegion())); return builder.build(); }) .build(); HttpJsonCallSettings<PatchPacketMirroringRequest, Operation> patchTransportSettings = HttpJsonCallSettings.<PatchPacketMirroringRequest, Operation>newBuilder() .setMethodDescriptor(patchMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("packet_mirroring", String.valueOf(request.getPacketMirroring())); builder.add("project", String.valueOf(request.getProject())); builder.add("region", String.valueOf(request.getRegion())); return builder.build(); }) .build(); HttpJsonCallSettings<TestIamPermissionsPacketMirroringRequest, TestPermissionsResponse> testIamPermissionsTransportSettings = HttpJsonCallSettings .<TestIamPermissionsPacketMirroringRequest, TestPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("region", String.valueOf(request.getRegion())); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.aggregatedListCallable = callableFactory.createUnaryCallable( aggregatedListTransportSettings, settings.aggregatedListSettings(), clientContext); this.aggregatedListPagedCallable = callableFactory.createPagedCallable( aggregatedListTransportSettings, settings.aggregatedListSettings(), clientContext); this.deleteCallable = callableFactory.createUnaryCallable( deleteTransportSettings, settings.deleteSettings(), clientContext); this.deleteOperationCallable = callableFactory.createOperationCallable( deleteTransportSettings, settings.deleteOperationSettings(), clientContext, httpJsonOperationsStub); this.getCallable = callableFactory.createUnaryCallable( getTransportSettings, settings.getSettings(), clientContext); this.insertCallable = callableFactory.createUnaryCallable( insertTransportSettings, settings.insertSettings(), clientContext); this.insertOperationCallable = callableFactory.createOperationCallable( insertTransportSettings, settings.insertOperationSettings(), clientContext, httpJsonOperationsStub); this.listCallable = callableFactory.createUnaryCallable( listTransportSettings, settings.listSettings(), clientContext); this.listPagedCallable = callableFactory.createPagedCallable( listTransportSettings, settings.listSettings(), clientContext); this.patchCallable = callableFactory.createUnaryCallable( patchTransportSettings, settings.patchSettings(), clientContext); this.patchOperationCallable = callableFactory.createOperationCallable( patchTransportSettings, settings.patchOperationSettings(), clientContext, httpJsonOperationsStub); this.testIamPermissionsCallable = callableFactory.createUnaryCallable( testIamPermissionsTransportSettings, settings.testIamPermissionsSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(aggregatedListMethodDescriptor); methodDescriptors.add(deleteMethodDescriptor); methodDescriptors.add(getMethodDescriptor); methodDescriptors.add(insertMethodDescriptor); methodDescriptors.add(listMethodDescriptor); methodDescriptors.add(patchMethodDescriptor); methodDescriptors.add(testIamPermissionsMethodDescriptor); return methodDescriptors; } @Override public UnaryCallable<AggregatedListPacketMirroringsRequest, PacketMirroringAggregatedList> aggregatedListCallable() { return aggregatedListCallable; } @Override public UnaryCallable<AggregatedListPacketMirroringsRequest, AggregatedListPagedResponse> aggregatedListPagedCallable() { return aggregatedListPagedCallable; } @Override public UnaryCallable<DeletePacketMirroringRequest, Operation> deleteCallable() { return deleteCallable; } @Override public OperationCallable<DeletePacketMirroringRequest, Operation, Operation> deleteOperationCallable() { return deleteOperationCallable; } @Override public UnaryCallable<GetPacketMirroringRequest, PacketMirroring> getCallable() { return getCallable; } @Override public UnaryCallable<InsertPacketMirroringRequest, Operation> insertCallable() { return insertCallable; } @Override public OperationCallable<InsertPacketMirroringRequest, Operation, Operation> insertOperationCallable() { return insertOperationCallable; } @Override public UnaryCallable<ListPacketMirroringsRequest, PacketMirroringList> listCallable() { return listCallable; } @Override public UnaryCallable<ListPacketMirroringsRequest, ListPagedResponse> listPagedCallable() { return listPagedCallable; } @Override public UnaryCallable<PatchPacketMirroringRequest, Operation> patchCallable() { return patchCallable; } @Override public OperationCallable<PatchPacketMirroringRequest, Operation, Operation> patchOperationCallable() { return patchOperationCallable; } @Override public UnaryCallable<TestIamPermissionsPacketMirroringRequest, TestPermissionsResponse> testIamPermissionsCallable() { return testIamPermissionsCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
googleapis/google-cloud-java
37,785
java-discoveryengine/proto-google-cloud-discoveryengine-v1/src/main/java/com/google/cloud/discoveryengine/v1/ListConversationsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/discoveryengine/v1/conversational_search_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1; /** * * * <pre> * Response for ListConversations method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.ListConversationsResponse} */ public final class ListConversationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1.ListConversationsResponse) ListConversationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListConversationsResponse.newBuilder() to construct. private ListConversationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListConversationsResponse() { conversations_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListConversationsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_ListConversationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_ListConversationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.ListConversationsResponse.class, com.google.cloud.discoveryengine.v1.ListConversationsResponse.Builder.class); } public static final int CONVERSATIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.discoveryengine.v1.Conversation> conversations_; /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.discoveryengine.v1.Conversation> getConversationsList() { return conversations_; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.discoveryengine.v1.ConversationOrBuilder> getConversationsOrBuilderList() { return conversations_; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ @java.lang.Override public int getConversationsCount() { return conversations_.size(); } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ @java.lang.Override public com.google.cloud.discoveryengine.v1.Conversation getConversations(int index) { return conversations_.get(index); } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ @java.lang.Override public com.google.cloud.discoveryengine.v1.ConversationOrBuilder getConversationsOrBuilder( int index) { return conversations_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < conversations_.size(); i++) { output.writeMessage(1, conversations_.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 < conversations_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, conversations_.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.ListConversationsResponse)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1.ListConversationsResponse other = (com.google.cloud.discoveryengine.v1.ListConversationsResponse) obj; if (!getConversationsList().equals(other.getConversationsList())) 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 (getConversationsCount() > 0) { hash = (37 * hash) + CONVERSATIONS_FIELD_NUMBER; hash = (53 * hash) + getConversationsList().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.ListConversationsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.ListConversationsResponse 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.ListConversationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.ListConversationsResponse 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.ListConversationsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.ListConversationsResponse 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.ListConversationsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.ListConversationsResponse 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.ListConversationsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.ListConversationsResponse 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.ListConversationsResponse 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.ListConversationsResponse 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.ListConversationsResponse 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 ListConversations method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.ListConversationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1.ListConversationsResponse) com.google.cloud.discoveryengine.v1.ListConversationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_ListConversationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_ListConversationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.ListConversationsResponse.class, com.google.cloud.discoveryengine.v1.ListConversationsResponse.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1.ListConversationsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (conversationsBuilder_ == null) { conversations_ = java.util.Collections.emptyList(); } else { conversations_ = null; conversationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_ListConversationsResponse_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1.ListConversationsResponse getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1.ListConversationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1.ListConversationsResponse build() { com.google.cloud.discoveryengine.v1.ListConversationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1.ListConversationsResponse buildPartial() { com.google.cloud.discoveryengine.v1.ListConversationsResponse result = new com.google.cloud.discoveryengine.v1.ListConversationsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.discoveryengine.v1.ListConversationsResponse result) { if (conversationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { conversations_ = java.util.Collections.unmodifiableList(conversations_); bitField0_ = (bitField0_ & ~0x00000001); } result.conversations_ = conversations_; } else { result.conversations_ = conversationsBuilder_.build(); } } private void buildPartial0( com.google.cloud.discoveryengine.v1.ListConversationsResponse 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.ListConversationsResponse) { return mergeFrom((com.google.cloud.discoveryengine.v1.ListConversationsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1.ListConversationsResponse other) { if (other == com.google.cloud.discoveryengine.v1.ListConversationsResponse.getDefaultInstance()) return this; if (conversationsBuilder_ == null) { if (!other.conversations_.isEmpty()) { if (conversations_.isEmpty()) { conversations_ = other.conversations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureConversationsIsMutable(); conversations_.addAll(other.conversations_); } onChanged(); } } else { if (!other.conversations_.isEmpty()) { if (conversationsBuilder_.isEmpty()) { conversationsBuilder_.dispose(); conversationsBuilder_ = null; conversations_ = other.conversations_; bitField0_ = (bitField0_ & ~0x00000001); conversationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getConversationsFieldBuilder() : null; } else { conversationsBuilder_.addAllMessages(other.conversations_); } } } 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.Conversation m = input.readMessage( com.google.cloud.discoveryengine.v1.Conversation.parser(), extensionRegistry); if (conversationsBuilder_ == null) { ensureConversationsIsMutable(); conversations_.add(m); } else { conversationsBuilder_.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.Conversation> conversations_ = java.util.Collections.emptyList(); private void ensureConversationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { conversations_ = new java.util.ArrayList<com.google.cloud.discoveryengine.v1.Conversation>( conversations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.discoveryengine.v1.Conversation, com.google.cloud.discoveryengine.v1.Conversation.Builder, com.google.cloud.discoveryengine.v1.ConversationOrBuilder> conversationsBuilder_; /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public java.util.List<com.google.cloud.discoveryengine.v1.Conversation> getConversationsList() { if (conversationsBuilder_ == null) { return java.util.Collections.unmodifiableList(conversations_); } else { return conversationsBuilder_.getMessageList(); } } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public int getConversationsCount() { if (conversationsBuilder_ == null) { return conversations_.size(); } else { return conversationsBuilder_.getCount(); } } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public com.google.cloud.discoveryengine.v1.Conversation getConversations(int index) { if (conversationsBuilder_ == null) { return conversations_.get(index); } else { return conversationsBuilder_.getMessage(index); } } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder setConversations( int index, com.google.cloud.discoveryengine.v1.Conversation value) { if (conversationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConversationsIsMutable(); conversations_.set(index, value); onChanged(); } else { conversationsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder setConversations( int index, com.google.cloud.discoveryengine.v1.Conversation.Builder builderForValue) { if (conversationsBuilder_ == null) { ensureConversationsIsMutable(); conversations_.set(index, builderForValue.build()); onChanged(); } else { conversationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder addConversations(com.google.cloud.discoveryengine.v1.Conversation value) { if (conversationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConversationsIsMutable(); conversations_.add(value); onChanged(); } else { conversationsBuilder_.addMessage(value); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder addConversations( int index, com.google.cloud.discoveryengine.v1.Conversation value) { if (conversationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConversationsIsMutable(); conversations_.add(index, value); onChanged(); } else { conversationsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder addConversations( com.google.cloud.discoveryengine.v1.Conversation.Builder builderForValue) { if (conversationsBuilder_ == null) { ensureConversationsIsMutable(); conversations_.add(builderForValue.build()); onChanged(); } else { conversationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder addConversations( int index, com.google.cloud.discoveryengine.v1.Conversation.Builder builderForValue) { if (conversationsBuilder_ == null) { ensureConversationsIsMutable(); conversations_.add(index, builderForValue.build()); onChanged(); } else { conversationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder addAllConversations( java.lang.Iterable<? extends com.google.cloud.discoveryengine.v1.Conversation> values) { if (conversationsBuilder_ == null) { ensureConversationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, conversations_); onChanged(); } else { conversationsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder clearConversations() { if (conversationsBuilder_ == null) { conversations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { conversationsBuilder_.clear(); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public Builder removeConversations(int index) { if (conversationsBuilder_ == null) { ensureConversationsIsMutable(); conversations_.remove(index); onChanged(); } else { conversationsBuilder_.remove(index); } return this; } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public com.google.cloud.discoveryengine.v1.Conversation.Builder getConversationsBuilder( int index) { return getConversationsFieldBuilder().getBuilder(index); } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public com.google.cloud.discoveryengine.v1.ConversationOrBuilder getConversationsOrBuilder( int index) { if (conversationsBuilder_ == null) { return conversations_.get(index); } else { return conversationsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public java.util.List<? extends com.google.cloud.discoveryengine.v1.ConversationOrBuilder> getConversationsOrBuilderList() { if (conversationsBuilder_ != null) { return conversationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(conversations_); } } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public com.google.cloud.discoveryengine.v1.Conversation.Builder addConversationsBuilder() { return getConversationsFieldBuilder() .addBuilder(com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance()); } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public com.google.cloud.discoveryengine.v1.Conversation.Builder addConversationsBuilder( int index) { return getConversationsFieldBuilder() .addBuilder(index, com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance()); } /** * * * <pre> * All the Conversations for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1.Conversation conversations = 1;</code> */ public java.util.List<com.google.cloud.discoveryengine.v1.Conversation.Builder> getConversationsBuilderList() { return getConversationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.discoveryengine.v1.Conversation, com.google.cloud.discoveryengine.v1.Conversation.Builder, com.google.cloud.discoveryengine.v1.ConversationOrBuilder> getConversationsFieldBuilder() { if (conversationsBuilder_ == null) { conversationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.discoveryengine.v1.Conversation, com.google.cloud.discoveryengine.v1.Conversation.Builder, com.google.cloud.discoveryengine.v1.ConversationOrBuilder>( conversations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); conversations_ = null; } return conversationsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1.ListConversationsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1.ListConversationsResponse) private static final com.google.cloud.discoveryengine.v1.ListConversationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1.ListConversationsResponse(); } public static com.google.cloud.discoveryengine.v1.ListConversationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListConversationsResponse> PARSER = new com.google.protobuf.AbstractParser<ListConversationsResponse>() { @java.lang.Override public ListConversationsResponse 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<ListConversationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListConversationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1.ListConversationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/conscrypt
37,897
testing/src/main/java/org/conscrypt/TestUtils.java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.conscrypt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.conscrypt.java.security.StandardNames; import org.conscrypt.java.security.TestKeyStore; import org.conscrypt.testing.Streams; import org.junit.Assume; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.PublicKey; import java.security.Security; import java.security.Signature; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; /** * Utility methods to support testing. */ public final class TestUtils { public static final Charset UTF_8 = StandardCharsets.UTF_8; private static final String PROTOCOL_TLS_V1_3 = "TLSv1.3"; private static final String PROTOCOL_TLS_V1_2 = "TLSv1.2"; private static final String PROTOCOL_TLS_V1_1 = "TLSv1.1"; // For interop testing we need a JDK Provider that can do TLS 1.2 as 1.x may be disabled // in Conscrypt and 1.3 does not (yet) handle interoperability with the JDK Provider. private static final String[] DESIRED_JDK_PROTOCOLS = new String[] { PROTOCOL_TLS_V1_2 }; private static final Provider JDK_PROVIDER = getNonConscryptTlsProvider(); private static final byte[] CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".getBytes(UTF_8); private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocateDirect(0); static final String TEST_CIPHER = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"; public enum BufferType { HEAP { @Override ByteBuffer newBuffer(int size) { return ByteBuffer.allocate(size); } }, DIRECT { @Override ByteBuffer newBuffer(int size) { return ByteBuffer.allocateDirect(size); } }; private static final Random random = new Random(System.currentTimeMillis()); abstract ByteBuffer newBuffer(int size); public ByteBuffer[] newRandomBuffers(int... sizes) { int numBuffers = sizes.length; ByteBuffer[] result = new ByteBuffer[numBuffers]; for (int i = 0; i < numBuffers; i++) { result[i] = newRandomBuffer(sizes[i]); } return result; } public ByteBuffer newRandomBuffer(int size) { byte[] data = new byte[size]; random.nextBytes(data); ByteBuffer buffer = newBuffer(size); buffer.put(data); buffer.flip(); return buffer; } } private TestUtils() {} private static Provider getNonConscryptTlsProvider() { for (String protocol : DESIRED_JDK_PROTOCOLS) { Provider p = getNonConscryptProviderFor("SSLContext", protocol); if (p != null) { return p; } } return new BouncyCastleProvider(); } static Provider getNonConscryptProviderFor(String type, String algorithm) { for (Provider p : Security.getProviders()) { if (!p.getClass().getPackage().getName().contains("conscrypt") && (p.getService(type, algorithm) != null)) { return p; } } return null; } static Provider getJdkProvider() { return JDK_PROVIDER; } public static boolean isClassAvailable(String classname) { try { Class.forName(classname); return true; } catch (ClassNotFoundException ignore) { // Ignored } return false; } private static void assumeClassAvailable(String classname) { Assume.assumeTrue("Skipping test: " + classname + " unavailable", isClassAvailable(classname)); } public static void assumeSNIHostnameAvailable() { assumeClassAvailable("javax.net.ssl.SNIHostName"); } public static void assumeExtendedTrustManagerAvailable() { assumeClassAvailable("javax.net.ssl.X509ExtendedTrustManager"); } public static void assumeStatsLogAvailable() { assumeClassAvailable("android.util.StatsEvent"); } public static void assumeSetEndpointIdentificationAlgorithmAvailable() { boolean supported = false; try { SSLParameters.class.getMethod("setEndpointIdentificationAlgorithm", String.class); supported = true; } catch (NoSuchMethodException ignore) { // Ignored } Assume.assumeTrue("Skipping test: " + "SSLParameters.setEndpointIdentificationAlgorithm unavailable", supported); } public static void assumeAEADAvailable() { assumeClassAvailable("javax.crypto.AEADBadTagException"); } private static boolean isAndroid() { try { Class.forName("android.app.Application", false, ClassLoader.getSystemClassLoader()); return true; } catch (Throwable ignored) { // Failed to load the class uniquely available in Android. return false; } } public static void assumeAndroid() { Assume.assumeTrue(isAndroid()); } public static void assumeAllowsUnsignedCrypto() { // The Oracle JRE disallows loading crypto providers from unsigned jars Assume.assumeTrue(isAndroid() || !System.getProperty("java.vm.name").contains("HotSpot")); } public static void assumeSHA2WithDSAAvailable() { boolean available; try { Signature.getInstance("SHA256withDSA"); available = true; } catch (NoSuchAlgorithmException e) { available = false; } Assume.assumeTrue("SHA2 with DSA signatures not available", available); } public static InetAddress getLoopbackAddress() { try { Method method = InetAddress.class.getMethod("getLoopbackAddress"); return (InetAddress) method.invoke(null); } catch (Exception ignore) { // Ignored. } try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } public static Provider getConscryptProvider(boolean isTlsV1Deprecated, boolean isTlsV1Enabled) { try { String defaultName = (String) conscryptClass("Platform") .getDeclaredMethod("getDefaultProviderName") .invoke(null); Constructor<?> c = conscryptClass("OpenSSLProvider") .getDeclaredConstructor(String.class, Boolean.TYPE, String.class, Boolean.TYPE, Boolean.TYPE); if (!isClassAvailable("javax.net.ssl.X509ExtendedTrustManager")) { return (Provider) c.newInstance(defaultName, false, "TLSv1.3", isTlsV1Deprecated, isTlsV1Enabled); } else { return (Provider) c.newInstance(defaultName, true, "TLSv1.3", isTlsV1Deprecated, isTlsV1Enabled); } } catch (Exception e) { throw new RuntimeException(e); } } public static Provider getConscryptProvider() { return getConscryptProvider(true, false); } public static synchronized void installConscryptAsDefaultProvider() { Provider conscryptProvider = getConscryptProvider(); Provider[] providers = Security.getProviders(); if (providers.length == 0 || !providers[0].equals(conscryptProvider)) { Security.insertProviderAt(conscryptProvider, 1); } } public static InputStream openTestFile(String name) throws FileNotFoundException { InputStream is = TestUtils.class.getResourceAsStream("/" + name); if (is == null) { throw new FileNotFoundException(name); } return is; } public static byte[] readTestFile(String name) throws IOException { return Streams.readFully(openTestFile(name)); } public static PublicKey readPublicKeyPemFile(String name) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException { String keyData = new String(readTestFile(name), StandardCharsets.US_ASCII); keyData = keyData.replace("-----BEGIN PUBLIC KEY-----", ""); keyData = keyData.replace("-----END PUBLIC KEY-----", ""); keyData = keyData.replace("\r", ""); keyData = keyData.replace("\n", ""); return KeyFactory.getInstance("EC").generatePublic( new X509EncodedKeySpec(decodeBase64(keyData))); } public static List<String[]> readCsvResource(String resourceName) throws IOException { InputStream stream = openTestFile(resourceName); List<String[]> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) { continue; } lines.add(line.split(",", -1)); } } return lines; } public static List<TestVector> readTestVectors(String resourceName) throws IOException { InputStream stream = openTestFile(resourceName); List<TestVector> result = new ArrayList<>(); TestVector current = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { String line; int lineNumber = 0; while ((line = reader.readLine()) != null) { lineNumber++; if (line.isEmpty() || line.startsWith("#")) { continue; } int index = line.indexOf('='); if (index < 0) { throw new IllegalStateException("No = found: line " + lineNumber); } String label = line.substring(0, index).trim().toLowerCase(Locale.ROOT); String value = line.substring(index + 1).trim(); if ("name".equals(label)) { current = new TestVector(); result.add(current); } else if (current == null) { throw new IllegalStateException("Vectors must start with a name: line " + lineNumber); } current.put(label, value); } } return result; } /** * Looks up the conscrypt class for the given simple name (i.e. no package prefix). */ public static Class<?> conscryptClass(String simpleName) throws ClassNotFoundException { ClassNotFoundException ex = null; for (String packageName : new String[] {"org.conscrypt", "com.android.org.conscrypt"}) { String name = packageName + "." + simpleName; try { return Class.forName(name); } catch (ClassNotFoundException e) { ex = e; } } throw ex; } // Return a Class by name or null public static Class<?> findClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException ignored) { return null; } } public static SSLSocketFactory setUseEngineSocket( SSLSocketFactory conscryptFactory, boolean useEngineSocket) { try { Class<?> clazz = conscryptClass("Conscrypt"); Method method = clazz.getMethod("setUseEngineSocket", SSLSocketFactory.class, boolean.class); method.invoke(null, conscryptFactory, useEngineSocket); return conscryptFactory; } catch (Exception e) { throw new RuntimeException(e); } } public static SSLServerSocketFactory setUseEngineSocket( SSLServerSocketFactory conscryptFactory, boolean useEngineSocket) { try { Class<?> clazz = conscryptClass("Conscrypt"); Method method = clazz.getMethod( "setUseEngineSocket", SSLServerSocketFactory.class, boolean.class); method.invoke(null, conscryptFactory, useEngineSocket); return conscryptFactory; } catch (Exception e) { throw new RuntimeException(e); } } static boolean getUseEngineSocketByDefault() { try { boolean sfDefault = getBooleanField( "OpenSSLSocketFactoryImpl", "useEngineSocketByDefault"); boolean ssfDefault = getBooleanField( "OpenSSLServerSocketFactoryImpl", "useEngineSocketByDefault"); if (sfDefault != ssfDefault) { throw new IllegalStateException("Socket factory and server socket factory must\n" + "use the same default implementation during testing"); } return sfDefault; } catch (Exception e) { throw new RuntimeException(e); } } static boolean getBooleanField(String className, String fieldName) throws Exception { Class<?> clazz = conscryptClass(className); Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field.getBoolean(null); } public static void setUseSessionTickets(SSLSocket socket, boolean useTickets) { try { Class<?> clazz = conscryptClass("Conscrypt"); Method method = clazz.getMethod("setUseSessionTickets", SSLSocket.class, boolean.class); method.invoke(null, socket, useTickets); } catch (Exception e) { throw new RuntimeException(e); } } static SSLContext newContext(Provider provider) { try { return SSLContext.getInstance("TLS", provider); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String highestCommonProtocol() { String[] common = getCommonProtocolSuites(); Arrays.sort(common); return common[common.length - 1]; } public static String[] getCommonProtocolSuites() { SSLContext jdkContext = newClientSslContext(getJdkProvider()); SSLContext conscryptContext = newClientSslContext(getConscryptProvider()); // No point building a Set here due to small list sizes. List<String> conscryptProtocols = getSupportedProtocols(conscryptContext); Predicate<String> predicate = p -> conscryptProtocols.contains(p) // TODO(prb): Certificate auth fails when connecting Conscrypt and JDK's TLS 1.3. && !p.equals(PROTOCOL_TLS_V1_3); return getSupportedProtocols(jdkContext, predicate); } public static String[] getCommonCipherSuites() { SSLContext jdkContext = newClientSslContext(getJdkProvider()); SSLContext conscryptContext = newClientSslContext(getConscryptProvider()); Set<String> conscryptCiphers = new HashSet<>(getSupportedCiphers(conscryptContext)); Predicate<String> predicate = c -> isTlsCipherSuite(c) && conscryptCiphers.contains(c); return getSupportedCiphers(jdkContext, predicate); } public static List<String> getSupportedCiphers(SSLContext ctx) { return Arrays.asList(ctx.getDefaultSSLParameters().getCipherSuites()); } public static String[] getSupportedCiphers(SSLContext ctx, Predicate<String> predicate) { return Arrays.stream(ctx.getDefaultSSLParameters().getCipherSuites()) .filter(predicate) .toArray(String[]::new); } public static String[] getSupportedProtocols() { return getSupportedProtocols(newClientSslContext(getConscryptProvider())) .toArray(new String[0]); } public static List<String> getSupportedProtocols(SSLContext ctx) { return Arrays.asList(ctx.getDefaultSSLParameters().getProtocols()); } public static String[] getSupportedProtocols(SSLContext ctx, Predicate<String> predicate) { return Arrays.stream(ctx.getDefaultSSLParameters().getProtocols()) .filter(predicate) .toArray(String[]::new); } private static boolean isTlsCipherSuite(String cipher) { return !cipher.startsWith("SSL_") && !cipher.startsWith("TLS_EMPTY") && !cipher.contains("_RC4_"); } public static void assumeTlsV11Enabled(SSLContext context) { Assume.assumeTrue(getSupportedProtocols(context).contains(PROTOCOL_TLS_V1_1)); } /** * Picks a port that is not used right at this moment. * Warning: Not thread safe. May see "BindException: Address already in use: bind" if using the * returned port to create a new server socket when other threads/processes are concurrently * creating new sockets without a specific port. */ public static int pickUnusedPort() { try { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { throw new RuntimeException(e); } } /** * Creates a text message of the given length. */ public static byte[] newTextMessage(int length) { byte[] msg = new byte[length]; for (int msgIndex = 0; msgIndex < length;) { int remaining = length - msgIndex; int numChars = Math.min(remaining, CHARS.length); System.arraycopy(CHARS, 0, msg, msgIndex, numChars); msgIndex += numChars; } return msg; } public static SSLContext newClientSslContext(Provider provider) { SSLContext context = newContext(provider); return initClientSslContext(context); } public static SSLContext newServerSslContext(Provider provider) { SSLContext context = newContext(provider); return initServerSslContext(context); } /** * Initializes the given client-side {@code context} with a default cert. */ public static SSLContext initClientSslContext(SSLContext context) { return initSslContext(context, TestKeyStore.getClient()); } /** * Initializes the given server-side {@code context} with the given cert chain and private key. */ public static SSLContext initServerSslContext(SSLContext context) { return initSslContext(context, TestKeyStore.getServer()); } /** * Initializes the given {@code context} from the {@code keyStore}. */ static SSLContext initSslContext(SSLContext context, TestKeyStore keyStore) { try { context.init(keyStore.keyManagers, keyStore.trustManagers, null); return context; } catch (Exception e) { throw new RuntimeException(e); } } /** * Performs the initial TLS handshake between the two {@link SSLEngine} instances. */ public static void doEngineHandshake(SSLEngine clientEngine, SSLEngine serverEngine, ByteBuffer clientAppBuffer, ByteBuffer clientPacketBuffer, ByteBuffer serverAppBuffer, ByteBuffer serverPacketBuffer, boolean beginHandshake) throws SSLException { if (beginHandshake) { clientEngine.beginHandshake(); serverEngine.beginHandshake(); } SSLEngineResult clientResult; SSLEngineResult serverResult; boolean clientHandshakeFinished = false; boolean serverHandshakeFinished = false; do { int cTOsPos = clientPacketBuffer.position(); int sTOcPos = serverPacketBuffer.position(); clientResult = clientEngine.wrap(EMPTY_BUFFER, clientPacketBuffer); runDelegatedTasks(clientResult, clientEngine); serverResult = serverEngine.wrap(EMPTY_BUFFER, serverPacketBuffer); runDelegatedTasks(serverResult, serverEngine); // Verify that the consumed and produced number match what is in the buffers now. assertEquals(0, clientResult.bytesConsumed()); assertEquals(0, serverResult.bytesConsumed()); assertEquals(clientPacketBuffer.position() - cTOsPos, clientResult.bytesProduced()); assertEquals(serverPacketBuffer.position() - sTOcPos, serverResult.bytesProduced()); clientPacketBuffer.flip(); serverPacketBuffer.flip(); // Verify that we only had one SSLEngineResult.HandshakeStatus.FINISHED if (isHandshakeFinished(clientResult)) { assertFalse(clientHandshakeFinished); clientHandshakeFinished = true; } if (isHandshakeFinished(serverResult)) { assertFalse(serverHandshakeFinished); serverHandshakeFinished = true; } cTOsPos = clientPacketBuffer.position(); sTOcPos = serverPacketBuffer.position(); int clientAppReadBufferPos = clientAppBuffer.position(); int serverAppReadBufferPos = serverAppBuffer.position(); clientResult = clientEngine.unwrap(serverPacketBuffer, clientAppBuffer); runDelegatedTasks(clientResult, clientEngine); serverResult = serverEngine.unwrap(clientPacketBuffer, serverAppBuffer); runDelegatedTasks(serverResult, serverEngine); // Verify that the consumed and produced number match what is in the buffers now. assertEquals(serverPacketBuffer.position() - sTOcPos, clientResult.bytesConsumed()); assertEquals(clientPacketBuffer.position() - cTOsPos, serverResult.bytesConsumed()); assertEquals(clientAppBuffer.position() - clientAppReadBufferPos, clientResult.bytesProduced()); assertEquals(serverAppBuffer.position() - serverAppReadBufferPos, serverResult.bytesProduced()); clientPacketBuffer.compact(); serverPacketBuffer.compact(); // Verify that we only had one SSLEngineResult.HandshakeStatus.FINISHED if (isHandshakeFinished(clientResult)) { assertFalse(clientHandshakeFinished); clientHandshakeFinished = true; } if (isHandshakeFinished(serverResult)) { assertFalse(serverHandshakeFinished); serverHandshakeFinished = true; } } while (!clientHandshakeFinished || !serverHandshakeFinished); } private static boolean isHandshakeFinished(SSLEngineResult result) { return result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.FINISHED; } private static void runDelegatedTasks(SSLEngineResult result, SSLEngine engine) { if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) { for (;;) { Runnable task = engine.getDelegatedTask(); if (task == null) { break; } task.run(); } } } public static String pickArbitraryNonTls13Suite(String[] cipherSuites) { return pickArbitraryNonTls13Suite(Arrays.asList(cipherSuites)); } public static String pickArbitraryNonTls13Suite(Iterable<String> cipherSuites) { for (String cipherSuite : cipherSuites) { if (!StandardNames.CIPHER_SUITES_TLS13.contains(cipherSuite)) { return cipherSuite; } } fail("No non-TLSv1.3 cipher suite available."); return null; } /** * Decodes the provided hexadecimal string into a byte array. Odd-length inputs * are not allowed. * <p> * Throws an {@code IllegalArgumentException} if the input is malformed. */ public static byte[] decodeHex(String encoded) throws IllegalArgumentException { return decodeHex(encoded.toCharArray()); } /** * Decodes the provided hexadecimal string into a byte array. If {@code allowSingleChar} * is {@code true} odd-length inputs are allowed and the first character is interpreted * as the lower bits of the first result byte. * <p> * Throws an {@code IllegalArgumentException} if the input is malformed. */ public static byte[] decodeHex(String encoded, boolean allowSingleChar) throws IllegalArgumentException { return decodeHex(encoded.toCharArray(), allowSingleChar); } /** * Decodes the provided hexadecimal string into a byte array. Odd-length inputs * are not allowed. * <p> * Throws an {@code IllegalArgumentException} if the input is malformed. */ public static byte[] decodeHex(char[] encoded) throws IllegalArgumentException { return decodeHex(encoded, false); } /** * Decodes the provided hexadecimal string into a byte array. If {@code allowSingleChar} * is {@code true} odd-length inputs are allowed and the first character is interpreted * as the lower bits of the first result byte. * <p> * Throws an {@code IllegalArgumentException} if the input is malformed. */ public static byte[] decodeHex(char[] encoded, boolean allowSingleChar) throws IllegalArgumentException { int resultLengthBytes = (encoded.length + 1) / 2; byte[] result = new byte[resultLengthBytes]; int resultOffset = 0; int i = 0; if (allowSingleChar) { if ((encoded.length % 2) != 0) { // Odd number of digits -- the first digit is the lower 4 bits of the first result byte. result[resultOffset++] = (byte) toDigit(encoded, i); i++; } } else { if ((encoded.length % 2) != 0) { throw new IllegalArgumentException("Invalid input length: " + encoded.length); } } for (int len = encoded.length; i < len; i += 2) { result[resultOffset++] = (byte) ((toDigit(encoded, i) << 4) | toDigit(encoded, i + 1)); } return result; } private static int toDigit(char[] str, int offset) throws IllegalArgumentException { // NOTE: that this isn't really a code point in the traditional sense, since we're // just rejecting surrogate pairs outright. int pseudoCodePoint = str[offset]; if ('0' <= pseudoCodePoint && pseudoCodePoint <= '9') { return pseudoCodePoint - '0'; } else if ('a' <= pseudoCodePoint && pseudoCodePoint <= 'f') { return 10 + (pseudoCodePoint - 'a'); } else if ('A' <= pseudoCodePoint && pseudoCodePoint <= 'F') { return 10 + (pseudoCodePoint - 'A'); } throw new IllegalArgumentException("Illegal char: " + str[offset] + " at offset " + offset); } private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); public static String encodeHex(byte[] data) { char[] hex = new char[data.length * 2]; for (int i = 0; i < data.length; i++) { int value = data[i] & 0xff; hex[2 * i] = HEX_CHARS[value >>> 4]; hex[2 * i + 1] = HEX_CHARS[value & 0x0f]; } return new String(hex); } private static final String BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; public static String encodeBase64(byte[] data) { // Base64 was introduced in Java 8, so if it's not available we can use a hacky // solution that works in previous versions if (isClassAvailable("java.util.Base64")) { return Base64.getEncoder().encodeToString(data); } else { StringBuilder builder = new StringBuilder(); for (int i = 0; i < data.length; i += 3) { int padding = (i + 2 < data.length) ? 0 : (i + 3 - data.length); byte b1 = data[i]; byte b2 = padding >= 2 ? 0 : data[i+1]; byte b3 = padding >= 1 ? 0 : data[i+2]; char c1 = BASE64_ALPHABET.charAt((b1 & 0xFF) >>> 2); char c2 = BASE64_ALPHABET.charAt(((b1 & 0x03) << 4) | ((b2 & 0xFF) >>> 4)); char c3 = BASE64_ALPHABET.charAt(((b2 & 0x0F) << 2) | ((b3 & 0xFF) >>> 6)); char c4 = BASE64_ALPHABET.charAt(b3 & 0x3F); if (padding >= 1) { c4 = '='; } if (padding >= 2) { c3 = '='; } builder.append(c1).append(c2).append(c3).append(c4); } return builder.toString(); } } public static byte[] decodeBase64(String data) { // Base64 was introduced in Java 8, so if it's not available we can use a hacky // solution that works in previous versions if (isClassAvailable("java.util.Base64")) { return Base64.getDecoder().decode(data); } else { while (data.endsWith("=")) { data = data.substring(0, data.length() - 1); } int padding = (data.length() % 4 == 0) ? 0 : 4 - (data.length() % 4); byte[] output = new byte[((data.length() - 1) / 4) * 3 + 3 - padding]; int outputindex = 0; for (int i = 0; i < data.length(); i += 4) { char c1 = data.charAt(i); char c2 = data.charAt(i+1); char c3 = (i+2 < data.length()) ? data.charAt(i+2) : 'A'; char c4 = (i+3 < data.length()) ? data.charAt(i+3) : 'A'; byte b1 = (byte) (BASE64_ALPHABET.indexOf(c1) << 2 | BASE64_ALPHABET.indexOf(c2) >>> 4); byte b2 = (byte) ((BASE64_ALPHABET.indexOf(c2) & 0x0F) << 4 | BASE64_ALPHABET.indexOf(c3) >>> 2); byte b3 = (byte) ((BASE64_ALPHABET.indexOf(c3) & 0x03) << 6 | BASE64_ALPHABET.indexOf(c4)); output[outputindex++] = b1; if (outputindex < output.length) { output[outputindex++] = b2; } if (outputindex < output.length) { output[outputindex++] = b3; } } return output; } } public static boolean isJavaVersion(int version) { return javaVersion() >= version; } private static int javaVersion() { String[] v = System.getProperty("java.specification.version", "1.6").split("\\.", -1); if ("1".equals(v[0])) { return Integer.parseInt(v[1]); } return Integer.parseInt(v[0]); } public static void assumeJava8() { Assume.assumeTrue("Require Java 8: " + javaVersion(), isJavaVersion(8)); } public static void assumeEngineSocket() { Assume.assumeTrue(getUseEngineSocketByDefault()); } public static String osName() { return System.getProperty("os.name").toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", ""); } public static boolean isLinux() { return osName().startsWith("linux"); } public static boolean isWindows() { return osName().startsWith("windows"); } public static boolean isOsx() { String name = osName(); return name.startsWith("macosx") || name.startsWith("osx"); } public static void assumeXecClassesAvailable() { Assume.assumeTrue(findClass("java.security.spec.XECPrivateKeySpec") != null); } public static boolean isTlsV1Deprecated() { return callPlatformMethod("isTlsV1Deprecated", false); } public static boolean isTlsV1Filtered() { return callPlatformMethod("isTlsV1Filtered", true); } public static boolean isTlsV1Supported() { return callPlatformMethod("isTlsV1Supported", true); } public static boolean isJavaxCertificateSupported() { return callPlatformMethod("isJavaxCertificateSupported", true); } // Calls a boolean platform method by reflection. If the method is not present, e.g. // due to version skew etc then return the default value. public static boolean callPlatformMethod(String methodName, boolean defaultValue) { try { return (Boolean) conscryptClass("Platform") .getDeclaredMethod(methodName) .invoke(null); } catch (NoSuchMethodException e) { return defaultValue; } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Reflection failure", e); } } // Just a Runnable which can throw exceptions. @FunctionalInterface public interface ThrowingRunnable { void run() throws Exception; } // Stress test a throwing Runnable with default counts and allowing exceptions, // e.g. to ensure abuse of non-thread-safe code doesn't cause native crashes. public static void stressTestAllowingExceptions( int threadCount, int iterationCount, ThrowingRunnable runnable) throws Exception { stressTest(threadCount, iterationCount, true, runnable); } // Stress test a throwing Runnable with default counts, rethrowing any exceptions encountered. public static void stressTest(int threadCount, int iterationCount, ThrowingRunnable runnable) throws Exception { stressTest(threadCount, iterationCount, false, runnable); } /** * Stress test a throwing {@code Runnable} by running it multiple times in multiple threads. * <p> * Optionally allow exceptions - this is to allow for stress tests which abuse non-thread-safe * classes where we are aware that the answers will be wrong and the code may throw but we * wish to ensure that such misuse doesn't provoke any native crashes. * <p> * The test will time out after one minute. * <p> * TODO(prb): Now that we plan to use this more widely, it needs tests. * * @param threadCount the number of concurrent threads to use * @param iterationCount number of iterations on each thread * @param allowExceptions whether to allow exceptions * @param runnable a {@link ThrowingRunnable} containing the code to test */ private static void stressTest(int threadCount, int iterationCount, boolean allowExceptions, ThrowingRunnable runnable) throws Exception { ExecutorService es = Executors.newFixedThreadPool(threadCount); final CountDownLatch latch = new CountDownLatch(threadCount); List<Future<Void>> futures = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { futures.add(es.submit(() -> { // Try to make sure all the threads are ready first. latch.countDown(); latch.await(); for (int j = 0; j < iterationCount; j++) { runnable.run(); } return null; })); } es.shutdown(); assertTrue("Timed out during stress test", es.awaitTermination(1, TimeUnit.MINUTES)); for (Future<Void> f : futures) { try { f.get(); } catch (ExecutionException exception) { if (!allowExceptions) { throw exception; } } } } }
googleapis/google-cloud-java
37,858
java-kms/proto-google-cloud-kms-v1/src/main/java/com/google/cloud/kms/v1/KeyHandle.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/kms/v1/autokey.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.kms.v1; /** * * * <pre> * Resource-oriented representation of a request to Cloud KMS Autokey and the * resulting provisioning of a [CryptoKey][google.cloud.kms.v1.CryptoKey]. * </pre> * * Protobuf type {@code google.cloud.kms.v1.KeyHandle} */ public final class KeyHandle extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.kms.v1.KeyHandle) KeyHandleOrBuilder { private static final long serialVersionUID = 0L; // Use KeyHandle.newBuilder() to construct. private KeyHandle(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private KeyHandle() { name_ = ""; kmsKey_ = ""; resourceTypeSelector_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new KeyHandle(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.kms.v1.AutokeyProto .internal_static_google_cloud_kms_v1_KeyHandle_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.kms.v1.AutokeyProto .internal_static_google_cloud_kms_v1_KeyHandle_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.kms.v1.KeyHandle.class, com.google.cloud.kms.v1.KeyHandle.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int KMS_KEY_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object kmsKey_ = ""; /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The kmsKey. */ @java.lang.Override public java.lang.String getKmsKey() { java.lang.Object ref = kmsKey_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); kmsKey_ = s; return s; } } /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for kmsKey. */ @java.lang.Override public com.google.protobuf.ByteString getKmsKeyBytes() { java.lang.Object ref = kmsKey_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); kmsKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESOURCE_TYPE_SELECTOR_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object resourceTypeSelector_ = ""; /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The resourceTypeSelector. */ @java.lang.Override public java.lang.String getResourceTypeSelector() { java.lang.Object ref = resourceTypeSelector_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceTypeSelector_ = s; return s; } } /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for resourceTypeSelector. */ @java.lang.Override public com.google.protobuf.ByteString getResourceTypeSelectorBytes() { java.lang.Object ref = resourceTypeSelector_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resourceTypeSelector_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kmsKey_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, kmsKey_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceTypeSelector_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, resourceTypeSelector_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kmsKey_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, kmsKey_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceTypeSelector_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, resourceTypeSelector_); } 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.kms.v1.KeyHandle)) { return super.equals(obj); } com.google.cloud.kms.v1.KeyHandle other = (com.google.cloud.kms.v1.KeyHandle) obj; if (!getName().equals(other.getName())) return false; if (!getKmsKey().equals(other.getKmsKey())) return false; if (!getResourceTypeSelector().equals(other.getResourceTypeSelector())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + KMS_KEY_FIELD_NUMBER; hash = (53 * hash) + getKmsKey().hashCode(); hash = (37 * hash) + RESOURCE_TYPE_SELECTOR_FIELD_NUMBER; hash = (53 * hash) + getResourceTypeSelector().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.kms.v1.KeyHandle parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.kms.v1.KeyHandle 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.kms.v1.KeyHandle parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.kms.v1.KeyHandle 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.kms.v1.KeyHandle parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.kms.v1.KeyHandle parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.kms.v1.KeyHandle parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.kms.v1.KeyHandle 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.kms.v1.KeyHandle parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.kms.v1.KeyHandle 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.kms.v1.KeyHandle parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.kms.v1.KeyHandle 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.kms.v1.KeyHandle 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> * Resource-oriented representation of a request to Cloud KMS Autokey and the * resulting provisioning of a [CryptoKey][google.cloud.kms.v1.CryptoKey]. * </pre> * * Protobuf type {@code google.cloud.kms.v1.KeyHandle} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.kms.v1.KeyHandle) com.google.cloud.kms.v1.KeyHandleOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.kms.v1.AutokeyProto .internal_static_google_cloud_kms_v1_KeyHandle_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.kms.v1.AutokeyProto .internal_static_google_cloud_kms_v1_KeyHandle_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.kms.v1.KeyHandle.class, com.google.cloud.kms.v1.KeyHandle.Builder.class); } // Construct using com.google.cloud.kms.v1.KeyHandle.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; kmsKey_ = ""; resourceTypeSelector_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.kms.v1.AutokeyProto .internal_static_google_cloud_kms_v1_KeyHandle_descriptor; } @java.lang.Override public com.google.cloud.kms.v1.KeyHandle getDefaultInstanceForType() { return com.google.cloud.kms.v1.KeyHandle.getDefaultInstance(); } @java.lang.Override public com.google.cloud.kms.v1.KeyHandle build() { com.google.cloud.kms.v1.KeyHandle result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.kms.v1.KeyHandle buildPartial() { com.google.cloud.kms.v1.KeyHandle result = new com.google.cloud.kms.v1.KeyHandle(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.kms.v1.KeyHandle result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.kmsKey_ = kmsKey_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.resourceTypeSelector_ = resourceTypeSelector_; } } @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.kms.v1.KeyHandle) { return mergeFrom((com.google.cloud.kms.v1.KeyHandle) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.kms.v1.KeyHandle other) { if (other == com.google.cloud.kms.v1.KeyHandle.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getKmsKey().isEmpty()) { kmsKey_ = other.kmsKey_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getResourceTypeSelector().isEmpty()) { resourceTypeSelector_ = other.resourceTypeSelector_; 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: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 26: { kmsKey_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 26 case 34: { resourceTypeSelector_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Identifier. Name of the [KeyHandle][google.cloud.kms.v1.KeyHandle] * resource, e.g. * `projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}`. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object kmsKey_ = ""; /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The kmsKey. */ public java.lang.String getKmsKey() { java.lang.Object ref = kmsKey_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); kmsKey_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for kmsKey. */ public com.google.protobuf.ByteString getKmsKeyBytes() { java.lang.Object ref = kmsKey_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); kmsKey_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @param value The kmsKey to set. * @return This builder for chaining. */ public Builder setKmsKey(java.lang.String value) { if (value == null) { throw new NullPointerException(); } kmsKey_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearKmsKey() { kmsKey_ = getDefaultInstance().getKmsKey(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Output only. Name of a [CryptoKey][google.cloud.kms.v1.CryptoKey] that has * been provisioned for Customer Managed Encryption Key (CMEK) use in the * [KeyHandle][google.cloud.kms.v1.KeyHandle] project and location for the * requested resource type. The [CryptoKey][google.cloud.kms.v1.CryptoKey] * project will reflect the value configured in the * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the resource * project's ancestor folder at the time of the * [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more than one * ancestor folder has a configured * [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the nearest of these * configurations is used. * </pre> * * <code> * string kms_key = 3 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for kmsKey to set. * @return This builder for chaining. */ public Builder setKmsKeyBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); kmsKey_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object resourceTypeSelector_ = ""; /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The resourceTypeSelector. */ public java.lang.String getResourceTypeSelector() { java.lang.Object ref = resourceTypeSelector_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceTypeSelector_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for resourceTypeSelector. */ public com.google.protobuf.ByteString getResourceTypeSelectorBytes() { java.lang.Object ref = resourceTypeSelector_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resourceTypeSelector_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The resourceTypeSelector to set. * @return This builder for chaining. */ public Builder setResourceTypeSelector(java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceTypeSelector_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearResourceTypeSelector() { resourceTypeSelector_ = getDefaultInstance().getResourceTypeSelector(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. Indicates the resource type that the resulting * [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to protect, e.g. * `{SERVICE}.googleapis.com/{TYPE}`. See documentation for supported resource * types. * </pre> * * <code>string resource_type_selector = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for resourceTypeSelector to set. * @return This builder for chaining. */ public Builder setResourceTypeSelectorBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceTypeSelector_ = 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.kms.v1.KeyHandle) } // @@protoc_insertion_point(class_scope:google.cloud.kms.v1.KeyHandle) private static final com.google.cloud.kms.v1.KeyHandle DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.kms.v1.KeyHandle(); } public static com.google.cloud.kms.v1.KeyHandle getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<KeyHandle> PARSER = new com.google.protobuf.AbstractParser<KeyHandle>() { @java.lang.Override public KeyHandle 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<KeyHandle> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<KeyHandle> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.kms.v1.KeyHandle getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,746
java-shopping-merchant-reviews/proto-google-shopping-merchant-reviews-v1beta/src/main/java/com/google/shopping/merchant/reviews/v1beta/InsertProductReviewRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/merchant/reviews/v1beta/productreviews.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.reviews.v1beta; /** * * * <pre> * Request message for the `InsertProductReview` method. * </pre> * * Protobuf type {@code google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest} */ public final class InsertProductReviewRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) InsertProductReviewRequestOrBuilder { private static final long serialVersionUID = 0L; // Use InsertProductReviewRequest.newBuilder() to construct. private InsertProductReviewRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InsertProductReviewRequest() { parent_ = ""; dataSource_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new InsertProductReviewRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.reviews.v1beta.ProductReviewsProto .internal_static_google_shopping_merchant_reviews_v1beta_InsertProductReviewRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.reviews.v1beta.ProductReviewsProto .internal_static_google_shopping_merchant_reviews_v1beta_InsertProductReviewRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest.class, com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PRODUCT_REVIEW_FIELD_NUMBER = 2; private com.google.shopping.merchant.reviews.v1beta.ProductReview productReview_; /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the productReview field is set. */ @java.lang.Override public boolean hasProductReview() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The productReview. */ @java.lang.Override public com.google.shopping.merchant.reviews.v1beta.ProductReview getProductReview() { return productReview_ == null ? com.google.shopping.merchant.reviews.v1beta.ProductReview.getDefaultInstance() : productReview_; } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.shopping.merchant.reviews.v1beta.ProductReviewOrBuilder getProductReviewOrBuilder() { return productReview_ == null ? com.google.shopping.merchant.reviews.v1beta.ProductReview.getDefaultInstance() : productReview_; } public static final int DATA_SOURCE_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object dataSource_ = ""; /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The dataSource. */ @java.lang.Override public java.lang.String getDataSource() { java.lang.Object ref = dataSource_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); dataSource_ = s; return s; } } /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for dataSource. */ @java.lang.Override public com.google.protobuf.ByteString getDataSourceBytes() { java.lang.Object ref = dataSource_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); dataSource_ = 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, getProductReview()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(dataSource_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, dataSource_); } 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, getProductReview()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(dataSource_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, dataSource_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest)) { return super.equals(obj); } com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest other = (com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasProductReview() != other.hasProductReview()) return false; if (hasProductReview()) { if (!getProductReview().equals(other.getProductReview())) return false; } if (!getDataSource().equals(other.getDataSource())) 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 (hasProductReview()) { hash = (37 * hash) + PRODUCT_REVIEW_FIELD_NUMBER; hash = (53 * hash) + getProductReview().hashCode(); } hash = (37 * hash) + DATA_SOURCE_FIELD_NUMBER; hash = (53 * hash) + getDataSource().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the `InsertProductReview` method. * </pre> * * Protobuf type {@code google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.reviews.v1beta.ProductReviewsProto .internal_static_google_shopping_merchant_reviews_v1beta_InsertProductReviewRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.reviews.v1beta.ProductReviewsProto .internal_static_google_shopping_merchant_reviews_v1beta_InsertProductReviewRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest.class, com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest.Builder.class); } // Construct using // com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getProductReviewFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; productReview_ = null; if (productReviewBuilder_ != null) { productReviewBuilder_.dispose(); productReviewBuilder_ = null; } dataSource_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.reviews.v1beta.ProductReviewsProto .internal_static_google_shopping_merchant_reviews_v1beta_InsertProductReviewRequest_descriptor; } @java.lang.Override public com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest getDefaultInstanceForType() { return com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest .getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest build() { com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest buildPartial() { com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest result = new com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.productReview_ = productReviewBuilder_ == null ? productReview_ : productReviewBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.dataSource_ = dataSource_; } 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.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) { return mergeFrom( (com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest other) { if (other == com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasProductReview()) { mergeProductReview(other.getProductReview()); } if (!other.getDataSource().isEmpty()) { dataSource_ = other.dataSource_; 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(getProductReviewFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { dataSource_ = 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 account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The account where the product review will be inserted. * Format: accounts/{account} * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.shopping.merchant.reviews.v1beta.ProductReview productReview_; private com.google.protobuf.SingleFieldBuilderV3< com.google.shopping.merchant.reviews.v1beta.ProductReview, com.google.shopping.merchant.reviews.v1beta.ProductReview.Builder, com.google.shopping.merchant.reviews.v1beta.ProductReviewOrBuilder> productReviewBuilder_; /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the productReview field is set. */ public boolean hasProductReview() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The productReview. */ public com.google.shopping.merchant.reviews.v1beta.ProductReview getProductReview() { if (productReviewBuilder_ == null) { return productReview_ == null ? com.google.shopping.merchant.reviews.v1beta.ProductReview.getDefaultInstance() : productReview_; } else { return productReviewBuilder_.getMessage(); } } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setProductReview( com.google.shopping.merchant.reviews.v1beta.ProductReview value) { if (productReviewBuilder_ == null) { if (value == null) { throw new NullPointerException(); } productReview_ = value; } else { productReviewBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setProductReview( com.google.shopping.merchant.reviews.v1beta.ProductReview.Builder builderForValue) { if (productReviewBuilder_ == null) { productReview_ = builderForValue.build(); } else { productReviewBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeProductReview( com.google.shopping.merchant.reviews.v1beta.ProductReview value) { if (productReviewBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && productReview_ != null && productReview_ != com.google.shopping.merchant.reviews.v1beta.ProductReview.getDefaultInstance()) { getProductReviewBuilder().mergeFrom(value); } else { productReview_ = value; } } else { productReviewBuilder_.mergeFrom(value); } if (productReview_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearProductReview() { bitField0_ = (bitField0_ & ~0x00000002); productReview_ = null; if (productReviewBuilder_ != null) { productReviewBuilder_.dispose(); productReviewBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.shopping.merchant.reviews.v1beta.ProductReview.Builder getProductReviewBuilder() { bitField0_ |= 0x00000002; onChanged(); return getProductReviewFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.shopping.merchant.reviews.v1beta.ProductReviewOrBuilder getProductReviewOrBuilder() { if (productReviewBuilder_ != null) { return productReviewBuilder_.getMessageOrBuilder(); } else { return productReview_ == null ? com.google.shopping.merchant.reviews.v1beta.ProductReview.getDefaultInstance() : productReview_; } } /** * * * <pre> * Required. The product review to insert. * </pre> * * <code> * .google.shopping.merchant.reviews.v1beta.ProductReview product_review = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.shopping.merchant.reviews.v1beta.ProductReview, com.google.shopping.merchant.reviews.v1beta.ProductReview.Builder, com.google.shopping.merchant.reviews.v1beta.ProductReviewOrBuilder> getProductReviewFieldBuilder() { if (productReviewBuilder_ == null) { productReviewBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.shopping.merchant.reviews.v1beta.ProductReview, com.google.shopping.merchant.reviews.v1beta.ProductReview.Builder, com.google.shopping.merchant.reviews.v1beta.ProductReviewOrBuilder>( getProductReview(), getParentForChildren(), isClean()); productReview_ = null; } return productReviewBuilder_; } private java.lang.Object dataSource_ = ""; /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The dataSource. */ public java.lang.String getDataSource() { java.lang.Object ref = dataSource_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); dataSource_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for dataSource. */ public com.google.protobuf.ByteString getDataSourceBytes() { java.lang.Object ref = dataSource_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); dataSource_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The dataSource to set. * @return This builder for chaining. */ public Builder setDataSource(java.lang.String value) { if (value == null) { throw new NullPointerException(); } dataSource_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearDataSource() { dataSource_ = getDefaultInstance().getDataSource(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. Format: * `accounts/{account}/dataSources/{datasource}`. * </pre> * * <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for dataSource to set. * @return This builder for chaining. */ public Builder setDataSourceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); dataSource_ = 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.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest) private static final com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest(); } public static com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InsertProductReviewRequest> PARSER = new com.google.protobuf.AbstractParser<InsertProductReviewRequest>() { @java.lang.Override public InsertProductReviewRequest 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<InsertProductReviewRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InsertProductReviewRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.reviews.v1beta.InsertProductReviewRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,765
java-redis-cluster/proto-google-cloud-redis-cluster-v1/src/main/java/com/google/cloud/redis/cluster/v1/BackupClusterRequest.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/redis/cluster/v1/cloud_redis_cluster.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.redis.cluster.v1; /** * * * <pre> * Request for [BackupCluster]. * </pre> * * Protobuf type {@code google.cloud.redis.cluster.v1.BackupClusterRequest} */ public final class BackupClusterRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.redis.cluster.v1.BackupClusterRequest) BackupClusterRequestOrBuilder { private static final long serialVersionUID = 0L; // Use BackupClusterRequest.newBuilder() to construct. private BackupClusterRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BackupClusterRequest() { name_ = ""; backupId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BackupClusterRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.redis.cluster.v1.CloudRedisClusterProto .internal_static_google_cloud_redis_cluster_v1_BackupClusterRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.redis.cluster.v1.CloudRedisClusterProto .internal_static_google_cloud_redis_cluster_v1_BackupClusterRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.redis.cluster.v1.BackupClusterRequest.class, com.google.cloud.redis.cluster.v1.BackupClusterRequest.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TTL_FIELD_NUMBER = 2; private com.google.protobuf.Duration ttl_; /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the ttl field is set. */ @java.lang.Override public boolean hasTtl() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The ttl. */ @java.lang.Override public com.google.protobuf.Duration getTtl() { return ttl_ == null ? com.google.protobuf.Duration.getDefaultInstance() : ttl_; } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public com.google.protobuf.DurationOrBuilder getTtlOrBuilder() { return ttl_ == null ? com.google.protobuf.Duration.getDefaultInstance() : ttl_; } public static final int BACKUP_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object backupId_ = ""; /** * * * <pre> * Optional. The id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the backupId field is set. */ @java.lang.Override public boolean hasBackupId() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. The id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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 id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getTtl()); } if (((bitField0_ & 0x00000002) != 0)) { 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(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getTtl()); } if (((bitField0_ & 0x00000002) != 0)) { 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.redis.cluster.v1.BackupClusterRequest)) { return super.equals(obj); } com.google.cloud.redis.cluster.v1.BackupClusterRequest other = (com.google.cloud.redis.cluster.v1.BackupClusterRequest) obj; if (!getName().equals(other.getName())) return false; if (hasTtl() != other.hasTtl()) return false; if (hasTtl()) { if (!getTtl().equals(other.getTtl())) return false; } if (hasBackupId() != other.hasBackupId()) return false; if (hasBackupId()) { 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) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasTtl()) { hash = (37 * hash) + TTL_FIELD_NUMBER; hash = (53 * hash) + getTtl().hashCode(); } if (hasBackupId()) { 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.redis.cluster.v1.BackupClusterRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest 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.redis.cluster.v1.BackupClusterRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest 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.redis.cluster.v1.BackupClusterRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest 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.redis.cluster.v1.BackupClusterRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest 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.redis.cluster.v1.BackupClusterRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest 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.redis.cluster.v1.BackupClusterRequest 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 [BackupCluster]. * </pre> * * Protobuf type {@code google.cloud.redis.cluster.v1.BackupClusterRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.redis.cluster.v1.BackupClusterRequest) com.google.cloud.redis.cluster.v1.BackupClusterRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.redis.cluster.v1.CloudRedisClusterProto .internal_static_google_cloud_redis_cluster_v1_BackupClusterRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.redis.cluster.v1.CloudRedisClusterProto .internal_static_google_cloud_redis_cluster_v1_BackupClusterRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.redis.cluster.v1.BackupClusterRequest.class, com.google.cloud.redis.cluster.v1.BackupClusterRequest.Builder.class); } // Construct using com.google.cloud.redis.cluster.v1.BackupClusterRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTtlFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; ttl_ = null; if (ttlBuilder_ != null) { ttlBuilder_.dispose(); ttlBuilder_ = null; } backupId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.redis.cluster.v1.CloudRedisClusterProto .internal_static_google_cloud_redis_cluster_v1_BackupClusterRequest_descriptor; } @java.lang.Override public com.google.cloud.redis.cluster.v1.BackupClusterRequest getDefaultInstanceForType() { return com.google.cloud.redis.cluster.v1.BackupClusterRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.redis.cluster.v1.BackupClusterRequest build() { com.google.cloud.redis.cluster.v1.BackupClusterRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.redis.cluster.v1.BackupClusterRequest buildPartial() { com.google.cloud.redis.cluster.v1.BackupClusterRequest result = new com.google.cloud.redis.cluster.v1.BackupClusterRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.redis.cluster.v1.BackupClusterRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.ttl_ = ttlBuilder_ == null ? ttl_ : ttlBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.backupId_ = backupId_; 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.redis.cluster.v1.BackupClusterRequest) { return mergeFrom((com.google.cloud.redis.cluster.v1.BackupClusterRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.redis.cluster.v1.BackupClusterRequest other) { if (other == com.google.cloud.redis.cluster.v1.BackupClusterRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasTtl()) { mergeTtl(other.getTtl()); } if (other.hasBackupId()) { 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: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getTtlFieldBuilder().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 name_ = ""; /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Redis cluster resource name using the form: * `projects/{project_id}/locations/{location_id}/clusters/{cluster_id}` * where `location_id` refers to a GCP region. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.Duration ttl_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Duration, com.google.protobuf.Duration.Builder, com.google.protobuf.DurationOrBuilder> ttlBuilder_; /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the ttl field is set. */ public boolean hasTtl() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The ttl. */ public com.google.protobuf.Duration getTtl() { if (ttlBuilder_ == null) { return ttl_ == null ? com.google.protobuf.Duration.getDefaultInstance() : ttl_; } else { return ttlBuilder_.getMessage(); } } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder setTtl(com.google.protobuf.Duration value) { if (ttlBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ttl_ = value; } else { ttlBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder setTtl(com.google.protobuf.Duration.Builder builderForValue) { if (ttlBuilder_ == null) { ttl_ = builderForValue.build(); } else { ttlBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder mergeTtl(com.google.protobuf.Duration value) { if (ttlBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && ttl_ != null && ttl_ != com.google.protobuf.Duration.getDefaultInstance()) { getTtlBuilder().mergeFrom(value); } else { ttl_ = value; } } else { ttlBuilder_.mergeFrom(value); } if (ttl_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder clearTtl() { bitField0_ = (bitField0_ & ~0x00000002); ttl_ = null; if (ttlBuilder_ != null) { ttlBuilder_.dispose(); ttlBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.protobuf.Duration.Builder getTtlBuilder() { bitField0_ |= 0x00000002; onChanged(); return getTtlFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public com.google.protobuf.DurationOrBuilder getTtlOrBuilder() { if (ttlBuilder_ != null) { return ttlBuilder_.getMessageOrBuilder(); } else { return ttl_ == null ? com.google.protobuf.Duration.getDefaultInstance() : ttl_; } } /** * * * <pre> * Optional. TTL for the backup to expire. Value range is 1 day to 100 years. * If not specified, the default value is 100 years. * </pre> * * <code>.google.protobuf.Duration ttl = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Duration, com.google.protobuf.Duration.Builder, com.google.protobuf.DurationOrBuilder> getTtlFieldBuilder() { if (ttlBuilder_ == null) { ttlBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Duration, com.google.protobuf.Duration.Builder, com.google.protobuf.DurationOrBuilder>(getTtl(), getParentForChildren(), isClean()); ttl_ = null; } return ttlBuilder_; } private java.lang.Object backupId_ = ""; /** * * * <pre> * Optional. The id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional string backup_id = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the backupId field is set. */ public boolean hasBackupId() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Optional. The id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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 id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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 id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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 id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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 id of the backup to be created. If not specified, the * default value ([YYYYMMDDHHMMSS]_[Shortened Cluster UID] is used. * </pre> * * <code>optional 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.redis.cluster.v1.BackupClusterRequest) } // @@protoc_insertion_point(class_scope:google.cloud.redis.cluster.v1.BackupClusterRequest) private static final com.google.cloud.redis.cluster.v1.BackupClusterRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.redis.cluster.v1.BackupClusterRequest(); } public static com.google.cloud.redis.cluster.v1.BackupClusterRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BackupClusterRequest> PARSER = new com.google.protobuf.AbstractParser<BackupClusterRequest>() { @java.lang.Override public BackupClusterRequest 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<BackupClusterRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BackupClusterRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.redis.cluster.v1.BackupClusterRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
38,043
java-dialogflow-cx/google-cloud-dialogflow-cx/src/main/java/com/google/cloud/dialogflow/cx/v3/stub/HttpJsonVersionsStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.cx.v3.stub; import static com.google.cloud.dialogflow.cx.v3.VersionsClient.ListLocationsPagedResponse; import static com.google.cloud.dialogflow.cx.v3.VersionsClient.ListVersionsPagedResponse; import com.google.api.HttpRule; import com.google.api.core.InternalApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.httpjson.ApiMethodDescriptor; import com.google.api.gax.httpjson.HttpJsonCallSettings; import com.google.api.gax.httpjson.HttpJsonOperationSnapshot; import com.google.api.gax.httpjson.HttpJsonStubCallableFactory; import com.google.api.gax.httpjson.ProtoMessageRequestFormatter; import com.google.api.gax.httpjson.ProtoMessageResponseParser; import com.google.api.gax.httpjson.ProtoRestSerializer; import com.google.api.gax.httpjson.longrunning.stub.HttpJsonOperationsStub; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.dialogflow.cx.v3.CompareVersionsRequest; import com.google.cloud.dialogflow.cx.v3.CompareVersionsResponse; import com.google.cloud.dialogflow.cx.v3.CreateVersionOperationMetadata; import com.google.cloud.dialogflow.cx.v3.CreateVersionRequest; import com.google.cloud.dialogflow.cx.v3.DeleteVersionRequest; import com.google.cloud.dialogflow.cx.v3.GetVersionRequest; import com.google.cloud.dialogflow.cx.v3.ListVersionsRequest; import com.google.cloud.dialogflow.cx.v3.ListVersionsResponse; import com.google.cloud.dialogflow.cx.v3.LoadVersionRequest; import com.google.cloud.dialogflow.cx.v3.UpdateVersionRequest; import com.google.cloud.dialogflow.cx.v3.Version; 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.ImmutableMap; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import com.google.protobuf.Struct; import com.google.protobuf.TypeRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * REST stub implementation for the Versions service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonVersionsStub extends VersionsStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder() .add(Empty.getDescriptor()) .add(Version.getDescriptor()) .add(CreateVersionOperationMetadata.getDescriptor()) .add(Struct.getDescriptor()) .build(); private static final ApiMethodDescriptor<ListVersionsRequest, ListVersionsResponse> listVersionsMethodDescriptor = ApiMethodDescriptor.<ListVersionsRequest, ListVersionsResponse>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/ListVersions") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListVersionsRequest>newBuilder() .setPath( "/v3/{parent=projects/*/locations/*/agents/*/flows/*}/versions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListVersionsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListVersionsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "pageSize", request.getPageSize()); serializer.putQueryParam(fields, "pageToken", request.getPageToken()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListVersionsResponse>newBuilder() .setDefaultInstance(ListVersionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetVersionRequest, Version> getVersionMethodDescriptor = ApiMethodDescriptor.<GetVersionRequest, Version>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/GetVersion") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetVersionRequest>newBuilder() .setPath( "/v3/{name=projects/*/locations/*/agents/*/flows/*/versions/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Version>newBuilder() .setDefaultInstance(Version.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<CreateVersionRequest, Operation> createVersionMethodDescriptor = ApiMethodDescriptor.<CreateVersionRequest, Operation>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/CreateVersion") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CreateVersionRequest>newBuilder() .setPath( "/v3/{parent=projects/*/locations/*/agents/*/flows/*}/versions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CreateVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CreateVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("version", request.getVersion(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (CreateVersionRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<UpdateVersionRequest, Version> updateVersionMethodDescriptor = ApiMethodDescriptor.<UpdateVersionRequest, Version>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/UpdateVersion") .setHttpMethod("PATCH") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<UpdateVersionRequest>newBuilder() .setPath( "/v3/{version.name=projects/*/locations/*/agents/*/flows/*/versions/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<UpdateVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "version.name", request.getVersion().getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<UpdateVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "updateMask", request.getUpdateMask()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("version", request.getVersion(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Version>newBuilder() .setDefaultInstance(Version.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<DeleteVersionRequest, Empty> deleteVersionMethodDescriptor = ApiMethodDescriptor.<DeleteVersionRequest, Empty>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/DeleteVersion") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteVersionRequest>newBuilder() .setPath( "/v3/{name=projects/*/locations/*/agents/*/flows/*/versions/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Empty>newBuilder() .setDefaultInstance(Empty.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<LoadVersionRequest, Operation> loadVersionMethodDescriptor = ApiMethodDescriptor.<LoadVersionRequest, Operation>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/LoadVersion") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<LoadVersionRequest>newBuilder() .setPath( "/v3/{name=projects/*/locations/*/agents/*/flows/*/versions/*}:load", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<LoadVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<LoadVersionRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearName().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (LoadVersionRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<CompareVersionsRequest, CompareVersionsResponse> compareVersionsMethodDescriptor = ApiMethodDescriptor.<CompareVersionsRequest, CompareVersionsResponse>newBuilder() .setFullMethodName("google.cloud.dialogflow.cx.v3.Versions/CompareVersions") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CompareVersionsRequest>newBuilder() .setPath( "/v3/{baseVersion=projects/*/locations/*/agents/*/flows/*/versions/*}:compareVersions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CompareVersionsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "baseVersion", request.getBaseVersion()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CompareVersionsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "*", request.toBuilder().clearBaseVersion().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<CompareVersionsResponse>newBuilder() .setDefaultInstance(CompareVersionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<ListLocationsRequest, ListLocationsResponse> listLocationsMethodDescriptor = ApiMethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setFullMethodName("google.cloud.location.Locations/ListLocations") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListLocationsRequest>newBuilder() .setPath( "/v3/{name=projects/*}/locations", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListLocationsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListLocationsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListLocationsResponse>newBuilder() .setDefaultInstance(ListLocationsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor = ApiMethodDescriptor.<GetLocationRequest, Location>newBuilder() .setFullMethodName("google.cloud.location.Locations/GetLocation") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetLocationRequest>newBuilder() .setPath( "/v3/{name=projects/*/locations/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetLocationRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetLocationRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Location>newBuilder() .setDefaultInstance(Location.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<ListVersionsRequest, ListVersionsResponse> listVersionsCallable; private final UnaryCallable<ListVersionsRequest, ListVersionsPagedResponse> listVersionsPagedCallable; private final UnaryCallable<GetVersionRequest, Version> getVersionCallable; private final UnaryCallable<CreateVersionRequest, Operation> createVersionCallable; private final OperationCallable<CreateVersionRequest, Version, CreateVersionOperationMetadata> createVersionOperationCallable; private final UnaryCallable<UpdateVersionRequest, Version> updateVersionCallable; private final UnaryCallable<DeleteVersionRequest, Empty> deleteVersionCallable; private final UnaryCallable<LoadVersionRequest, Operation> loadVersionCallable; private final OperationCallable<LoadVersionRequest, Empty, Struct> loadVersionOperationCallable; private final UnaryCallable<CompareVersionsRequest, CompareVersionsResponse> compareVersionsCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable; private final UnaryCallable<GetLocationRequest, Location> getLocationCallable; private final BackgroundResource backgroundResources; private final HttpJsonOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonVersionsStub create(VersionsStubSettings settings) throws IOException { return new HttpJsonVersionsStub(settings, ClientContext.create(settings)); } public static final HttpJsonVersionsStub create(ClientContext clientContext) throws IOException { return new HttpJsonVersionsStub( VersionsStubSettings.newHttpJsonBuilder().build(), clientContext); } public static final HttpJsonVersionsStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonVersionsStub( VersionsStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonVersionsStub, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonVersionsStub(VersionsStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonVersionsCallableFactory()); } /** * Constructs an instance of HttpJsonVersionsStub, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonVersionsStub( VersionsStubSettings settings, ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.httpJsonOperationsStub = HttpJsonOperationsStub.create( clientContext, callableFactory, typeRegistry, ImmutableMap.<String, HttpRule>builder() .put( "google.longrunning.Operations.CancelOperation", HttpRule.newBuilder() .setPost("/v3/{name=projects/*/operations/*}:cancel") .addAdditionalBindings( HttpRule.newBuilder() .setPost("/v3/{name=projects/*/locations/*/operations/*}:cancel") .build()) .build()) .put( "google.longrunning.Operations.GetOperation", HttpRule.newBuilder() .setGet("/v3/{name=projects/*/operations/*}") .addAdditionalBindings( HttpRule.newBuilder() .setGet("/v3/{name=projects/*/locations/*/operations/*}") .build()) .build()) .put( "google.longrunning.Operations.ListOperations", HttpRule.newBuilder() .setGet("/v3/{name=projects/*}/operations") .addAdditionalBindings( HttpRule.newBuilder() .setGet("/v3/{name=projects/*/locations/*}/operations") .build()) .build()) .build()); HttpJsonCallSettings<ListVersionsRequest, ListVersionsResponse> listVersionsTransportSettings = HttpJsonCallSettings.<ListVersionsRequest, ListVersionsResponse>newBuilder() .setMethodDescriptor(listVersionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<GetVersionRequest, Version> getVersionTransportSettings = HttpJsonCallSettings.<GetVersionRequest, Version>newBuilder() .setMethodDescriptor(getVersionMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<CreateVersionRequest, Operation> createVersionTransportSettings = HttpJsonCallSettings.<CreateVersionRequest, Operation>newBuilder() .setMethodDescriptor(createVersionMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<UpdateVersionRequest, Version> updateVersionTransportSettings = HttpJsonCallSettings.<UpdateVersionRequest, Version>newBuilder() .setMethodDescriptor(updateVersionMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("version.name", String.valueOf(request.getVersion().getName())); return builder.build(); }) .build(); HttpJsonCallSettings<DeleteVersionRequest, Empty> deleteVersionTransportSettings = HttpJsonCallSettings.<DeleteVersionRequest, Empty>newBuilder() .setMethodDescriptor(deleteVersionMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<LoadVersionRequest, Operation> loadVersionTransportSettings = HttpJsonCallSettings.<LoadVersionRequest, Operation>newBuilder() .setMethodDescriptor(loadVersionMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<CompareVersionsRequest, CompareVersionsResponse> compareVersionsTransportSettings = HttpJsonCallSettings.<CompareVersionsRequest, CompareVersionsResponse>newBuilder() .setMethodDescriptor(compareVersionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("base_version", String.valueOf(request.getBaseVersion())); return builder.build(); }) .build(); HttpJsonCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings = HttpJsonCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setMethodDescriptor(listLocationsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<GetLocationRequest, Location> getLocationTransportSettings = HttpJsonCallSettings.<GetLocationRequest, Location>newBuilder() .setMethodDescriptor(getLocationMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); this.listVersionsCallable = callableFactory.createUnaryCallable( listVersionsTransportSettings, settings.listVersionsSettings(), clientContext); this.listVersionsPagedCallable = callableFactory.createPagedCallable( listVersionsTransportSettings, settings.listVersionsSettings(), clientContext); this.getVersionCallable = callableFactory.createUnaryCallable( getVersionTransportSettings, settings.getVersionSettings(), clientContext); this.createVersionCallable = callableFactory.createUnaryCallable( createVersionTransportSettings, settings.createVersionSettings(), clientContext); this.createVersionOperationCallable = callableFactory.createOperationCallable( createVersionTransportSettings, settings.createVersionOperationSettings(), clientContext, httpJsonOperationsStub); this.updateVersionCallable = callableFactory.createUnaryCallable( updateVersionTransportSettings, settings.updateVersionSettings(), clientContext); this.deleteVersionCallable = callableFactory.createUnaryCallable( deleteVersionTransportSettings, settings.deleteVersionSettings(), clientContext); this.loadVersionCallable = callableFactory.createUnaryCallable( loadVersionTransportSettings, settings.loadVersionSettings(), clientContext); this.loadVersionOperationCallable = callableFactory.createOperationCallable( loadVersionTransportSettings, settings.loadVersionOperationSettings(), clientContext, httpJsonOperationsStub); this.compareVersionsCallable = callableFactory.createUnaryCallable( compareVersionsTransportSettings, settings.compareVersionsSettings(), clientContext); this.listLocationsCallable = callableFactory.createUnaryCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.listLocationsPagedCallable = callableFactory.createPagedCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.getLocationCallable = callableFactory.createUnaryCallable( getLocationTransportSettings, settings.getLocationSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(listVersionsMethodDescriptor); methodDescriptors.add(getVersionMethodDescriptor); methodDescriptors.add(createVersionMethodDescriptor); methodDescriptors.add(updateVersionMethodDescriptor); methodDescriptors.add(deleteVersionMethodDescriptor); methodDescriptors.add(loadVersionMethodDescriptor); methodDescriptors.add(compareVersionsMethodDescriptor); methodDescriptors.add(listLocationsMethodDescriptor); methodDescriptors.add(getLocationMethodDescriptor); return methodDescriptors; } public HttpJsonOperationsStub getHttpJsonOperationsStub() { return httpJsonOperationsStub; } @Override public UnaryCallable<ListVersionsRequest, ListVersionsResponse> listVersionsCallable() { return listVersionsCallable; } @Override public UnaryCallable<ListVersionsRequest, ListVersionsPagedResponse> listVersionsPagedCallable() { return listVersionsPagedCallable; } @Override public UnaryCallable<GetVersionRequest, Version> getVersionCallable() { return getVersionCallable; } @Override public UnaryCallable<CreateVersionRequest, Operation> createVersionCallable() { return createVersionCallable; } @Override public OperationCallable<CreateVersionRequest, Version, CreateVersionOperationMetadata> createVersionOperationCallable() { return createVersionOperationCallable; } @Override public UnaryCallable<UpdateVersionRequest, Version> updateVersionCallable() { return updateVersionCallable; } @Override public UnaryCallable<DeleteVersionRequest, Empty> deleteVersionCallable() { return deleteVersionCallable; } @Override public UnaryCallable<LoadVersionRequest, Operation> loadVersionCallable() { return loadVersionCallable; } @Override public OperationCallable<LoadVersionRequest, Empty, Struct> loadVersionOperationCallable() { return loadVersionOperationCallable; } @Override public UnaryCallable<CompareVersionsRequest, CompareVersionsResponse> compareVersionsCallable() { return compareVersionsCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return listLocationsCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return listLocationsPagedCallable; } @Override public UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return getLocationCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
openjdk/jmh
37,924
jmh-core/src/main/java/org/openjdk/jmh/runner/Runner.java
/* * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.jmh.runner; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.IterationParams; import org.openjdk.jmh.profile.ExternalProfiler; import org.openjdk.jmh.profile.ProfilerException; import org.openjdk.jmh.profile.ProfilerFactory; import org.openjdk.jmh.results.*; import org.openjdk.jmh.results.format.ResultFormatFactory; import org.openjdk.jmh.runner.format.OutputFormat; import org.openjdk.jmh.runner.format.OutputFormatFactory; import org.openjdk.jmh.runner.link.BinaryLinkServer; import org.openjdk.jmh.runner.options.*; import org.openjdk.jmh.util.*; import org.openjdk.jmh.util.Optional; import java.io.*; import java.lang.management.ManagementFactory; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.jar.*; import java.util.zip.*; /** * Runner executes JMH benchmarks. * * <p>This is the entry point for JMH Java API.</p> * * <p>{@link Runner} is not usually reusable. After you execute any method on the {@link Runner}, you should digest * the results, give up on current {@link Runner}, and instantiate another one. This class may be turned into * static class in future releases.</p> */ public class Runner extends BaseRunner { private static final int TAIL_LINES_ON_ERROR = Integer.getInteger("jmh.tailLines", 20); private static final String JMH_LOCK_FILE = System.getProperty("java.io.tmpdir") + "/jmh.lock"; private static final Boolean JMH_LOCK_IGNORE = Boolean.getBoolean("jmh.ignoreLock"); private final BenchmarkList list; private int cpuCount; /** * Create runner with the custom OutputFormat. * * @param options options to use * @param format OutputFormat to use */ public Runner(Options options, OutputFormat format) { super(options, format); this.list = BenchmarkList.defaultList(); } /** * Create Runner with the given options. * This method sets up the {@link org.openjdk.jmh.runner.format.OutputFormat} as * mandated by options. * @param options options to use. */ public Runner(Options options) { this(options, createOutputFormat(options)); } private static OutputFormat createOutputFormat(Options options) { // sadly required here as the check cannot be made before calling this method in constructor if (options == null) { throw new IllegalArgumentException("Options not allowed to be null."); } PrintStream out; if (options.getOutput().hasValue()) { try { out = new PrintStream(options.getOutput().get()); } catch (FileNotFoundException ex) { throw new IllegalStateException(ex); } } else { // Protect the System.out from accidental closing try { out = new UnCloseablePrintStream(System.out, Utils.guessConsoleEncoding()); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } return OutputFormatFactory.createFormatInstance(out, options.verbosity().orElse(Defaults.VERBOSITY)); } /** * Print matching benchmarks into output. */ public void list() { Set<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); out.println("Benchmarks: "); for (BenchmarkListEntry benchmark : benchmarks) { out.println(benchmark.getUsername()); } } /** * Print matching benchmarks with parameters into output. * @param options options to use. */ public void listWithParams(CommandLineOptions options) { Set<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); out.println("Benchmarks: "); for (BenchmarkListEntry benchmark : benchmarks) { out.println(benchmark.getUsername()); Optional<Map<String, String[]>> params = benchmark.getParams(); if (params.hasValue()) { for (Map.Entry<String, String[]> e : params.get().entrySet()) { String param = e.getKey(); Collection<String> values = options.getParameter(param).orElse(Arrays.asList(e.getValue())); out.println(" param \"" + param + "\" = {" + Utils.join(values, ", ") + "}"); } } } } /** * Shortcut method for the single benchmark execution. * This method is handy when Options describe only the single benchmark to run. * * @return benchmark result * @throws RunnerException if more than one benchmark is found, or no results are returned */ public RunResult runSingle() throws RunnerException { Set<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); if (benchmarks.size() == 1) { Collection<RunResult> values = run(); if (values.size() == 1) { return values.iterator().next(); } else { throw new RunnerException("No results returned"); } } else { if (benchmarks.size() > 1) { throw new RunnerException("More than single benchmark are matching the options: " + benchmarks); } else { throw new NoBenchmarksException(); } } } /** * Run benchmarks. * * @return map of benchmark results * @throws org.openjdk.jmh.runner.RunnerException if something goes wrong */ public Collection<RunResult> run() throws RunnerException { if (JMH_LOCK_IGNORE) { out.println("# WARNING: JMH lock is ignored by user request, make sure no other JMH instances are running"); return internalRun(); } final String tailMsg = " the JMH lock (" + JMH_LOCK_FILE + "), exiting. Use -Djmh.ignoreLock=true to forcefully continue."; File lockFile; try { lockFile = new File(JMH_LOCK_FILE); lockFile.createNewFile(); // Make sure the lock file is world-writeable, otherwise the lock file created by current // user would not work for any other user, always failing the run. lockFile.setWritable(true, false); } catch (IOException e) { throw new RunnerException("ERROR: Unable to create" + tailMsg, e); } try (RandomAccessFile raf = new RandomAccessFile(lockFile, "rw"); FileLock lock = raf.getChannel().tryLock()) { if (lock == null) { // Lock acquisition failed, pretend this was the overlap. throw new OverlappingFileLockException(); } return internalRun(); } catch (OverlappingFileLockException e) { throw new RunnerException("ERROR: Another JMH instance might be running. Unable to acquire" + tailMsg); } catch (IOException e) { throw new RunnerException("ERROR: Unexpected exception while trying to acquire" + tailMsg, e); } } private Collection<RunResult> internalRun() throws RunnerException { Set<String> profilerClasses = new HashSet<>(); ProfilersFailedException failedException = null; for (ProfilerConfig p : options.getProfilers()) { if (!profilerClasses.add(p.getKlass())) { throw new RunnerException("Cannot instantiate the same profiler more than once: " + p.getKlass()); } try { ProfilerFactory.getProfilerOrException(p); } catch (ProfilerException e) { if (failedException == null) { failedException = new ProfilersFailedException(e); } else { failedException.addSuppressed(e); } } } if (failedException != null) { throw failedException; } // If user requested the result file in one way or the other, touch the result file, // and prepare to write it out after the run. String resultFile = null; if (options.getResult().hasValue() || options.getResultFormat().hasValue()) { resultFile = options.getResult().orElse( Defaults.RESULT_FILE_PREFIX + "." + options.getResultFormat().orElse(Defaults.RESULT_FORMAT).toString().toLowerCase() ); try { FileUtils.touch(resultFile); } catch (IOException e) { throw new RunnerException("Can not touch the result file: " + resultFile); } } SortedSet<BenchmarkListEntry> benchmarks = list.find(out, options.getIncludes(), options.getExcludes()); if (benchmarks.isEmpty()) { out.flush(); out.close(); throw new NoBenchmarksException(); } // override the benchmark types; // this may yield new benchmark records if (!options.getBenchModes().isEmpty()) { List<BenchmarkListEntry> newBenchmarks = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { for (Mode m : options.getBenchModes()) { newBenchmarks.add(br.cloneWith(m)); } } benchmarks.clear(); benchmarks.addAll(newBenchmarks); } // clone with all the modes { List<BenchmarkListEntry> newBenchmarks = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { if (br.getMode() == Mode.All) { for (Mode mode : Mode.values()) { if (mode == Mode.All) continue; newBenchmarks.add(br.cloneWith(mode)); } } else { newBenchmarks.add(br); } } benchmarks.clear(); benchmarks.addAll(newBenchmarks); } // clone with all parameters { List<BenchmarkListEntry> newBenchmarks = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { if (br.getParams().hasValue()) { for (WorkloadParams p : explodeAllParams(br)) { newBenchmarks.add(br.cloneWith(p)); } } else { newBenchmarks.add(br); } } benchmarks.clear(); benchmarks.addAll(newBenchmarks); } Collection<RunResult> results = runBenchmarks(benchmarks); // If user requested the result file, write it out. if (resultFile != null) { ResultFormatFactory.getInstance( options.getResultFormat().orElse(Defaults.RESULT_FORMAT), resultFile ).writeOut(results); out.println(""); out.println("Benchmark result is saved to " + resultFile); } out.flush(); out.close(); return results; } private List<ActionPlan> getActionPlans(Set<BenchmarkListEntry> benchmarks) { ActionPlan base = new ActionPlan(ActionType.FORKED); LinkedHashSet<BenchmarkListEntry> warmupBenches = new LinkedHashSet<>(); List<String> warmupMicrosRegexp = options.getWarmupIncludes(); if (warmupMicrosRegexp != null && !warmupMicrosRegexp.isEmpty()) { warmupBenches.addAll(list.find(out, warmupMicrosRegexp, Collections.<String>emptyList())); } if (options.getWarmupMode().orElse(Defaults.WARMUP_MODE).isBulk()) { warmupBenches.addAll(benchmarks); } for (BenchmarkListEntry wr : warmupBenches) { base.add(newAction(wr, ActionMode.WARMUP)); } ActionPlan embeddedPlan = new ActionPlan(ActionType.EMBEDDED); embeddedPlan.mixIn(base); boolean addEmbedded = false; List<ActionPlan> result = new ArrayList<>(); for (BenchmarkListEntry br : benchmarks) { BenchmarkParams params = newBenchmarkParams(br, ActionMode.UNDEF); if (params.getForks() <= 0) { if (options.getWarmupMode().orElse(Defaults.WARMUP_MODE).isIndi()) { embeddedPlan.add(newAction(br, ActionMode.WARMUP_MEASUREMENT)); } else { embeddedPlan.add(newAction(br, ActionMode.MEASUREMENT)); } addEmbedded = true; } if (params.getForks() > 0) { ActionPlan r = new ActionPlan(ActionType.FORKED); r.mixIn(base); if (options.getWarmupMode().orElse(Defaults.WARMUP_MODE).isIndi()) { r.add(newAction(br, ActionMode.WARMUP_MEASUREMENT)); } else { r.add(newAction(br, ActionMode.MEASUREMENT)); } result.add(r); } } if (addEmbedded) { result.add(embeddedPlan); } return result; } private Action newAction(BenchmarkListEntry br, ActionMode mode) { return new Action(newBenchmarkParams(br, mode), mode); } private BenchmarkParams newBenchmarkParams(BenchmarkListEntry benchmark, ActionMode mode) { int[] threadGroups = options.getThreadGroups().orElse(benchmark.getThreadGroups()); int threads = options.getThreads().orElse( benchmark.getThreads().orElse( Defaults.THREADS)); if (threads == Threads.MAX || threads == Threads.HALF_MAX) { if (cpuCount == 0) { out.print("# Detecting actual CPU count: "); cpuCount = Utils.figureOutHotCPUs(); out.println(cpuCount + " detected"); } if (threads == Threads.HALF_MAX) { threads = (cpuCount + 1) / 2; } else { threads = cpuCount; } } threads = Utils.roundUp(threads, Utils.sum(threadGroups)); boolean synchIterations = (benchmark.getMode() != Mode.SingleShotTime) && options.shouldSyncIterations().orElse(Defaults.SYNC_ITERATIONS); IterationParams measurement = mode.doMeasurement() ? new IterationParams( IterationType.MEASUREMENT, options.getMeasurementIterations().orElse( benchmark.getMeasurementIterations().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? Defaults.MEASUREMENT_ITERATIONS_SINGLESHOT : Defaults.MEASUREMENT_ITERATIONS )), options.getMeasurementTime().orElse( benchmark.getMeasurementTime().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? TimeValue.NONE : Defaults.MEASUREMENT_TIME )), options.getMeasurementBatchSize().orElse( benchmark.getMeasurementBatchSize().orElse( Defaults.MEASUREMENT_BATCHSIZE ) ) ) : new IterationParams(IterationType.MEASUREMENT, 0, TimeValue.NONE, 1); IterationParams warmup = mode.doWarmup() ? new IterationParams( IterationType.WARMUP, options.getWarmupIterations().orElse( benchmark.getWarmupIterations().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? Defaults.WARMUP_ITERATIONS_SINGLESHOT : Defaults.WARMUP_ITERATIONS )), options.getWarmupTime().orElse( benchmark.getWarmupTime().orElse( (benchmark.getMode() == Mode.SingleShotTime) ? TimeValue.NONE : Defaults.WARMUP_TIME )), options.getWarmupBatchSize().orElse( benchmark.getWarmupBatchSize().orElse( Defaults.WARMUP_BATCHSIZE ) ) ) : new IterationParams(IterationType.WARMUP, 0, TimeValue.NONE, 1); int forks = options.getForkCount().orElse( benchmark.getForks().orElse( Defaults.MEASUREMENT_FORKS)); int warmupForks = options.getWarmupForkCount().orElse( benchmark.getWarmupForks().orElse( Defaults.WARMUP_FORKS)); TimeUnit timeUnit = options.getTimeUnit().orElse( benchmark.getTimeUnit().orElse( Defaults.OUTPUT_TIMEUNIT)); int opsPerInvocation = options.getOperationsPerInvocation().orElse( benchmark.getOperationsPerInvocation().orElse( Defaults.OPS_PER_INVOCATION)); String jvm = options.getJvm().orElse( benchmark.getJvm().orElse(Utils.getCurrentJvm())); Properties targetProperties; if (jvm.equals(Utils.getCurrentJvm())) { targetProperties = Utils.getRecordedSystemProperties(); } else { targetProperties = Utils.readPropertiesFromCommand(getPrintPropertiesCommand(jvm)); } Collection<String> jvmArgs = new ArrayList<>(); jvmArgs.addAll(options.getJvmArgsPrepend().orElse( benchmark.getJvmArgsPrepend().orElse(Collections.<String>emptyList()))); // We want to be extra lazy when accessing ManagementFactory, because security manager // may prevent us doing so. jvmArgs.addAll(options.getJvmArgs() .orElseGet(() -> benchmark.getJvmArgs() .orElseGet(() -> ManagementFactory.getRuntimeMXBean().getInputArguments()) )); jvmArgs.addAll(options.getJvmArgsAppend().orElse( benchmark.getJvmArgsAppend().orElse(Collections.<String>emptyList()))); TimeValue timeout = options.getTimeout().orElse( benchmark.getTimeout().orElse(Defaults.TIMEOUT)); String jdkVersion = targetProperties.getProperty("java.version"); String vmVersion = targetProperties.getProperty("java.vm.version"); String vmName = targetProperties.getProperty("java.vm.name"); return new BenchmarkParams(benchmark.getUsername(), benchmark.generatedTarget(), synchIterations, threads, threadGroups, benchmark.getThreadGroupLabels().orElse(Collections.<String>emptyList()), forks, warmupForks, warmup, measurement, benchmark.getMode(), benchmark.getWorkloadParams(), timeUnit, opsPerInvocation, jvm, jvmArgs, jdkVersion, vmName, vmVersion, Version.getPlainVersion(), timeout); } private List<WorkloadParams> explodeAllParams(BenchmarkListEntry br) throws RunnerException { Map<String, String[]> benchParams = br.getParams().orElse(Collections.<String, String[]>emptyMap()); List<WorkloadParams> ps = new ArrayList<>(); for (Map.Entry<String, String[]> e : benchParams.entrySet()) { String k = e.getKey(); String[] vals = e.getValue(); Collection<String> values = options.getParameter(k).orElse(Arrays.asList(vals)); if (values.isEmpty()) { throw new RunnerException("Benchmark \"" + br.getUsername() + "\" defines the parameter \"" + k + "\", but no default values.\n" + "Define the default values within the annotation, or provide the parameter values at runtime."); } if (ps.isEmpty()) { int idx = 0; for (String v : values) { WorkloadParams al = new WorkloadParams(); al.put(k, v, idx); ps.add(al); idx++; } } else { List<WorkloadParams> newPs = new ArrayList<>(); for (WorkloadParams p : ps) { int idx = 0; for (String v : values) { WorkloadParams al = p.copy(); al.put(k, v, idx); newPs.add(al); idx++; } } ps = newPs; } } return ps; } private Collection<RunResult> runBenchmarks(SortedSet<BenchmarkListEntry> benchmarks) throws RunnerException { out.startRun(); Multimap<BenchmarkParams, BenchmarkResult> results = new TreeMultimap<>(); List<ActionPlan> plan = getActionPlans(benchmarks); etaBeforeBenchmarks(plan); try { for (ActionPlan r : plan) { Multimap<BenchmarkParams, BenchmarkResult> res; switch (r.getType()) { case EMBEDDED: res = runBenchmarksEmbedded(r); break; case FORKED: res = runSeparate(r); break; default: throw new IllegalStateException("Unknown action plan type: " + r.getType()); } for (BenchmarkParams br : res.keys()) { results.putAll(br, res.get(br)); } } etaAfterBenchmarks(); SortedSet<RunResult> runResults = mergeRunResults(results); out.endRun(runResults); return runResults; } catch (BenchmarkException be) { throw new RunnerException("Benchmark caught the exception", be); } } private SortedSet<RunResult> mergeRunResults(Multimap<BenchmarkParams, BenchmarkResult> results) { SortedSet<RunResult> result = new TreeSet<>(RunResult.DEFAULT_SORT_COMPARATOR); for (BenchmarkParams key : results.keys()) { result.add(new RunResult(key, results.get(key))); } return result; } private Multimap<BenchmarkParams, BenchmarkResult> runSeparate(ActionPlan actionPlan) { Multimap<BenchmarkParams, BenchmarkResult> results = new HashMultimap<>(); if (actionPlan.getMeasurementActions().size() != 1) { throw new IllegalStateException("Expect only single benchmark in the action plan, but was " + actionPlan.getMeasurementActions().size()); } BinaryLinkServer server = null; try { server = new BinaryLinkServer(options, out); server.setPlan(actionPlan); BenchmarkParams params = actionPlan.getMeasurementActions().get(0).getParams(); List<ExternalProfiler> profilers = ProfilerFactory.getSupportedExternal(options.getProfilers()); boolean printOut = true; boolean printErr = true; for (ExternalProfiler prof : profilers) { printOut &= prof.allowPrintOut(); printErr &= prof.allowPrintErr(); } List<ExternalProfiler> profilersRev = new ArrayList<>(profilers); Collections.reverse(profilersRev); boolean forcePrint = options.verbosity().orElse(Defaults.VERBOSITY).equalsOrHigherThan(VerboseMode.EXTRA); printOut = forcePrint || printOut; printErr = forcePrint || printErr; out.startBenchmark(params); out.println(""); int forkCount = params.getForks(); int warmupForkCount = params.getWarmupForks(); int totalForks = warmupForkCount + forkCount; for (int i = 0; i < totalForks; i++) { boolean warmupFork = (i < warmupForkCount); List<String> forkedString = getForkedMainCommand(params, profilers, server.getHost(), server.getPort()); etaBeforeBenchmark(); if (warmupFork) { out.verbosePrintln("Warmup forking using command: " + forkedString); out.println("# Warmup Fork: " + (i + 1) + " of " + warmupForkCount); } else { out.verbosePrintln("Forking using command: " + forkedString); out.println("# Fork: " + (i + 1 - warmupForkCount) + " of " + forkCount); } TempFile stdErr = FileUtils.weakTempFile("stderr"); TempFile stdOut = FileUtils.weakTempFile("stdout"); if (!profilers.isEmpty()) { out.print("# Preparing profilers: "); for (ExternalProfiler profiler : profilers) { out.print(profiler.getClass().getSimpleName() + " "); profiler.beforeTrial(params); } out.println(""); List<String> consumed = new ArrayList<>(); if (!printOut) consumed.add("stdout"); if (!printErr) consumed.add("stderr"); if (!consumed.isEmpty()) { out.println("# Profilers consume " + Utils.join(consumed, " and ") + " from target VM, use -v " + VerboseMode.EXTRA + " to copy to console"); } } long startTime = System.currentTimeMillis(); List<IterationResult> result = doFork(server, forkedString, stdOut.file(), stdErr.file(), printOut, printErr); if (!result.isEmpty()) { long pid = server.getClientPid(); BenchmarkResultMetaData md = server.getMetadata(); if (md != null) { md.adjustStart(startTime); } BenchmarkResult br = new BenchmarkResult(params, result, md); if (!profilersRev.isEmpty()) { out.print("# Processing profiler results: "); for (ExternalProfiler profiler : profilersRev) { out.print(profiler.getClass().getSimpleName() + " "); for (Result profR : profiler.afterTrial(br, pid, stdOut.file(), stdErr.file())) { br.addBenchmarkResult(profR); } } out.println(""); } if (!warmupFork) { results.put(params, br); } } etaAfterBenchmark(params); out.println(""); // we know these are not needed anymore, proactively delete stdOut.delete(); stdErr.delete(); } out.endBenchmark(new RunResult(params, results.get(params)).getAggregatedResult()); } catch (IOException e) { results.clear(); throw new BenchmarkException(e); } catch (BenchmarkException e) { results.clear(); if (options.shouldFailOnError().orElse(Defaults.FAIL_ON_ERROR)) { out.println("Benchmark had encountered error, and fail on error was requested"); throw e; } } finally { if (server != null) { server.terminate(); } FileUtils.purgeTemps(); } return results; } private List<IterationResult> doFork(BinaryLinkServer reader, List<String> commandString, File stdOut, File stdErr, boolean printOut, boolean printErr) { try (FileOutputStream fosErr = new FileOutputStream(stdErr); FileOutputStream fosOut = new FileOutputStream(stdOut)) { ProcessBuilder pb = new ProcessBuilder(commandString); Process p = pb.start(); // drain streams, else we might lock up InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), fosErr); InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), fosOut); if (printErr) { errDrainer.addOutputStream(new OutputFormatAdapter(out)); } if (printOut) { outDrainer.addOutputStream(new OutputFormatAdapter(out)); } errDrainer.start(); outDrainer.start(); int ecode = p.waitFor(); errDrainer.join(); outDrainer.join(); // need to wait for all pending messages to be processed // before starting the next benchmark reader.waitFinish(); if (ecode != 0) { out.println("<forked VM failed with exit code " + ecode + ">"); out.println("<stdout last='" + TAIL_LINES_ON_ERROR + " lines'>"); for (String l : FileUtils.tail(stdOut, TAIL_LINES_ON_ERROR)) { out.println(l); } out.println("</stdout>"); out.println("<stderr last='" + TAIL_LINES_ON_ERROR + " lines'>"); for (String l : FileUtils.tail(stdErr, TAIL_LINES_ON_ERROR)) { out.println(l); } out.println("</stderr>"); out.println(""); } BenchmarkException exception = reader.getException(); if (exception == null) { if (ecode == 0) { return reader.getResults(); } else { throw new BenchmarkException(new IllegalStateException("Forked VM failed with exit code " + ecode)); } } else { throw exception; } } catch (IOException ex) { out.println("<failed to invoke the VM, caught IOException: " + ex.getMessage() + ">"); out.println(""); throw new BenchmarkException(ex); } catch (InterruptedException ex) { out.println("<host VM has been interrupted waiting for forked VM: " + ex.getMessage() + ">"); out.println(""); throw new BenchmarkException(ex); } } /** * @param host host VM host * @param port host VM port * @return */ List<String> getForkedMainCommand(BenchmarkParams benchmark, List<ExternalProfiler> profilers, String host, int port) { // Poll profilers for options List<String> javaInvokeOptions = new ArrayList<>(); List<String> javaOptions = new ArrayList<>(); for (ExternalProfiler prof : profilers) { javaInvokeOptions.addAll(prof.addJVMInvokeOptions(benchmark)); javaOptions.addAll(prof.addJVMOptions(benchmark)); } List<String> command = new ArrayList<>(); // prefix java invoke options, if any profiler wants it command.addAll(javaInvokeOptions); // use supplied jvm, if given command.add(benchmark.getJvm()); // use supplied jvm args, if given command.addAll(benchmark.getJvmArgs()); // add profiler JVM commands, if any profiler wants it command.addAll(javaOptions); // add any compiler oracle hints CompilerHints.addCompilerHints(command); // assemble final process command addClasspath(command); command.add(ForkedMain.class.getName()); // Forked VM assumes the exact order of arguments: // 1) host name to back-connect // 2) host port to back-connect command.add(host); command.add(String.valueOf(port)); return command; } private List<String> getPrintPropertiesCommand(String jvm) { List<String> command = new ArrayList<>(); // use supplied jvm, if given command.add(jvm); // assemble final process command addClasspath(command); command.add(PrintPropertiesMain.class.getName()); return command; } private void addClasspath(List<String> command) { command.add("-cp"); String cpProp = System.getProperty("java.class.path"); File tmpFile = null; String jvmargs = "" + options.getJvmArgs().orElse(Collections.<String>emptyList()) + options.getJvmArgsPrepend().orElse(Collections.<String>emptyList()) + options.getJvmArgsAppend().orElse(Collections.<String>emptyList()); // The second (creepy) test is for the cases when external plugins are not supplying // the options properly. Looking at you, JMH Gradle plugin. In this case, we explicitly // check if the option is provided by the user. if (Boolean.getBoolean("jmh.separateClasspathJAR") || jvmargs.contains("jmh.separateClasspathJAR=true")) { // Classpath can be too long and overflow the command line length. // Looking at you, Windows. // // The trick is to generate the JAR file with appropriate Class-Path manifest entry, // and link it. The complication is that Class-Path entry paths are specified relative // to JAR file loaded, which is probably somewhere in java.io.tmpdir, outside of current // directory. Therefore, we have to relativize the paths to all the JAR entries. try { tmpFile = FileUtils.tempFile("classpath.jar"); Path tmpFileDir = tmpFile.toPath().getParent(); StringBuilder sb = new StringBuilder(); for (String cp : cpProp.split(File.pathSeparator)) { Path cpPath = new File(cp).getAbsoluteFile().toPath(); if (!cpPath.getRoot().equals(tmpFileDir.getRoot())) { throw new IOException("Cannot relativize: " + cpPath + " and " + tmpFileDir + " have different roots."); } Path relPath = tmpFileDir.relativize(cpPath); if (!Files.isReadable(tmpFileDir.resolve(relPath))) { throw new IOException("Cannot read through the relativized path: " + relPath); } String rel = relPath.toString(); sb.append(rel.replace('\\', '/').replace(" ", "%20")); if (Files.isDirectory(cpPath)) { sb.append('/'); } sb.append(" "); } String classPath = sb.toString().trim(); Manifest manifest = new Manifest(); Attributes attrs = manifest.getMainAttributes(); attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attrs.putValue("Class-Path", classPath); try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(tmpFile), manifest)) { jos.putNextEntry(new ZipEntry("META-INF/")); } out.verbosePrintln("Using separate classpath JAR: " + tmpFile); out.verbosePrintln(" Class-Path: " + classPath); } catch (IOException ex) { // Something is wrong in file generation, give up and fall-through to usual thing out.verbosePrintln("Caught IOException when building separate classpath JAR: " + ex.getMessage() + ", falling back to default -cp."); tmpFile = null; } } if (tmpFile != null) { if (Utils.isWindows()) { command.add("\"" + tmpFile.getAbsolutePath() + "\""); } else { command.add(tmpFile.getAbsolutePath()); } } else { if (Utils.isWindows()) { command.add('"' + cpProp + '"'); } else { command.add(cpProp); } } } }
googleapis/google-cloud-java
37,791
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListTuningJobsResponse.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/genai_tuning_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Response message for * [GenAiTuningService.ListTuningJobs][google.cloud.aiplatform.v1beta1.GenAiTuningService.ListTuningJobs] * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListTuningJobsResponse} */ public final class ListTuningJobsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListTuningJobsResponse) ListTuningJobsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListTuningJobsResponse.newBuilder() to construct. private ListTuningJobsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListTuningJobsResponse() { tuningJobs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListTuningJobsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.class, com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.Builder.class); } public static final int TUNING_JOBS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1beta1.TuningJob> tuningJobs_; /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.TuningJob> getTuningJobsList() { return tuningJobs_; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder> getTuningJobsOrBuilderList() { return tuningJobs_; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ @java.lang.Override public int getTuningJobsCount() { return tuningJobs_.size(); } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TuningJob getTuningJobs(int index) { return tuningJobs_.get(index); } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder getTuningJobsOrBuilder(int index) { return tuningJobs_.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 * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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 * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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 < tuningJobs_.size(); i++) { output.writeMessage(1, tuningJobs_.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 < tuningJobs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, tuningJobs_.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.ListTuningJobsResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse other = (com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse) obj; if (!getTuningJobsList().equals(other.getTuningJobsList())) 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 (getTuningJobsCount() > 0) { hash = (37 * hash) + TUNING_JOBS_FIELD_NUMBER; hash = (53 * hash) + getTuningJobsList().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.ListTuningJobsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse 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.ListTuningJobsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse 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.ListTuningJobsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse 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.ListTuningJobsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse 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.ListTuningJobsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse 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.ListTuningJobsResponse 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.ListTuningJobsResponse 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.ListTuningJobsResponse 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 * [GenAiTuningService.ListTuningJobs][google.cloud.aiplatform.v1beta1.GenAiTuningService.ListTuningJobs] * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListTuningJobsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListTuningJobsResponse) com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.class, com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (tuningJobsBuilder_ == null) { tuningJobs_ = java.util.Collections.emptyList(); } else { tuningJobs_ = null; tuningJobsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.GenAiTuningServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListTuningJobsResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse build() { com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse buildPartial() { com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse result = new com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse result) { if (tuningJobsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { tuningJobs_ = java.util.Collections.unmodifiableList(tuningJobs_); bitField0_ = (bitField0_ & ~0x00000001); } result.tuningJobs_ = tuningJobs_; } else { result.tuningJobs_ = tuningJobsBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse 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.ListTuningJobsResponse) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse other) { if (other == com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse.getDefaultInstance()) return this; if (tuningJobsBuilder_ == null) { if (!other.tuningJobs_.isEmpty()) { if (tuningJobs_.isEmpty()) { tuningJobs_ = other.tuningJobs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTuningJobsIsMutable(); tuningJobs_.addAll(other.tuningJobs_); } onChanged(); } } else { if (!other.tuningJobs_.isEmpty()) { if (tuningJobsBuilder_.isEmpty()) { tuningJobsBuilder_.dispose(); tuningJobsBuilder_ = null; tuningJobs_ = other.tuningJobs_; bitField0_ = (bitField0_ & ~0x00000001); tuningJobsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTuningJobsFieldBuilder() : null; } else { tuningJobsBuilder_.addAllMessages(other.tuningJobs_); } } } 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.TuningJob m = input.readMessage( com.google.cloud.aiplatform.v1beta1.TuningJob.parser(), extensionRegistry); if (tuningJobsBuilder_ == null) { ensureTuningJobsIsMutable(); tuningJobs_.add(m); } else { tuningJobsBuilder_.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.TuningJob> tuningJobs_ = java.util.Collections.emptyList(); private void ensureTuningJobsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { tuningJobs_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.TuningJob>(tuningJobs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.TuningJob, com.google.cloud.aiplatform.v1beta1.TuningJob.Builder, com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder> tuningJobsBuilder_; /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.TuningJob> getTuningJobsList() { if (tuningJobsBuilder_ == null) { return java.util.Collections.unmodifiableList(tuningJobs_); } else { return tuningJobsBuilder_.getMessageList(); } } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public int getTuningJobsCount() { if (tuningJobsBuilder_ == null) { return tuningJobs_.size(); } else { return tuningJobsBuilder_.getCount(); } } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.TuningJob getTuningJobs(int index) { if (tuningJobsBuilder_ == null) { return tuningJobs_.get(index); } else { return tuningJobsBuilder_.getMessage(index); } } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder setTuningJobs(int index, com.google.cloud.aiplatform.v1beta1.TuningJob value) { if (tuningJobsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTuningJobsIsMutable(); tuningJobs_.set(index, value); onChanged(); } else { tuningJobsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder setTuningJobs( int index, com.google.cloud.aiplatform.v1beta1.TuningJob.Builder builderForValue) { if (tuningJobsBuilder_ == null) { ensureTuningJobsIsMutable(); tuningJobs_.set(index, builderForValue.build()); onChanged(); } else { tuningJobsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder addTuningJobs(com.google.cloud.aiplatform.v1beta1.TuningJob value) { if (tuningJobsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTuningJobsIsMutable(); tuningJobs_.add(value); onChanged(); } else { tuningJobsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder addTuningJobs(int index, com.google.cloud.aiplatform.v1beta1.TuningJob value) { if (tuningJobsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTuningJobsIsMutable(); tuningJobs_.add(index, value); onChanged(); } else { tuningJobsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder addTuningJobs( com.google.cloud.aiplatform.v1beta1.TuningJob.Builder builderForValue) { if (tuningJobsBuilder_ == null) { ensureTuningJobsIsMutable(); tuningJobs_.add(builderForValue.build()); onChanged(); } else { tuningJobsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder addTuningJobs( int index, com.google.cloud.aiplatform.v1beta1.TuningJob.Builder builderForValue) { if (tuningJobsBuilder_ == null) { ensureTuningJobsIsMutable(); tuningJobs_.add(index, builderForValue.build()); onChanged(); } else { tuningJobsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder addAllTuningJobs( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.TuningJob> values) { if (tuningJobsBuilder_ == null) { ensureTuningJobsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tuningJobs_); onChanged(); } else { tuningJobsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder clearTuningJobs() { if (tuningJobsBuilder_ == null) { tuningJobs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { tuningJobsBuilder_.clear(); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public Builder removeTuningJobs(int index) { if (tuningJobsBuilder_ == null) { ensureTuningJobsIsMutable(); tuningJobs_.remove(index); onChanged(); } else { tuningJobsBuilder_.remove(index); } return this; } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.TuningJob.Builder getTuningJobsBuilder(int index) { return getTuningJobsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder getTuningJobsOrBuilder( int index) { if (tuningJobsBuilder_ == null) { return tuningJobs_.get(index); } else { return tuningJobsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder> getTuningJobsOrBuilderList() { if (tuningJobsBuilder_ != null) { return tuningJobsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(tuningJobs_); } } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.TuningJob.Builder addTuningJobsBuilder() { return getTuningJobsFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1beta1.TuningJob.getDefaultInstance()); } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.TuningJob.Builder addTuningJobsBuilder(int index) { return getTuningJobsFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1beta1.TuningJob.getDefaultInstance()); } /** * * * <pre> * List of TuningJobs in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.TuningJob tuning_jobs = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.TuningJob.Builder> getTuningJobsBuilderList() { return getTuningJobsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.TuningJob, com.google.cloud.aiplatform.v1beta1.TuningJob.Builder, com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder> getTuningJobsFieldBuilder() { if (tuningJobsBuilder_ == null) { tuningJobsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.TuningJob, com.google.cloud.aiplatform.v1beta1.TuningJob.Builder, com.google.cloud.aiplatform.v1beta1.TuningJobOrBuilder>( tuningJobs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); tuningJobs_ = null; } return tuningJobsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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 * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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 * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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 * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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 * [ListTuningJobsRequest.page_token][google.cloud.aiplatform.v1beta1.ListTuningJobsRequest.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.ListTuningJobsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListTuningJobsResponse) private static final com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse(); } public static com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListTuningJobsResponse> PARSER = new com.google.protobuf.AbstractParser<ListTuningJobsResponse>() { @java.lang.Override public ListTuningJobsResponse 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<ListTuningJobsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListTuningJobsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListTuningJobsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,786
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ForwardingRuleServiceDirectoryRegistration.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> * Describes the auto-registration of the forwarding rule to Service Directory. The region and project of the Service Directory resource generated from this registration will be the same as this forwarding rule. * </pre> * * Protobuf type {@code google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration} */ public final class ForwardingRuleServiceDirectoryRegistration extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration) ForwardingRuleServiceDirectoryRegistrationOrBuilder { private static final long serialVersionUID = 0L; // Use ForwardingRuleServiceDirectoryRegistration.newBuilder() to construct. private ForwardingRuleServiceDirectoryRegistration( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ForwardingRuleServiceDirectoryRegistration() { namespace_ = ""; service_ = ""; serviceDirectoryRegion_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ForwardingRuleServiceDirectoryRegistration(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ForwardingRuleServiceDirectoryRegistration_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ForwardingRuleServiceDirectoryRegistration_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration.class, com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration.Builder.class); } private int bitField0_; public static final int NAMESPACE_FIELD_NUMBER = 178476379; @SuppressWarnings("serial") private volatile java.lang.Object namespace_ = ""; /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return Whether the namespace field is set. */ @java.lang.Override public boolean hasNamespace() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return The namespace. */ @java.lang.Override public java.lang.String getNamespace() { java.lang.Object ref = namespace_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); namespace_ = s; return s; } } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return The bytes for namespace. */ @java.lang.Override public com.google.protobuf.ByteString getNamespaceBytes() { java.lang.Object ref = namespace_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); namespace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICE_FIELD_NUMBER = 373540533; @SuppressWarnings("serial") private volatile java.lang.Object service_ = ""; /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return Whether the service field is set. */ @java.lang.Override public boolean hasService() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return The service. */ @java.lang.Override public java.lang.String getService() { java.lang.Object ref = service_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); service_ = s; return s; } } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return The bytes for service. */ @java.lang.Override public com.google.protobuf.ByteString getServiceBytes() { java.lang.Object ref = service_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); service_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICE_DIRECTORY_REGION_FIELD_NUMBER = 74030416; @SuppressWarnings("serial") private volatile java.lang.Object serviceDirectoryRegion_ = ""; /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return Whether the serviceDirectoryRegion field is set. */ @java.lang.Override public boolean hasServiceDirectoryRegion() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return The serviceDirectoryRegion. */ @java.lang.Override public java.lang.String getServiceDirectoryRegion() { java.lang.Object ref = serviceDirectoryRegion_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceDirectoryRegion_ = s; return s; } } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return The bytes for serviceDirectoryRegion. */ @java.lang.Override public com.google.protobuf.ByteString getServiceDirectoryRegionBytes() { java.lang.Object ref = serviceDirectoryRegion_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); serviceDirectoryRegion_ = 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_ & 0x00000004) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 74030416, serviceDirectoryRegion_); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 178476379, namespace_); } if (((bitField0_ & 0x00000002) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 373540533, service_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize( 74030416, serviceDirectoryRegion_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(178476379, namespace_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(373540533, service_); } 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.ForwardingRuleServiceDirectoryRegistration)) { return super.equals(obj); } com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration other = (com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration) obj; if (hasNamespace() != other.hasNamespace()) return false; if (hasNamespace()) { if (!getNamespace().equals(other.getNamespace())) return false; } if (hasService() != other.hasService()) return false; if (hasService()) { if (!getService().equals(other.getService())) return false; } if (hasServiceDirectoryRegion() != other.hasServiceDirectoryRegion()) return false; if (hasServiceDirectoryRegion()) { if (!getServiceDirectoryRegion().equals(other.getServiceDirectoryRegion())) 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 (hasNamespace()) { hash = (37 * hash) + NAMESPACE_FIELD_NUMBER; hash = (53 * hash) + getNamespace().hashCode(); } if (hasService()) { hash = (37 * hash) + SERVICE_FIELD_NUMBER; hash = (53 * hash) + getService().hashCode(); } if (hasServiceDirectoryRegion()) { hash = (37 * hash) + SERVICE_DIRECTORY_REGION_FIELD_NUMBER; hash = (53 * hash) + getServiceDirectoryRegion().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration 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.ForwardingRuleServiceDirectoryRegistration prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Describes the auto-registration of the forwarding rule to Service Directory. The region and project of the Service Directory resource generated from this registration will be the same as this forwarding rule. * </pre> * * Protobuf type {@code google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration) com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistrationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ForwardingRuleServiceDirectoryRegistration_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ForwardingRuleServiceDirectoryRegistration_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration.class, com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration.Builder.class); } // Construct using // com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; namespace_ = ""; service_ = ""; serviceDirectoryRegion_ = ""; 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_ForwardingRuleServiceDirectoryRegistration_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration getDefaultInstanceForType() { return com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration .getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration build() { com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration buildPartial() { com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration result = new com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.namespace_ = namespace_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.service_ = service_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.serviceDirectoryRegion_ = serviceDirectoryRegion_; to_bitField0_ |= 0x00000004; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration) { return mergeFrom( (com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration other) { if (other == com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration .getDefaultInstance()) return this; if (other.hasNamespace()) { namespace_ = other.namespace_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasService()) { service_ = other.service_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasServiceDirectoryRegion()) { serviceDirectoryRegion_ = other.serviceDirectoryRegion_; 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 592243330: { serviceDirectoryRegion_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 592243330 case 1427811034: { namespace_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 1427811034 case -1306643030: { service_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case -1306643030 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 namespace_ = ""; /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return Whether the namespace field is set. */ public boolean hasNamespace() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return The namespace. */ public java.lang.String getNamespace() { java.lang.Object ref = namespace_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); namespace_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return The bytes for namespace. */ public com.google.protobuf.ByteString getNamespaceBytes() { java.lang.Object ref = namespace_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); namespace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @param value The namespace to set. * @return This builder for chaining. */ public Builder setNamespace(java.lang.String value) { if (value == null) { throw new NullPointerException(); } namespace_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @return This builder for chaining. */ public Builder clearNamespace() { namespace_ = getDefaultInstance().getNamespace(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Service Directory namespace to register the forwarding rule under. * </pre> * * <code>optional string namespace = 178476379;</code> * * @param value The bytes for namespace to set. * @return This builder for chaining. */ public Builder setNamespaceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); namespace_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object service_ = ""; /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return Whether the service field is set. */ public boolean hasService() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return The service. */ public java.lang.String getService() { java.lang.Object ref = service_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); service_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return The bytes for service. */ public com.google.protobuf.ByteString getServiceBytes() { java.lang.Object ref = service_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); service_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @param value The service to set. * @return This builder for chaining. */ public Builder setService(java.lang.String value) { if (value == null) { throw new NullPointerException(); } service_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @return This builder for chaining. */ public Builder clearService() { service_ = getDefaultInstance().getService(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Service Directory service to register the forwarding rule under. * </pre> * * <code>optional string service = 373540533;</code> * * @param value The bytes for service to set. * @return This builder for chaining. */ public Builder setServiceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); service_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object serviceDirectoryRegion_ = ""; /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return Whether the serviceDirectoryRegion field is set. */ public boolean hasServiceDirectoryRegion() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return The serviceDirectoryRegion. */ public java.lang.String getServiceDirectoryRegion() { java.lang.Object ref = serviceDirectoryRegion_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceDirectoryRegion_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return The bytes for serviceDirectoryRegion. */ public com.google.protobuf.ByteString getServiceDirectoryRegionBytes() { java.lang.Object ref = serviceDirectoryRegion_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); serviceDirectoryRegion_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @param value The serviceDirectoryRegion to set. * @return This builder for chaining. */ public Builder setServiceDirectoryRegion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceDirectoryRegion_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @return This builder for chaining. */ public Builder clearServiceDirectoryRegion() { serviceDirectoryRegion_ = getDefaultInstance().getServiceDirectoryRegion(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * [Optional] Service Directory region to register this global forwarding rule under. Default to "us-central1". Only used for PSC for Google APIs. All PSC for Google APIs forwarding rules on the same network should use the same Service Directory region. * </pre> * * <code>optional string service_directory_region = 74030416;</code> * * @param value The bytes for serviceDirectoryRegion to set. * @return This builder for chaining. */ public Builder setServiceDirectoryRegionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceDirectoryRegion_ = 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.ForwardingRuleServiceDirectoryRegistration) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration) private static final com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration(); } public static com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ForwardingRuleServiceDirectoryRegistration> PARSER = new com.google.protobuf.AbstractParser<ForwardingRuleServiceDirectoryRegistration>() { @java.lang.Override public ForwardingRuleServiceDirectoryRegistration 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<ForwardingRuleServiceDirectoryRegistration> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ForwardingRuleServiceDirectoryRegistration> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.ForwardingRuleServiceDirectoryRegistration getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
38,114
java-aiplatform/google-cloud-aiplatform/src/main/java/com/google/cloud/aiplatform/v1beta1/stub/GrpcEndpointServiceStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.aiplatform.v1beta1.stub; import static com.google.cloud.aiplatform.v1beta1.EndpointServiceClient.ListEndpointsPagedResponse; import static com.google.cloud.aiplatform.v1beta1.EndpointServiceClient.ListLocationsPagedResponse; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.grpc.GrpcCallSettings; import com.google.api.gax.grpc.GrpcStubCallableFactory; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.aiplatform.v1beta1.CreateEndpointOperationMetadata; import com.google.cloud.aiplatform.v1beta1.CreateEndpointRequest; import com.google.cloud.aiplatform.v1beta1.DeleteEndpointRequest; import com.google.cloud.aiplatform.v1beta1.DeleteOperationMetadata; import com.google.cloud.aiplatform.v1beta1.DeployModelOperationMetadata; import com.google.cloud.aiplatform.v1beta1.DeployModelRequest; import com.google.cloud.aiplatform.v1beta1.DeployModelResponse; import com.google.cloud.aiplatform.v1beta1.Endpoint; import com.google.cloud.aiplatform.v1beta1.FetchPublisherModelConfigRequest; import com.google.cloud.aiplatform.v1beta1.GetEndpointRequest; import com.google.cloud.aiplatform.v1beta1.ListEndpointsRequest; import com.google.cloud.aiplatform.v1beta1.ListEndpointsResponse; import com.google.cloud.aiplatform.v1beta1.MutateDeployedModelOperationMetadata; import com.google.cloud.aiplatform.v1beta1.MutateDeployedModelRequest; import com.google.cloud.aiplatform.v1beta1.MutateDeployedModelResponse; import com.google.cloud.aiplatform.v1beta1.PublisherModelConfig; import com.google.cloud.aiplatform.v1beta1.SetPublisherModelConfigOperationMetadata; import com.google.cloud.aiplatform.v1beta1.SetPublisherModelConfigRequest; import com.google.cloud.aiplatform.v1beta1.UndeployModelOperationMetadata; import com.google.cloud.aiplatform.v1beta1.UndeployModelRequest; import com.google.cloud.aiplatform.v1beta1.UndeployModelResponse; import com.google.cloud.aiplatform.v1beta1.UpdateEndpointLongRunningRequest; import com.google.cloud.aiplatform.v1beta1.UpdateEndpointOperationMetadata; import com.google.cloud.aiplatform.v1beta1.UpdateEndpointRequest; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.longrunning.stub.GrpcOperationsStub; import com.google.protobuf.Empty; import io.grpc.MethodDescriptor; import io.grpc.protobuf.ProtoUtils; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * gRPC stub implementation for the EndpointService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @BetaApi @Generated("by gapic-generator-java") public class GrpcEndpointServiceStub extends EndpointServiceStub { private static final MethodDescriptor<CreateEndpointRequest, Operation> createEndpointMethodDescriptor = MethodDescriptor.<CreateEndpointRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/CreateEndpoint") .setRequestMarshaller( ProtoUtils.marshaller(CreateEndpointRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetEndpointRequest, Endpoint> getEndpointMethodDescriptor = MethodDescriptor.<GetEndpointRequest, Endpoint>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/GetEndpoint") .setRequestMarshaller(ProtoUtils.marshaller(GetEndpointRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Endpoint.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListEndpointsRequest, ListEndpointsResponse> listEndpointsMethodDescriptor = MethodDescriptor.<ListEndpointsRequest, ListEndpointsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/ListEndpoints") .setRequestMarshaller( ProtoUtils.marshaller(ListEndpointsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListEndpointsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UpdateEndpointRequest, Endpoint> updateEndpointMethodDescriptor = MethodDescriptor.<UpdateEndpointRequest, Endpoint>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/UpdateEndpoint") .setRequestMarshaller( ProtoUtils.marshaller(UpdateEndpointRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Endpoint.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UpdateEndpointLongRunningRequest, Operation> updateEndpointLongRunningMethodDescriptor = MethodDescriptor.<UpdateEndpointLongRunningRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1beta1.EndpointService/UpdateEndpointLongRunning") .setRequestMarshaller( ProtoUtils.marshaller(UpdateEndpointLongRunningRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteEndpointRequest, Operation> deleteEndpointMethodDescriptor = MethodDescriptor.<DeleteEndpointRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/DeleteEndpoint") .setRequestMarshaller( ProtoUtils.marshaller(DeleteEndpointRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeployModelRequest, Operation> deployModelMethodDescriptor = MethodDescriptor.<DeployModelRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/DeployModel") .setRequestMarshaller(ProtoUtils.marshaller(DeployModelRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UndeployModelRequest, Operation> undeployModelMethodDescriptor = MethodDescriptor.<UndeployModelRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1beta1.EndpointService/UndeployModel") .setRequestMarshaller( ProtoUtils.marshaller(UndeployModelRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<MutateDeployedModelRequest, Operation> mutateDeployedModelMethodDescriptor = MethodDescriptor.<MutateDeployedModelRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1beta1.EndpointService/MutateDeployedModel") .setRequestMarshaller( ProtoUtils.marshaller(MutateDeployedModelRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<SetPublisherModelConfigRequest, Operation> setPublisherModelConfigMethodDescriptor = MethodDescriptor.<SetPublisherModelConfigRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1beta1.EndpointService/SetPublisherModelConfig") .setRequestMarshaller( ProtoUtils.marshaller(SetPublisherModelConfigRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<FetchPublisherModelConfigRequest, PublisherModelConfig> fetchPublisherModelConfigMethodDescriptor = MethodDescriptor.<FetchPublisherModelConfigRequest, PublisherModelConfig>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1beta1.EndpointService/FetchPublisherModelConfig") .setRequestMarshaller( ProtoUtils.marshaller(FetchPublisherModelConfigRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(PublisherModelConfig.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListLocationsRequest, ListLocationsResponse> listLocationsMethodDescriptor = MethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.location.Locations/ListLocations") .setRequestMarshaller( ProtoUtils.marshaller(ListLocationsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListLocationsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor = MethodDescriptor.<GetLocationRequest, Location>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.location.Locations/GetLocation") .setRequestMarshaller(ProtoUtils.marshaller(GetLocationRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Location.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor = MethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") .setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor = MethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") .setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsMethodDescriptor = MethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") .setRequestMarshaller( ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private final UnaryCallable<CreateEndpointRequest, Operation> createEndpointCallable; private final OperationCallable<CreateEndpointRequest, Endpoint, CreateEndpointOperationMetadata> createEndpointOperationCallable; private final UnaryCallable<GetEndpointRequest, Endpoint> getEndpointCallable; private final UnaryCallable<ListEndpointsRequest, ListEndpointsResponse> listEndpointsCallable; private final UnaryCallable<ListEndpointsRequest, ListEndpointsPagedResponse> listEndpointsPagedCallable; private final UnaryCallable<UpdateEndpointRequest, Endpoint> updateEndpointCallable; private final UnaryCallable<UpdateEndpointLongRunningRequest, Operation> updateEndpointLongRunningCallable; private final OperationCallable< UpdateEndpointLongRunningRequest, Endpoint, UpdateEndpointOperationMetadata> updateEndpointLongRunningOperationCallable; private final UnaryCallable<DeleteEndpointRequest, Operation> deleteEndpointCallable; private final OperationCallable<DeleteEndpointRequest, Empty, DeleteOperationMetadata> deleteEndpointOperationCallable; private final UnaryCallable<DeployModelRequest, Operation> deployModelCallable; private final OperationCallable< DeployModelRequest, DeployModelResponse, DeployModelOperationMetadata> deployModelOperationCallable; private final UnaryCallable<UndeployModelRequest, Operation> undeployModelCallable; private final OperationCallable< UndeployModelRequest, UndeployModelResponse, UndeployModelOperationMetadata> undeployModelOperationCallable; private final UnaryCallable<MutateDeployedModelRequest, Operation> mutateDeployedModelCallable; private final OperationCallable< MutateDeployedModelRequest, MutateDeployedModelResponse, MutateDeployedModelOperationMetadata> mutateDeployedModelOperationCallable; private final UnaryCallable<SetPublisherModelConfigRequest, Operation> setPublisherModelConfigCallable; private final OperationCallable< SetPublisherModelConfigRequest, PublisherModelConfig, SetPublisherModelConfigOperationMetadata> setPublisherModelConfigOperationCallable; private final UnaryCallable<FetchPublisherModelConfigRequest, PublisherModelConfig> fetchPublisherModelConfigCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable; private final UnaryCallable<GetLocationRequest, Location> getLocationCallable; private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable; private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable; private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final GrpcOperationsStub operationsStub; private final GrpcStubCallableFactory callableFactory; public static final GrpcEndpointServiceStub create(EndpointServiceStubSettings settings) throws IOException { return new GrpcEndpointServiceStub(settings, ClientContext.create(settings)); } public static final GrpcEndpointServiceStub create(ClientContext clientContext) throws IOException { return new GrpcEndpointServiceStub( EndpointServiceStubSettings.newBuilder().build(), clientContext); } public static final GrpcEndpointServiceStub create( ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { return new GrpcEndpointServiceStub( EndpointServiceStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of GrpcEndpointServiceStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected GrpcEndpointServiceStub( EndpointServiceStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new GrpcEndpointServiceCallableFactory()); } /** * Constructs an instance of GrpcEndpointServiceStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected GrpcEndpointServiceStub( EndpointServiceStubSettings settings, ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); GrpcCallSettings<CreateEndpointRequest, Operation> createEndpointTransportSettings = GrpcCallSettings.<CreateEndpointRequest, Operation>newBuilder() .setMethodDescriptor(createEndpointMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<GetEndpointRequest, Endpoint> getEndpointTransportSettings = GrpcCallSettings.<GetEndpointRequest, Endpoint>newBuilder() .setMethodDescriptor(getEndpointMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListEndpointsRequest, ListEndpointsResponse> listEndpointsTransportSettings = GrpcCallSettings.<ListEndpointsRequest, ListEndpointsResponse>newBuilder() .setMethodDescriptor(listEndpointsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<UpdateEndpointRequest, Endpoint> updateEndpointTransportSettings = GrpcCallSettings.<UpdateEndpointRequest, Endpoint>newBuilder() .setMethodDescriptor(updateEndpointMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("endpoint.name", String.valueOf(request.getEndpoint().getName())); return builder.build(); }) .build(); GrpcCallSettings<UpdateEndpointLongRunningRequest, Operation> updateEndpointLongRunningTransportSettings = GrpcCallSettings.<UpdateEndpointLongRunningRequest, Operation>newBuilder() .setMethodDescriptor(updateEndpointLongRunningMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("endpoint.name", String.valueOf(request.getEndpoint().getName())); return builder.build(); }) .build(); GrpcCallSettings<DeleteEndpointRequest, Operation> deleteEndpointTransportSettings = GrpcCallSettings.<DeleteEndpointRequest, Operation>newBuilder() .setMethodDescriptor(deleteEndpointMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<DeployModelRequest, Operation> deployModelTransportSettings = GrpcCallSettings.<DeployModelRequest, Operation>newBuilder() .setMethodDescriptor(deployModelMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("endpoint", String.valueOf(request.getEndpoint())); return builder.build(); }) .build(); GrpcCallSettings<UndeployModelRequest, Operation> undeployModelTransportSettings = GrpcCallSettings.<UndeployModelRequest, Operation>newBuilder() .setMethodDescriptor(undeployModelMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("endpoint", String.valueOf(request.getEndpoint())); return builder.build(); }) .build(); GrpcCallSettings<MutateDeployedModelRequest, Operation> mutateDeployedModelTransportSettings = GrpcCallSettings.<MutateDeployedModelRequest, Operation>newBuilder() .setMethodDescriptor(mutateDeployedModelMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("endpoint", String.valueOf(request.getEndpoint())); return builder.build(); }) .build(); GrpcCallSettings<SetPublisherModelConfigRequest, Operation> setPublisherModelConfigTransportSettings = GrpcCallSettings.<SetPublisherModelConfigRequest, Operation>newBuilder() .setMethodDescriptor(setPublisherModelConfigMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<FetchPublisherModelConfigRequest, PublisherModelConfig> fetchPublisherModelConfigTransportSettings = GrpcCallSettings.<FetchPublisherModelConfigRequest, PublisherModelConfig>newBuilder() .setMethodDescriptor(fetchPublisherModelConfigMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings = GrpcCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setMethodDescriptor(listLocationsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<GetLocationRequest, Location> getLocationTransportSettings = GrpcCallSettings.<GetLocationRequest, Location>newBuilder() .setMethodDescriptor(getLocationMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings = GrpcCallSettings.<SetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(setIamPolicyMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); GrpcCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings = GrpcCallSettings.<GetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(getIamPolicyMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); GrpcCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsTransportSettings = GrpcCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.createEndpointCallable = callableFactory.createUnaryCallable( createEndpointTransportSettings, settings.createEndpointSettings(), clientContext); this.createEndpointOperationCallable = callableFactory.createOperationCallable( createEndpointTransportSettings, settings.createEndpointOperationSettings(), clientContext, operationsStub); this.getEndpointCallable = callableFactory.createUnaryCallable( getEndpointTransportSettings, settings.getEndpointSettings(), clientContext); this.listEndpointsCallable = callableFactory.createUnaryCallable( listEndpointsTransportSettings, settings.listEndpointsSettings(), clientContext); this.listEndpointsPagedCallable = callableFactory.createPagedCallable( listEndpointsTransportSettings, settings.listEndpointsSettings(), clientContext); this.updateEndpointCallable = callableFactory.createUnaryCallable( updateEndpointTransportSettings, settings.updateEndpointSettings(), clientContext); this.updateEndpointLongRunningCallable = callableFactory.createUnaryCallable( updateEndpointLongRunningTransportSettings, settings.updateEndpointLongRunningSettings(), clientContext); this.updateEndpointLongRunningOperationCallable = callableFactory.createOperationCallable( updateEndpointLongRunningTransportSettings, settings.updateEndpointLongRunningOperationSettings(), clientContext, operationsStub); this.deleteEndpointCallable = callableFactory.createUnaryCallable( deleteEndpointTransportSettings, settings.deleteEndpointSettings(), clientContext); this.deleteEndpointOperationCallable = callableFactory.createOperationCallable( deleteEndpointTransportSettings, settings.deleteEndpointOperationSettings(), clientContext, operationsStub); this.deployModelCallable = callableFactory.createUnaryCallable( deployModelTransportSettings, settings.deployModelSettings(), clientContext); this.deployModelOperationCallable = callableFactory.createOperationCallable( deployModelTransportSettings, settings.deployModelOperationSettings(), clientContext, operationsStub); this.undeployModelCallable = callableFactory.createUnaryCallable( undeployModelTransportSettings, settings.undeployModelSettings(), clientContext); this.undeployModelOperationCallable = callableFactory.createOperationCallable( undeployModelTransportSettings, settings.undeployModelOperationSettings(), clientContext, operationsStub); this.mutateDeployedModelCallable = callableFactory.createUnaryCallable( mutateDeployedModelTransportSettings, settings.mutateDeployedModelSettings(), clientContext); this.mutateDeployedModelOperationCallable = callableFactory.createOperationCallable( mutateDeployedModelTransportSettings, settings.mutateDeployedModelOperationSettings(), clientContext, operationsStub); this.setPublisherModelConfigCallable = callableFactory.createUnaryCallable( setPublisherModelConfigTransportSettings, settings.setPublisherModelConfigSettings(), clientContext); this.setPublisherModelConfigOperationCallable = callableFactory.createOperationCallable( setPublisherModelConfigTransportSettings, settings.setPublisherModelConfigOperationSettings(), clientContext, operationsStub); this.fetchPublisherModelConfigCallable = callableFactory.createUnaryCallable( fetchPublisherModelConfigTransportSettings, settings.fetchPublisherModelConfigSettings(), clientContext); this.listLocationsCallable = callableFactory.createUnaryCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.listLocationsPagedCallable = callableFactory.createPagedCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.getLocationCallable = callableFactory.createUnaryCallable( getLocationTransportSettings, settings.getLocationSettings(), clientContext); this.setIamPolicyCallable = callableFactory.createUnaryCallable( setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); this.getIamPolicyCallable = callableFactory.createUnaryCallable( getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); this.testIamPermissionsCallable = callableFactory.createUnaryCallable( testIamPermissionsTransportSettings, settings.testIamPermissionsSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } public GrpcOperationsStub getOperationsStub() { return operationsStub; } @Override public UnaryCallable<CreateEndpointRequest, Operation> createEndpointCallable() { return createEndpointCallable; } @Override public OperationCallable<CreateEndpointRequest, Endpoint, CreateEndpointOperationMetadata> createEndpointOperationCallable() { return createEndpointOperationCallable; } @Override public UnaryCallable<GetEndpointRequest, Endpoint> getEndpointCallable() { return getEndpointCallable; } @Override public UnaryCallable<ListEndpointsRequest, ListEndpointsResponse> listEndpointsCallable() { return listEndpointsCallable; } @Override public UnaryCallable<ListEndpointsRequest, ListEndpointsPagedResponse> listEndpointsPagedCallable() { return listEndpointsPagedCallable; } @Override public UnaryCallable<UpdateEndpointRequest, Endpoint> updateEndpointCallable() { return updateEndpointCallable; } @Override public UnaryCallable<UpdateEndpointLongRunningRequest, Operation> updateEndpointLongRunningCallable() { return updateEndpointLongRunningCallable; } @Override public OperationCallable< UpdateEndpointLongRunningRequest, Endpoint, UpdateEndpointOperationMetadata> updateEndpointLongRunningOperationCallable() { return updateEndpointLongRunningOperationCallable; } @Override public UnaryCallable<DeleteEndpointRequest, Operation> deleteEndpointCallable() { return deleteEndpointCallable; } @Override public OperationCallable<DeleteEndpointRequest, Empty, DeleteOperationMetadata> deleteEndpointOperationCallable() { return deleteEndpointOperationCallable; } @Override public UnaryCallable<DeployModelRequest, Operation> deployModelCallable() { return deployModelCallable; } @Override public OperationCallable<DeployModelRequest, DeployModelResponse, DeployModelOperationMetadata> deployModelOperationCallable() { return deployModelOperationCallable; } @Override public UnaryCallable<UndeployModelRequest, Operation> undeployModelCallable() { return undeployModelCallable; } @Override public OperationCallable< UndeployModelRequest, UndeployModelResponse, UndeployModelOperationMetadata> undeployModelOperationCallable() { return undeployModelOperationCallable; } @Override public UnaryCallable<MutateDeployedModelRequest, Operation> mutateDeployedModelCallable() { return mutateDeployedModelCallable; } @Override public OperationCallable< MutateDeployedModelRequest, MutateDeployedModelResponse, MutateDeployedModelOperationMetadata> mutateDeployedModelOperationCallable() { return mutateDeployedModelOperationCallable; } @Override public UnaryCallable<SetPublisherModelConfigRequest, Operation> setPublisherModelConfigCallable() { return setPublisherModelConfigCallable; } @Override public OperationCallable< SetPublisherModelConfigRequest, PublisherModelConfig, SetPublisherModelConfigOperationMetadata> setPublisherModelConfigOperationCallable() { return setPublisherModelConfigOperationCallable; } @Override public UnaryCallable<FetchPublisherModelConfigRequest, PublisherModelConfig> fetchPublisherModelConfigCallable() { return fetchPublisherModelConfigCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return listLocationsCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return listLocationsPagedCallable; } @Override public UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return getLocationCallable; } @Override public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return setIamPolicyCallable; } @Override public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return getIamPolicyCallable; } @Override public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable() { return testIamPermissionsCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
apache/parquet-java
37,555
parquet-hadoop/src/test/java/org/apache/parquet/filter2/dictionarylevel/DictionaryFilterTest.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.parquet.filter2.dictionarylevel; import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_1_0; import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_2_0; import static org.apache.parquet.filter2.dictionarylevel.DictionaryFilter.canDrop; import static org.apache.parquet.filter2.predicate.FilterApi.and; import static org.apache.parquet.filter2.predicate.FilterApi.binaryColumn; import static org.apache.parquet.filter2.predicate.FilterApi.contains; import static org.apache.parquet.filter2.predicate.FilterApi.doubleColumn; import static org.apache.parquet.filter2.predicate.FilterApi.eq; import static org.apache.parquet.filter2.predicate.FilterApi.floatColumn; import static org.apache.parquet.filter2.predicate.FilterApi.gt; import static org.apache.parquet.filter2.predicate.FilterApi.gtEq; import static org.apache.parquet.filter2.predicate.FilterApi.in; import static org.apache.parquet.filter2.predicate.FilterApi.intColumn; import static org.apache.parquet.filter2.predicate.FilterApi.longColumn; import static org.apache.parquet.filter2.predicate.FilterApi.lt; import static org.apache.parquet.filter2.predicate.FilterApi.ltEq; import static org.apache.parquet.filter2.predicate.FilterApi.not; import static org.apache.parquet.filter2.predicate.FilterApi.notEq; import static org.apache.parquet.filter2.predicate.FilterApi.notIn; import static org.apache.parquet.filter2.predicate.FilterApi.or; import static org.apache.parquet.filter2.predicate.FilterApi.userDefined; import static org.apache.parquet.hadoop.metadata.CompressionCodecName.GZIP; import static org.apache.parquet.schema.MessageTypeParser.parseMessageType; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.parquet.FixedBinaryTestUtils; import org.apache.parquet.column.Encoding; import org.apache.parquet.column.EncodingStats; import org.apache.parquet.column.ParquetProperties.WriterVersion; import org.apache.parquet.column.page.DictionaryPageReadStore; import org.apache.parquet.example.data.Group; import org.apache.parquet.example.data.simple.SimpleGroupFactory; import org.apache.parquet.filter2.predicate.FilterPredicate; import org.apache.parquet.filter2.predicate.LogicalInverseRewriter; import org.apache.parquet.filter2.predicate.Operators; import org.apache.parquet.filter2.predicate.Operators.BinaryColumn; import org.apache.parquet.filter2.predicate.Operators.DoubleColumn; import org.apache.parquet.filter2.predicate.Operators.FloatColumn; import org.apache.parquet.filter2.predicate.Operators.IntColumn; import org.apache.parquet.filter2.predicate.Operators.LongColumn; import org.apache.parquet.filter2.predicate.Statistics; import org.apache.parquet.filter2.predicate.UserDefinedPredicate; import org.apache.parquet.hadoop.ParquetFileReader; import org.apache.parquet.hadoop.ParquetWriter; import org.apache.parquet.hadoop.example.ExampleParquetWriter; import org.apache.parquet.hadoop.example.GroupWriteSupport; import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData; import org.apache.parquet.hadoop.metadata.ParquetMetadata; import org.apache.parquet.io.api.Binary; import org.apache.parquet.schema.MessageType; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class DictionaryFilterTest { private static final int nElements = 1000; private static final Configuration conf = new Configuration(); private static final Path FILE_V1 = new Path("target/test/TestDictionaryFilter/testParquetFileV1.parquet"); private static final Path FILE_V2 = new Path("target/test/TestDictionaryFilter/testParquetFileV2.parquet"); private static final MessageType schema = parseMessageType("message test { " + "required binary binary_field; " + "required binary single_value_field; " + "optional binary optional_single_value_field; " + "optional int32 optional_single_value_int32_field;" + "required fixed_len_byte_array(17) fixed_field (DECIMAL(40,4)); " + "required int32 int32_field; " + "required int64 int64_field; " + "required double double_field; " + "required float float_field; " + "required int32 plain_int32_field; " + "required binary fallback_binary_field; " + "required int96 int96_field; " + "repeated binary repeated_binary_field;" + "} "); private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; private static final int[] intValues = new int[] { -100, 302, 3333333, 7654321, 1234567, -2000, -77775, 0, 75, 22223, 77, 22221, -444443, 205, 12, 44444, 889, 66665, -777889, -7, 52, 33, -257, 1111, 775, 26 }; private static final long[] longValues = new long[] { -100L, 302L, 3333333L, 7654321L, 1234567L, -2000L, -77775L, 0L, 75L, 22223L, 77L, 22221L, -444443L, 205L, 12L, 44444L, 889L, 66665L, -777889L, -7L, 52L, 33L, -257L, 1111L, 775L, 26L }; private static final Binary[] DECIMAL_VALUES = new Binary[] { toBinary("-9999999999999999999999999999999999999999", 17), toBinary("-9999999999999999999999999999999999999998", 17), toBinary(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), 17), toBinary(BigInteger.valueOf(Long.MIN_VALUE), 17), toBinary(BigInteger.valueOf(Long.MIN_VALUE).add(BigInteger.ONE), 17), toBinary("-1", 17), toBinary("0", 17), toBinary(BigInteger.valueOf(Long.MAX_VALUE).subtract(BigInteger.ONE), 17), toBinary(BigInteger.valueOf(Long.MAX_VALUE), 17), toBinary(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE), 17), toBinary("999999999999999999999999999999999999999", 17), toBinary("9999999999999999999999999999999999999998", 17), toBinary("9999999999999999999999999999999999999999", 17) }; private static final Binary[] INT96_VALUES = new Binary[] { toBinary("-9999999999999999999999999999", 12), toBinary("-9999999999999999999999999998", 12), toBinary("-1234567890", 12), toBinary("-1", 12), toBinary("-0", 12), toBinary("1", 12), toBinary("1234567890", 12), toBinary("-9999999999999999999999999998", 12), toBinary("9999999999999999999999999999", 12) }; private static Binary toBinary(String decimalWithoutScale, int byteCount) { return toBinary(new BigInteger(decimalWithoutScale), byteCount); } private static Binary toBinary(BigInteger decimalWithoutScale, int byteCount) { return FixedBinaryTestUtils.getFixedBinary(byteCount, decimalWithoutScale); } private static void writeData(SimpleGroupFactory f, ParquetWriter<Group> writer) throws IOException { for (int i = 0; i < nElements; i++) { int index = i % ALPHABET.length(); Group group = f.newGroup() .append("binary_field", ALPHABET.substring(index, index + 1)) .append("single_value_field", "sharp") .append("fixed_field", DECIMAL_VALUES[i % DECIMAL_VALUES.length]) .append("int32_field", intValues[i % intValues.length]) .append("int64_field", longValues[i % longValues.length]) .append("double_field", toDouble(intValues[i % intValues.length])) .append("float_field", toFloat(intValues[i % intValues.length])) .append("plain_int32_field", i) .append( "fallback_binary_field", i < (nElements / 2) ? ALPHABET.substring(index, index + 1) : UUID.randomUUID().toString()) .append("int96_field", INT96_VALUES[i % INT96_VALUES.length]) .append("repeated_binary_field", ALPHABET.substring(index, index + 1)); if (index + 1 < 26) { group = group.append("repeated_binary_field", ALPHABET.substring(index + 1, index + 2)); } if (index + 2 < 26) { group = group.append("repeated_binary_field", ALPHABET.substring(index + 2, index + 3)); } // 10% of the time, leave the field null if (index % 10 > 0) { group.append("optional_single_value_field", "sharp"); group.append("optional_single_value_int32_field", 42); } writer.write(group); } writer.close(); } @BeforeClass public static void prepareFile() throws IOException { cleanup(); prepareFile(PARQUET_1_0, FILE_V1); prepareFile(PARQUET_2_0, FILE_V2); } private static void prepareFile(WriterVersion version, Path file) throws IOException { GroupWriteSupport.setSchema(schema, conf); SimpleGroupFactory f = new SimpleGroupFactory(schema); ParquetWriter<Group> writer = ExampleParquetWriter.builder(file) .withWriterVersion(version) .withCompressionCodec(GZIP) .withRowGroupSize(1024 * 1024) .withPageSize(1024) .enableDictionaryEncoding() .withDictionaryPageSize(2 * 1024) .withConf(conf) .build(); writeData(f, writer); } @AfterClass public static void cleanup() throws IOException { deleteFile(FILE_V1); deleteFile(FILE_V2); } private static void deleteFile(Path file) throws IOException { FileSystem fs = file.getFileSystem(conf); if (fs.exists(file)) { fs.delete(file, true); } } @Parameters public static Object[] params() { return new Object[] {PARQUET_1_0, PARQUET_2_0}; } List<ColumnChunkMetaData> ccmd; ParquetFileReader reader; DictionaryPageReadStore dictionaries; private Path file; private WriterVersion version; public DictionaryFilterTest(WriterVersion version) { this.version = version; switch (version) { case PARQUET_1_0: file = FILE_V1; break; case PARQUET_2_0: file = FILE_V2; break; } } @Before public void setUp() throws Exception { reader = ParquetFileReader.open(conf, file); ParquetMetadata meta = reader.getFooter(); ccmd = meta.getBlocks().get(0).getColumns(); dictionaries = reader.getDictionaryReader(meta.getBlocks().get(0)); } @After public void tearDown() throws Exception { reader.close(); } @Test public void testDictionaryEncodedColumns() throws Exception { switch (version) { case PARQUET_1_0: testDictionaryEncodedColumnsV1(); break; case PARQUET_2_0: testDictionaryEncodedColumnsV2(); break; } } @SuppressWarnings("deprecation") private void testDictionaryEncodedColumnsV1() throws Exception { Set<String> dictionaryEncodedColumns = new HashSet<String>(Arrays.asList( "binary_field", "single_value_field", "optional_single_value_field", "optional_single_value_int32_field", "int32_field", "int64_field", "double_field", "float_field", "int96_field", "repeated_binary_field")); for (ColumnChunkMetaData column : ccmd) { String name = column.getPath().toDotString(); if (dictionaryEncodedColumns.contains(name)) { assertTrue( "Column should be dictionary encoded: " + name, column.getEncodings().contains(Encoding.PLAIN_DICTIONARY)); assertFalse( "Column should not have plain data pages" + name, column.getEncodings().contains(Encoding.PLAIN)); } else { assertTrue( "Column should have plain encoding: " + name, column.getEncodings().contains(Encoding.PLAIN)); if (name.startsWith("fallback")) { assertTrue( "Column should have some dictionary encoding: " + name, column.getEncodings().contains(Encoding.PLAIN_DICTIONARY)); } else { assertFalse( "Column should have no dictionary encoding: " + name, column.getEncodings().contains(Encoding.PLAIN_DICTIONARY)); } } } } private void testDictionaryEncodedColumnsV2() throws Exception { Set<String> dictionaryEncodedColumns = new HashSet<String>(Arrays.asList( "binary_field", "single_value_field", "optional_single_value_field", "optional_single_value_int32_field", "fixed_field", "int32_field", "int64_field", "double_field", "float_field", "int96_field", "repeated_binary_field")); for (ColumnChunkMetaData column : ccmd) { EncodingStats encStats = column.getEncodingStats(); String name = column.getPath().toDotString(); if (dictionaryEncodedColumns.contains(name)) { assertTrue("Column should have dictionary pages: " + name, encStats.hasDictionaryPages()); assertTrue( "Column should have dictionary encoded pages: " + name, encStats.hasDictionaryEncodedPages()); assertFalse( "Column should not have non-dictionary encoded pages: " + name, encStats.hasNonDictionaryEncodedPages()); } else { assertTrue( "Column should have non-dictionary encoded pages: " + name, encStats.hasNonDictionaryEncodedPages()); if (name.startsWith("fallback")) { assertTrue("Column should have dictionary pages: " + name, encStats.hasDictionaryPages()); assertTrue( "Column should have dictionary encoded pages: " + name, encStats.hasDictionaryEncodedPages()); } else { assertFalse("Column should not have dictionary pages: " + name, encStats.hasDictionaryPages()); assertFalse( "Column should not have dictionary encoded pages: " + name, encStats.hasDictionaryEncodedPages()); } } } } @Test public void testEqBinary() throws Exception { BinaryColumn b = binaryColumn("binary_field"); FilterPredicate pred = eq(b, Binary.fromString("c")); assertFalse("Should not drop block for lower case letters", canDrop(pred, ccmd, dictionaries)); assertTrue( "Should drop block for upper case letters", canDrop(eq(b, Binary.fromString("A")), ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(eq(b, null), ccmd, dictionaries)); } @Test public void testEqFixed() throws Exception { BinaryColumn b = binaryColumn("fixed_field"); // Only V2 supports dictionary encoding for FIXED_LEN_BYTE_ARRAY values if (version == PARQUET_2_0) { assertTrue("Should drop block for -2", canDrop(eq(b, toBinary("-2", 17)), ccmd, dictionaries)); } assertFalse("Should not drop block for -1", canDrop(eq(b, toBinary("-1", 17)), ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(eq(b, null), ccmd, dictionaries)); } @Test public void testEqInt96() throws Exception { BinaryColumn b = binaryColumn("int96_field"); // INT96 ordering is undefined => no filtering shall be done assertFalse("Should not drop block for -2", canDrop(eq(b, toBinary("-2", 12)), ccmd, dictionaries)); assertFalse("Should not drop block for -1", canDrop(eq(b, toBinary("-1", 12)), ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(eq(b, null), ccmd, dictionaries)); } @Test public void testNotEqBinary() throws Exception { BinaryColumn sharp = binaryColumn("single_value_field"); BinaryColumn sharpAndNull = binaryColumn("optional_single_value_field"); BinaryColumn b = binaryColumn("binary_field"); assertTrue( "Should drop block with only the excluded value", canDrop(notEq(sharp, Binary.fromString("sharp")), ccmd, dictionaries)); assertFalse( "Should not drop block with any other value", canDrop(notEq(sharp, Binary.fromString("applause")), ccmd, dictionaries)); assertFalse( "Should not drop block with only the excluded value and null", canDrop(notEq(sharpAndNull, Binary.fromString("sharp")), ccmd, dictionaries)); assertFalse( "Should not drop block with any other value", canDrop(notEq(sharpAndNull, Binary.fromString("applause")), ccmd, dictionaries)); assertFalse( "Should not drop block with a known value", canDrop(notEq(b, Binary.fromString("x")), ccmd, dictionaries)); assertFalse( "Should not drop block with a known value", canDrop(notEq(b, Binary.fromString("B")), ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(notEq(b, null), ccmd, dictionaries)); } @Test public void testLtInt() throws Exception { IntColumn i32 = intColumn("int32_field"); int lowest = Integer.MAX_VALUE; for (int value : intValues) { lowest = Math.min(lowest, value); } assertTrue("Should drop: < lowest value", canDrop(lt(i32, lowest), ccmd, dictionaries)); assertFalse("Should not drop: < (lowest value + 1)", canDrop(lt(i32, lowest + 1), ccmd, dictionaries)); assertFalse( "Should not drop: contains matching values", canDrop(lt(i32, Integer.MAX_VALUE), ccmd, dictionaries)); } @Test public void testLtFixed() throws Exception { BinaryColumn fixed = binaryColumn("fixed_field"); // Only V2 supports dictionary encoding for FIXED_LEN_BYTE_ARRAY values if (version == PARQUET_2_0) { assertTrue("Should drop: < lowest value", canDrop(lt(fixed, DECIMAL_VALUES[0]), ccmd, dictionaries)); } assertFalse("Should not drop: < 2nd lowest value", canDrop(lt(fixed, DECIMAL_VALUES[1]), ccmd, dictionaries)); } @Test public void testLtEqLong() throws Exception { LongColumn i64 = longColumn("int64_field"); long lowest = Long.MAX_VALUE; for (long value : longValues) { lowest = Math.min(lowest, value); } assertTrue("Should drop: <= lowest - 1", canDrop(ltEq(i64, lowest - 1), ccmd, dictionaries)); assertFalse("Should not drop: <= lowest", canDrop(ltEq(i64, lowest), ccmd, dictionaries)); assertFalse( "Should not drop: contains matching values", canDrop(ltEq(i64, Long.MAX_VALUE), ccmd, dictionaries)); } @Test public void testGtFloat() throws Exception { FloatColumn f = floatColumn("float_field"); float highest = Float.MIN_VALUE; for (int value : intValues) { highest = Math.max(highest, toFloat(value)); } assertTrue("Should drop: > highest value", canDrop(gt(f, highest), ccmd, dictionaries)); assertFalse("Should not drop: > (highest value - 1.0)", canDrop(gt(f, highest - 1.0f), ccmd, dictionaries)); assertFalse("Should not drop: contains matching values", canDrop(gt(f, Float.MIN_VALUE), ccmd, dictionaries)); } @Test public void testGtEqDouble() throws Exception { DoubleColumn d = doubleColumn("double_field"); double highest = Double.MIN_VALUE; for (int value : intValues) { highest = Math.max(highest, toDouble(value)); } assertTrue("Should drop: >= highest + 0.00000001", canDrop(gtEq(d, highest + 0.00000001), ccmd, dictionaries)); assertFalse("Should not drop: >= highest", canDrop(gtEq(d, highest), ccmd, dictionaries)); assertFalse( "Should not drop: contains matching values", canDrop(gtEq(d, Double.MIN_VALUE), ccmd, dictionaries)); } @Test public void testInBinary() throws Exception { BinaryColumn b = binaryColumn("binary_field"); Set<Binary> set1 = new HashSet<>(); set1.add(Binary.fromString("F")); set1.add(Binary.fromString("C")); set1.add(Binary.fromString("h")); set1.add(Binary.fromString("E")); FilterPredicate predIn1 = in(b, set1); FilterPredicate predNotIn1 = notIn(b, set1); assertFalse("Should not drop block", canDrop(predIn1, ccmd, dictionaries)); assertFalse("Should not drop block", canDrop(predNotIn1, ccmd, dictionaries)); Set<Binary> set2 = new HashSet<>(); for (int i = 0; i < 26; i++) { set2.add(Binary.fromString(Character.toString((char) (i + 97)))); } set2.add(Binary.fromString("A")); FilterPredicate predIn2 = in(b, set2); FilterPredicate predNotIn2 = notIn(b, set2); assertFalse("Should not drop block", canDrop(predIn2, ccmd, dictionaries)); assertTrue("Should not drop block", canDrop(predNotIn2, ccmd, dictionaries)); Set<Binary> set3 = new HashSet<>(); set3.add(Binary.fromString("F")); set3.add(Binary.fromString("C")); set3.add(Binary.fromString("A")); set3.add(Binary.fromString("E")); FilterPredicate predIn3 = in(b, set3); FilterPredicate predNotIn3 = notIn(b, set3); assertTrue("Should drop block", canDrop(predIn3, ccmd, dictionaries)); assertFalse("Should not drop block", canDrop(predNotIn3, ccmd, dictionaries)); Set<Binary> set4 = new HashSet<>(); set4.add(null); FilterPredicate predIn4 = in(b, set4); FilterPredicate predNotIn4 = notIn(b, set4); assertFalse("Should not drop block for null", canDrop(predIn4, ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(predNotIn4, ccmd, dictionaries)); BinaryColumn sharpAndNull = binaryColumn("optional_single_value_field"); // Test the case that all non-null values are in the set but the column may have nulls and the set has no nulls. Set<Binary> set5 = new HashSet<>(); set5.add(Binary.fromString("sharp")); FilterPredicate predNotIn5 = notIn(sharpAndNull, set5); FilterPredicate predIn5 = in(sharpAndNull, set5); assertFalse("Should not drop block", canDrop(predNotIn5, ccmd, dictionaries)); assertFalse("Should not drop block", canDrop(predIn5, ccmd, dictionaries)); } @Test public void testInFixed() throws Exception { BinaryColumn b = binaryColumn("fixed_field"); // Only V2 supports dictionary encoding for FIXED_LEN_BYTE_ARRAY values if (version == PARQUET_2_0) { Set<Binary> set1 = new HashSet<>(); set1.add(toBinary("-2", 17)); set1.add(toBinary("-22", 17)); set1.add(toBinary("12345", 17)); FilterPredicate predIn1 = in(b, set1); FilterPredicate predNotIn1 = notIn(b, set1); assertTrue("Should drop block for in (-2, -22, 12345)", canDrop(predIn1, ccmd, dictionaries)); assertFalse("Should not drop block for notIn (-2, -22, 12345)", canDrop(predNotIn1, ccmd, dictionaries)); Set<Binary> set2 = new HashSet<>(); set2.add(toBinary("-1", 17)); set2.add(toBinary("0", 17)); set2.add(toBinary("12345", 17)); assertFalse("Should not drop block for in (-1, 0, 12345)", canDrop(in(b, set2), ccmd, dictionaries)); assertFalse("Should not drop block for in (-1, 0, 12345)", canDrop(notIn(b, set2), ccmd, dictionaries)); } Set<Binary> set3 = new HashSet<>(); set3.add(null); FilterPredicate predIn3 = in(b, set3); FilterPredicate predNotIn3 = notIn(b, set3); assertFalse("Should not drop block for null", canDrop(predIn3, ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(predNotIn3, ccmd, dictionaries)); } @Test public void testInInt96() throws Exception { // INT96 ordering is undefined => no filtering shall be done BinaryColumn b = binaryColumn("int96_field"); Set<Binary> set1 = new HashSet<>(); set1.add(toBinary("-2", 12)); set1.add(toBinary("-0", 12)); set1.add(toBinary("12345", 12)); FilterPredicate predIn1 = in(b, set1); FilterPredicate predNotIn1 = notIn(b, set1); assertFalse("Should not drop block for in (-2, -0, 12345)", canDrop(predIn1, ccmd, dictionaries)); assertFalse("Should not drop block for notIn (-2, -0, 12345)", canDrop(predNotIn1, ccmd, dictionaries)); Set<Binary> set2 = new HashSet<>(); set2.add(toBinary("-2", 17)); set2.add(toBinary("12345", 17)); set2.add(toBinary("-789", 17)); FilterPredicate predIn2 = in(b, set2); FilterPredicate predNotIn2 = notIn(b, set2); assertFalse("Should not drop block for in (-2, 12345, -789)", canDrop(predIn2, ccmd, dictionaries)); assertFalse("Should not drop block for notIn (-2, 12345, -789)", canDrop(predNotIn2, ccmd, dictionaries)); Set<Binary> set3 = new HashSet<>(); set3.add(null); FilterPredicate predIn3 = in(b, set3); FilterPredicate predNotIn3 = notIn(b, set3); assertFalse("Should not drop block for null", canDrop(predIn3, ccmd, dictionaries)); assertFalse("Should not drop block for null", canDrop(predNotIn3, ccmd, dictionaries)); } @Test public void testAnd() throws Exception { BinaryColumn col = binaryColumn("binary_field"); // both evaluate to false (no upper-case letters are in the dictionary) FilterPredicate B = eq(col, Binary.fromString("B")); FilterPredicate C = eq(col, Binary.fromString("C")); // both evaluate to true (all lower-case letters are in the dictionary) FilterPredicate x = eq(col, Binary.fromString("x")); FilterPredicate y = eq(col, Binary.fromString("y")); assertTrue("Should drop when either predicate must be false", canDrop(and(B, y), ccmd, dictionaries)); assertTrue("Should drop when either predicate must be false", canDrop(and(x, C), ccmd, dictionaries)); assertTrue("Should drop when either predicate must be false", canDrop(and(B, C), ccmd, dictionaries)); assertFalse("Should not drop when either predicate could be true", canDrop(and(x, y), ccmd, dictionaries)); } @Test public void testOr() throws Exception { BinaryColumn col = binaryColumn("binary_field"); // both evaluate to false (no upper-case letters are in the dictionary) FilterPredicate B = eq(col, Binary.fromString("B")); FilterPredicate C = eq(col, Binary.fromString("C")); // both evaluate to true (all lower-case letters are in the dictionary) FilterPredicate x = eq(col, Binary.fromString("x")); FilterPredicate y = eq(col, Binary.fromString("y")); assertFalse("Should not drop when one predicate could be true", canDrop(or(B, y), ccmd, dictionaries)); assertFalse("Should not drop when one predicate could be true", canDrop(or(x, C), ccmd, dictionaries)); assertTrue("Should drop when both predicates must be false", canDrop(or(B, C), ccmd, dictionaries)); assertFalse("Should not drop when one predicate could be true", canDrop(or(x, y), ccmd, dictionaries)); } @Test public void testUdp() throws Exception { InInt32UDP dropabble = new InInt32UDP(ImmutableSet.of(42)); InInt32UDP undroppable = new InInt32UDP(ImmutableSet.of(205)); assertTrue( "Should drop block for non-matching UDP", canDrop(userDefined(intColumn("int32_field"), dropabble), ccmd, dictionaries)); assertFalse( "Should not drop block for matching UDP", canDrop(userDefined(intColumn("int32_field"), undroppable), ccmd, dictionaries)); } @Test public void testNullAcceptingUdp() throws Exception { InInt32UDP drop42DenyNulls = new InInt32UDP(Sets.newHashSet(205)); InInt32UDP drop42AcceptNulls = new InInt32UDP(Sets.newHashSet(null, 205)); // A column with value 42 and 10% nulls IntColumn intColumnWithNulls = intColumn("optional_single_value_int32_field"); assertTrue("Should drop block", canDrop(userDefined(intColumnWithNulls, drop42DenyNulls), ccmd, dictionaries)); assertFalse( "Should not drop block for null accepting udp", canDrop(userDefined(intColumnWithNulls, drop42AcceptNulls), ccmd, dictionaries)); } @Test public void testInverseUdp() throws Exception { InInt32UDP droppable = new InInt32UDP(ImmutableSet.of(42)); InInt32UDP undroppable = new InInt32UDP(ImmutableSet.of(205)); Set<Integer> allValues = ImmutableSet.copyOf(Ints.asList(intValues)); InInt32UDP completeMatch = new InInt32UDP(allValues); FilterPredicate inverse = LogicalInverseRewriter.rewrite(not(userDefined(intColumn("int32_field"), droppable))); FilterPredicate inverse1 = LogicalInverseRewriter.rewrite(not(userDefined(intColumn("int32_field"), undroppable))); FilterPredicate inverse2 = LogicalInverseRewriter.rewrite(not(userDefined(intColumn("int32_field"), completeMatch))); assertFalse("Should not drop block for inverse of non-matching UDP", canDrop(inverse, ccmd, dictionaries)); assertFalse( "Should not drop block for inverse of UDP with some matches", canDrop(inverse1, ccmd, dictionaries)); assertTrue("Should drop block for inverse of UDP with all matches", canDrop(inverse2, ccmd, dictionaries)); } @Test public void testColumnWithoutDictionary() throws Exception { IntColumn plain = intColumn("plain_int32_field"); DictionaryPageReadStore dictionaryStore = mock(DictionaryPageReadStore.class); assertFalse("Should never drop block using plain encoding", canDrop(eq(plain, -10), ccmd, dictionaryStore)); assertFalse("Should never drop block using plain encoding", canDrop(lt(plain, -10), ccmd, dictionaryStore)); assertFalse("Should never drop block using plain encoding", canDrop(ltEq(plain, -10), ccmd, dictionaryStore)); assertFalse( "Should never drop block using plain encoding", canDrop(gt(plain, nElements + 10), ccmd, dictionaryStore)); assertFalse( "Should never drop block using plain encoding", canDrop(gtEq(plain, nElements + 10), ccmd, dictionaryStore)); assertFalse( "Should never drop block using plain encoding", canDrop(notEq(plain, nElements + 10), ccmd, dictionaryStore)); verifyZeroInteractions(dictionaryStore); } @Test public void testColumnWithDictionaryAndPlainEncodings() throws Exception { IntColumn plain = intColumn("fallback_binary_field"); DictionaryPageReadStore dictionaryStore = mock(DictionaryPageReadStore.class); assertFalse("Should never drop block using plain encoding", canDrop(eq(plain, -10), ccmd, dictionaryStore)); assertFalse("Should never drop block using plain encoding", canDrop(lt(plain, -10), ccmd, dictionaryStore)); assertFalse("Should never drop block using plain encoding", canDrop(ltEq(plain, -10), ccmd, dictionaryStore)); assertFalse( "Should never drop block using plain encoding", canDrop(gt(plain, nElements + 10), ccmd, dictionaryStore)); assertFalse( "Should never drop block using plain encoding", canDrop(gtEq(plain, nElements + 10), ccmd, dictionaryStore)); assertFalse( "Should never drop block using plain encoding", canDrop(notEq(plain, nElements + 10), ccmd, dictionaryStore)); verifyZeroInteractions(dictionaryStore); } @Test public void testEqMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertTrue( "Should drop block for non-null query", canDrop(eq(b, Binary.fromString("any")), ccmd, dictionaries)); assertFalse("Should not drop block null query", canDrop(eq(b, null), ccmd, dictionaries)); } @Test public void testNotEqMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertFalse( "Should not drop block for non-null query", canDrop(notEq(b, Binary.fromString("any")), ccmd, dictionaries)); assertTrue("Should not drop block null query", canDrop(notEq(b, null), ccmd, dictionaries)); } @Test public void testLtMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertTrue( "Should drop block for any non-null query", canDrop(lt(b, Binary.fromString("any")), ccmd, dictionaries)); } @Test public void testLtEqMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertTrue( "Should drop block for any non-null query", canDrop(ltEq(b, Binary.fromString("any")), ccmd, dictionaries)); } @Test public void testGtMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertTrue( "Should drop block for any non-null query", canDrop(gt(b, Binary.fromString("any")), ccmd, dictionaries)); } @Test public void testGtEqMissingColumn() throws Exception { BinaryColumn b = binaryColumn("missing_column"); assertTrue( "Should drop block for any non-null query", canDrop(gtEq(b, Binary.fromString("any")), ccmd, dictionaries)); } @Test public void testUdpMissingColumn() throws Exception { InInt32UDP nullRejecting = new InInt32UDP(ImmutableSet.of(42)); InInt32UDP nullAccepting = new InInt32UDP(Sets.newHashSet((Integer) null)); IntColumn fake = intColumn("missing_column"); assertTrue( "Should drop block for null rejecting udp", canDrop(userDefined(fake, nullRejecting), ccmd, dictionaries)); assertFalse( "Should not drop block for null accepting udp", canDrop(userDefined(fake, nullAccepting), ccmd, dictionaries)); } @Test public void testInverseUdpMissingColumn() throws Exception { InInt32UDP nullRejecting = new InInt32UDP(ImmutableSet.of(42)); InInt32UDP nullAccepting = new InInt32UDP(Sets.newHashSet((Integer) null)); IntColumn fake = intColumn("missing_column"); assertTrue( "Should drop block for null accepting udp", canDrop(LogicalInverseRewriter.rewrite(not(userDefined(fake, nullAccepting))), ccmd, dictionaries)); assertFalse( "Should not drop block for null rejecting udp", canDrop(LogicalInverseRewriter.rewrite(not(userDefined(fake, nullRejecting))), ccmd, dictionaries)); } @Test public void testContainsAnd() throws Exception { BinaryColumn col = binaryColumn("binary_field"); // both evaluate to false (no upper-case letters are in the dictionary) Operators.Contains<Binary> B = contains(eq(col, Binary.fromString("B"))); Operators.Contains<Binary> C = contains(eq(col, Binary.fromString("C"))); // both evaluate to true (all lower-case letters are in the dictionary) Operators.Contains<Binary> x = contains(eq(col, Binary.fromString("x"))); Operators.Contains<Binary> y = contains(eq(col, Binary.fromString("y"))); assertTrue("Should drop when either predicate must be false", canDrop(and(B, y), ccmd, dictionaries)); assertTrue("Should drop when either predicate must be false", canDrop(and(x, C), ccmd, dictionaries)); assertTrue("Should drop when either predicate must be false", canDrop(and(B, C), ccmd, dictionaries)); assertFalse("Should not drop when either predicate could be true", canDrop(and(x, y), ccmd, dictionaries)); } @Test public void testContainsOr() throws Exception { BinaryColumn col = binaryColumn("binary_field"); // both evaluate to false (no upper-case letters are in the dictionary) Operators.Contains<Binary> B = contains(eq(col, Binary.fromString("B"))); Operators.Contains<Binary> C = contains(eq(col, Binary.fromString("C"))); // both evaluate to true (all lower-case letters are in the dictionary) Operators.Contains<Binary> x = contains(eq(col, Binary.fromString("x"))); Operators.Contains<Binary> y = contains(eq(col, Binary.fromString("y"))); assertFalse("Should not drop when one predicate could be true", canDrop(or(B, y), ccmd, dictionaries)); assertFalse("Should not drop when one predicate could be true", canDrop(or(x, C), ccmd, dictionaries)); assertTrue("Should drop when both predicates must be false", canDrop(or(B, C), ccmd, dictionaries)); assertFalse("Should not drop when one predicate could be true", canDrop(or(x, y), ccmd, dictionaries)); } private static final class InInt32UDP extends UserDefinedPredicate<Integer> implements Serializable { private final Set<Integer> ints; InInt32UDP(Set<Integer> ints) { this.ints = ints; } @Override public boolean keep(Integer value) { return ints.contains(value); } @Override public boolean canDrop(Statistics<Integer> statistics) { return false; } @Override public boolean inverseCanDrop(Statistics<Integer> statistics) { return false; } } private static double toDouble(int value) { return (value * 1.0); } private static float toFloat(int value) { return (float) (value * 2.0); } }
google/j2objc
38,195
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Spliterator.java
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; /** * An object for traversing and partitioning elements of a source. The source * of elements covered by a Spliterator could be, for example, an array, a * {@link Collection}, an IO channel, or a generator function. * * <p>A Spliterator may traverse elements individually ({@link * #tryAdvance tryAdvance()}) or sequentially in bulk * ({@link #forEachRemaining forEachRemaining()}). * * <p>A Spliterator may also partition off some of its elements (using * {@link #trySplit}) as another Spliterator, to be used in * possibly-parallel operations. Operations using a Spliterator that * cannot split, or does so in a highly imbalanced or inefficient * manner, are unlikely to benefit from parallelism. Traversal * and splitting exhaust elements; each Spliterator is useful for only a single * bulk computation. * * <p>A Spliterator also reports a set of {@link #characteristics()} of its * structure, source, and elements from among {@link #ORDERED}, * {@link #DISTINCT}, {@link #SORTED}, {@link #SIZED}, {@link #NONNULL}, * {@link #IMMUTABLE}, {@link #CONCURRENT}, and {@link #SUBSIZED}. These may * be employed by Spliterator clients to control, specialize or simplify * computation. For example, a Spliterator for a {@link Collection} would * report {@code SIZED}, a Spliterator for a {@link Set} would report * {@code DISTINCT}, and a Spliterator for a {@link SortedSet} would also * report {@code SORTED}. Characteristics are reported as a simple unioned bit * set. * * Some characteristics additionally constrain method behavior; for example if * {@code ORDERED}, traversal methods must conform to their documented ordering. * New characteristics may be defined in the future, so implementors should not * assign meanings to unlisted values. * * <p><a id="binding">A Spliterator that does not report {@code IMMUTABLE} or * {@code CONCURRENT} is expected to have a documented policy concerning: * when the spliterator <em>binds</em> to the element source; and detection of * structural interference of the element source detected after binding.</a> A * <em>late-binding</em> Spliterator binds to the source of elements at the * point of first traversal, first split, or first query for estimated size, * rather than at the time the Spliterator is created. A Spliterator that is * not <em>late-binding</em> binds to the source of elements at the point of * construction or first invocation of any method. Modifications made to the * source prior to binding are reflected when the Spliterator is traversed. * After binding a Spliterator should, on a best-effort basis, throw * {@link ConcurrentModificationException} if structural interference is * detected. Spliterators that do this are called <em>fail-fast</em>. The * bulk traversal method ({@link #forEachRemaining forEachRemaining()}) of a * Spliterator may optimize traversal and check for structural interference * after all elements have been traversed, rather than checking per-element and * failing immediately. * * <p>Spliterators can provide an estimate of the number of remaining elements * via the {@link #estimateSize} method. Ideally, as reflected in characteristic * {@link #SIZED}, this value corresponds exactly to the number of elements * that would be encountered in a successful traversal. However, even when not * exactly known, an estimated value may still be useful to operations * being performed on the source, such as helping to determine whether it is * preferable to split further or traverse the remaining elements sequentially. * * <p>Despite their obvious utility in parallel algorithms, spliterators are not * expected to be thread-safe; instead, implementations of parallel algorithms * using spliterators should ensure that the spliterator is only used by one * thread at a time. This is generally easy to attain via <em>serial * thread-confinement</em>, which often is a natural consequence of typical * parallel algorithms that work by recursive decomposition. A thread calling * {@link #trySplit()} may hand over the returned Spliterator to another thread, * which in turn may traverse or further split that Spliterator. The behaviour * of splitting and traversal is undefined if two or more threads operate * concurrently on the same spliterator. If the original thread hands a * spliterator off to another thread for processing, it is best if that handoff * occurs before any elements are consumed with {@link #tryAdvance(Consumer) * tryAdvance()}, as certain guarantees (such as the accuracy of * {@link #estimateSize()} for {@code SIZED} spliterators) are only valid before * traversal has begun. * * <p>Primitive subtype specializations of {@code Spliterator} are provided for * {@link OfInt int}, {@link OfLong long}, and {@link OfDouble double} values. * The subtype default implementations of * {@link Spliterator#tryAdvance(java.util.function.Consumer)} * and {@link Spliterator#forEachRemaining(java.util.function.Consumer)} box * primitive values to instances of their corresponding wrapper class. Such * boxing may undermine any performance advantages gained by using the primitive * specializations. To avoid boxing, the corresponding primitive-based methods * should be used. For example, * {@link Spliterator.OfInt#tryAdvance(java.util.function.IntConsumer)} * and {@link Spliterator.OfInt#forEachRemaining(java.util.function.IntConsumer)} * should be used in preference to * {@link Spliterator.OfInt#tryAdvance(java.util.function.Consumer)} and * {@link Spliterator.OfInt#forEachRemaining(java.util.function.Consumer)}. * Traversal of primitive values using boxing-based methods * {@link #tryAdvance tryAdvance()} and * {@link #forEachRemaining(java.util.function.Consumer) forEachRemaining()} * does not affect the order in which the values, transformed to boxed values, * are encountered. * * @apiNote * <p>Spliterators, like {@code Iterator}s, are for traversing the elements of * a source. The {@code Spliterator} API was designed to support efficient * parallel traversal in addition to sequential traversal, by supporting * decomposition as well as single-element iteration. In addition, the * protocol for accessing elements via a Spliterator is designed to impose * smaller per-element overhead than {@code Iterator}, and to avoid the inherent * race involved in having separate methods for {@code hasNext()} and * {@code next()}. * * <p>For mutable sources, arbitrary and non-deterministic behavior may occur if * the source is structurally interfered with (elements added, replaced, or * removed) between the time that the Spliterator binds to its data source and * the end of traversal. For example, such interference will produce arbitrary, * non-deterministic results when using the {@code java.util.stream} framework. * * <p>Structural interference of a source can be managed in the following ways * (in approximate order of decreasing desirability): * <ul> * <li>The source cannot be structurally interfered with. * <br>For example, an instance of * {@link java.util.concurrent.CopyOnWriteArrayList} is an immutable source. * A Spliterator created from the source reports a characteristic of * {@code IMMUTABLE}.</li> * <li>The source manages concurrent modifications. * <br>For example, a key set of a {@link java.util.concurrent.ConcurrentHashMap} * is a concurrent source. A Spliterator created from the source reports a * characteristic of {@code CONCURRENT}.</li> * <li>The mutable source provides a late-binding and fail-fast Spliterator. * <br>Late binding narrows the window during which interference can affect * the calculation; fail-fast detects, on a best-effort basis, that structural * interference has occurred after traversal has commenced and throws * {@link ConcurrentModificationException}. For example, {@link ArrayList}, * and many other non-concurrent {@code Collection} classes in the JDK, provide * a late-binding, fail-fast spliterator.</li> * <li>The mutable source provides a non-late-binding but fail-fast Spliterator. * <br>The source increases the likelihood of throwing * {@code ConcurrentModificationException} since the window of potential * interference is larger.</li> * <li>The mutable source provides a late-binding and non-fail-fast Spliterator. * <br>The source risks arbitrary, non-deterministic behavior after traversal * has commenced since interference is not detected. * </li> * <li>The mutable source provides a non-late-binding and non-fail-fast * Spliterator. * <br>The source increases the risk of arbitrary, non-deterministic behavior * since non-detected interference may occur after construction. * </li> * </ul> * * <p><b>Example.</b> Here is a class (not a very useful one, except * for illustration) that maintains an array in which the actual data * are held in even locations, and unrelated tag data are held in odd * locations. Its Spliterator ignores the tags. * * <pre> {@code * class TaggedArray<T> { * private final Object[] elements; // immutable after construction * TaggedArray(T[] data, Object[] tags) { * int size = data.length; * if (tags.length != size) throw new IllegalArgumentException(); * this.elements = new Object[2 * size]; * for (int i = 0, j = 0; i < size; ++i) { * elements[j++] = data[i]; * elements[j++] = tags[i]; * } * } * * public Spliterator<T> spliterator() { * return new TaggedArraySpliterator<>(elements, 0, elements.length); * } * * static class TaggedArraySpliterator<T> implements Spliterator<T> { * private final Object[] array; * private int origin; // current index, advanced on split or traversal * private final int fence; // one past the greatest index * * TaggedArraySpliterator(Object[] array, int origin, int fence) { * this.array = array; this.origin = origin; this.fence = fence; * } * * public void forEachRemaining(Consumer<? super T> action) { * for (; origin < fence; origin += 2) * action.accept((T) array[origin]); * } * * public boolean tryAdvance(Consumer<? super T> action) { * if (origin < fence) { * action.accept((T) array[origin]); * origin += 2; * return true; * } * else // cannot advance * return false; * } * * public Spliterator<T> trySplit() { * int lo = origin; // divide range in half * int mid = ((lo + fence) >>> 1) & ~1; // force midpoint to be even * if (lo < mid) { // split out left half * origin = mid; // reset this Spliterator's origin * return new TaggedArraySpliterator<>(array, lo, mid); * } * else // too small to split * return null; * } * * public long estimateSize() { * return (long)((fence - origin) / 2); * } * * public int characteristics() { * return ORDERED | SIZED | IMMUTABLE | SUBSIZED; * } * } * }}</pre> * * <p>As an example how a parallel computation framework, such as the * {@code java.util.stream} package, would use Spliterator in a parallel * computation, here is one way to implement an associated parallel forEach, * that illustrates the primary usage idiom of splitting off subtasks until * the estimated amount of work is small enough to perform * sequentially. Here we assume that the order of processing across * subtasks doesn't matter; different (forked) tasks may further split * and process elements concurrently in undetermined order. This * example uses a {@link java.util.concurrent.CountedCompleter}; * similar usages apply to other parallel task constructions. * * <pre>{@code * static <T> void parEach(TaggedArray<T> a, Consumer<T> action) { * Spliterator<T> s = a.spliterator(); * long targetBatchSize = s.estimateSize() / (ForkJoinPool.getCommonPoolParallelism() * 8); * new ParEach(null, s, action, targetBatchSize).invoke(); * } * * static class ParEach<T> extends CountedCompleter<Void> { * final Spliterator<T> spliterator; * final Consumer<T> action; * final long targetBatchSize; * * ParEach(ParEach<T> parent, Spliterator<T> spliterator, * Consumer<T> action, long targetBatchSize) { * super(parent); * this.spliterator = spliterator; this.action = action; * this.targetBatchSize = targetBatchSize; * } * * public void compute() { * Spliterator<T> sub; * while (spliterator.estimateSize() > targetBatchSize && * (sub = spliterator.trySplit()) != null) { * addToPendingCount(1); * new ParEach<>(this, sub, action, targetBatchSize).fork(); * } * spliterator.forEachRemaining(action); * propagateCompletion(); * } * }}</pre> * * @implNote * If the boolean system property {@code org.openjdk.java.util.stream.tripwire} * is set to {@code true} then diagnostic warnings are reported if boxing of * primitive values occur when operating on primitive subtype specializations. * * @param <T> the type of elements returned by this Spliterator * * @see Collection * @since 1.8 */ public interface Spliterator<T> { /** * If a remaining element exists, performs the given action on it, * returning {@code true}; else returns {@code false}. If this * Spliterator is {@link #ORDERED} the action is performed on the * next element in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @param action The action * @return {@code false} if no remaining elements existed * upon entry to this method, else {@code true}. * @throws NullPointerException if the specified action is null */ boolean tryAdvance(Consumer<? super T> action); /** * Performs the given action for each remaining element, sequentially in * the current thread, until all elements have been processed or the action * throws an exception. If this Spliterator is {@link #ORDERED}, actions * are performed in encounter order. Exceptions thrown by the action * are relayed to the caller. * * @implSpec * The default implementation repeatedly invokes {@link #tryAdvance} until * it returns {@code false}. It should be overridden whenever possible. * * @param action The action * @throws NullPointerException if the specified action is null */ default void forEachRemaining(Consumer<? super T> action) { do { } while (tryAdvance(action)); } /** * If this spliterator can be partitioned, returns a Spliterator * covering elements, that will, upon return from this method, not * be covered by this Spliterator. * * <p>If this Spliterator is {@link #ORDERED}, the returned Spliterator * must cover a strict prefix of the elements. * * <p>Unless this Spliterator covers an infinite number of elements, * repeated calls to {@code trySplit()} must eventually return {@code null}. * Upon non-null return: * <ul> * <li>the value reported for {@code estimateSize()} before splitting, * must, after splitting, be greater than or equal to {@code estimateSize()} * for this and the returned Spliterator; and</li> * <li>if this Spliterator is {@code SUBSIZED}, then {@code estimateSize()} * for this spliterator before splitting must be equal to the sum of * {@code estimateSize()} for this and the returned Spliterator after * splitting.</li> * </ul> * * <p>This method may return {@code null} for any reason, * including emptiness, inability to split after traversal has * commenced, data structure constraints, and efficiency * considerations. * * @apiNote * An ideal {@code trySplit} method efficiently (without * traversal) divides its elements exactly in half, allowing * balanced parallel computation. Many departures from this ideal * remain highly effective; for example, only approximately * splitting an approximately balanced tree, or for a tree in * which leaf nodes may contain either one or two elements, * failing to further split these nodes. However, large * deviations in balance and/or overly inefficient {@code * trySplit} mechanics typically result in poor parallel * performance. * * @return a {@code Spliterator} covering some portion of the * elements, or {@code null} if this spliterator cannot be split */ Spliterator<T> trySplit(); /** * Returns an estimate of the number of elements that would be * encountered by a {@link #forEachRemaining} traversal, or returns {@link * Long#MAX_VALUE} if infinite, unknown, or too expensive to compute. * * <p>If this Spliterator is {@link #SIZED} and has not yet been partially * traversed or split, or this Spliterator is {@link #SUBSIZED} and has * not yet been partially traversed, this estimate must be an accurate * count of elements that would be encountered by a complete traversal. * Otherwise, this estimate may be arbitrarily inaccurate, but must decrease * as specified across invocations of {@link #trySplit}. * * @apiNote * Even an inexact estimate is often useful and inexpensive to compute. * For example, a sub-spliterator of an approximately balanced binary tree * may return a value that estimates the number of elements to be half of * that of its parent; if the root Spliterator does not maintain an * accurate count, it could estimate size to be the power of two * corresponding to its maximum depth. * * @return the estimated size, or {@code Long.MAX_VALUE} if infinite, * unknown, or too expensive to compute. */ long estimateSize(); /** * Convenience method that returns {@link #estimateSize()} if this * Spliterator is {@link #SIZED}, else {@code -1}. * @implSpec * The default implementation returns the result of {@code estimateSize()} * if the Spliterator reports a characteristic of {@code SIZED}, and * {@code -1} otherwise. * * @return the exact size, if known, else {@code -1}. */ default long getExactSizeIfKnown() { return (characteristics() & SIZED) == 0 ? -1L : estimateSize(); } /** * Returns a set of characteristics of this Spliterator and its * elements. The result is represented as ORed values from {@link * #ORDERED}, {@link #DISTINCT}, {@link #SORTED}, {@link #SIZED}, * {@link #NONNULL}, {@link #IMMUTABLE}, {@link #CONCURRENT}, * {@link #SUBSIZED}. Repeated calls to {@code characteristics()} on * a given spliterator, prior to or in-between calls to {@code trySplit}, * should always return the same result. * * <p>If a Spliterator reports an inconsistent set of * characteristics (either those returned from a single invocation * or across multiple invocations), no guarantees can be made * about any computation using this Spliterator. * * @apiNote The characteristics of a given spliterator before splitting * may differ from the characteristics after splitting. For specific * examples see the characteristic values {@link #SIZED}, {@link #SUBSIZED} * and {@link #CONCURRENT}. * * @return a representation of characteristics */ int characteristics(); /** * Returns {@code true} if this Spliterator's {@link * #characteristics} contain all of the given characteristics. * * @implSpec * The default implementation returns true if the corresponding bits * of the given characteristics are set. * * @param characteristics the characteristics to check for * @return {@code true} if all the specified characteristics are present, * else {@code false} */ default boolean hasCharacteristics(int characteristics) { return (characteristics() & characteristics) == characteristics; } /** * If this Spliterator's source is {@link #SORTED} by a {@link Comparator}, * returns that {@code Comparator}. If the source is {@code SORTED} in * {@linkplain Comparable natural order}, returns {@code null}. Otherwise, * if the source is not {@code SORTED}, throws {@link IllegalStateException}. * * @implSpec * The default implementation always throws {@link IllegalStateException}. * * @return a Comparator, or {@code null} if the elements are sorted in the * natural order. * @throws IllegalStateException if the spliterator does not report * a characteristic of {@code SORTED}. */ default Comparator<? super T> getComparator() { throw new IllegalStateException(); } /** * Characteristic value signifying that an encounter order is defined for * elements. If so, this Spliterator guarantees that method * {@link #trySplit} splits a strict prefix of elements, that method * {@link #tryAdvance} steps by one element in prefix order, and that * {@link #forEachRemaining} performs actions in encounter order. * * <p>A {@link Collection} has an encounter order if the corresponding * {@link Collection#iterator} documents an order. If so, the encounter * order is the same as the documented order. Otherwise, a collection does * not have an encounter order. * * @apiNote Encounter order is guaranteed to be ascending index order for * any {@link List}. But no order is guaranteed for hash-based collections * such as {@link HashSet}. Clients of a Spliterator that reports * {@code ORDERED} are expected to preserve ordering constraints in * non-commutative parallel computations. */ public static final int ORDERED = 0x00000010; /** * Characteristic value signifying that, for each pair of * encountered elements {@code x, y}, {@code !x.equals(y)}. This * applies for example, to a Spliterator based on a {@link Set}. */ public static final int DISTINCT = 0x00000001; /** * Characteristic value signifying that encounter order follows a defined * sort order. If so, method {@link #getComparator()} returns the associated * Comparator, or {@code null} if all elements are {@link Comparable} and * are sorted by their natural ordering. * * <p>A Spliterator that reports {@code SORTED} must also report * {@code ORDERED}. * * @apiNote The spliterators for {@code Collection} classes in the JDK that * implement {@link NavigableSet} or {@link SortedSet} report {@code SORTED}. */ public static final int SORTED = 0x00000004; /** * Characteristic value signifying that the value returned from * {@code estimateSize()} prior to traversal or splitting represents a * finite size that, in the absence of structural source modification, * represents an exact count of the number of elements that would be * encountered by a complete traversal. * * @apiNote Most Spliterators for Collections, that cover all elements of a * {@code Collection} report this characteristic. Sub-spliterators, such as * those for {@link HashSet}, that cover a sub-set of elements and * approximate their reported size do not. */ public static final int SIZED = 0x00000040; /** * Characteristic value signifying that the source guarantees that * encountered elements will not be {@code null}. (This applies, * for example, to most concurrent collections, queues, and maps.) */ public static final int NONNULL = 0x00000100; /** * Characteristic value signifying that the element source cannot be * structurally modified; that is, elements cannot be added, replaced, or * removed, so such changes cannot occur during traversal. A Spliterator * that does not report {@code IMMUTABLE} or {@code CONCURRENT} is expected * to have a documented policy (for example throwing * {@link ConcurrentModificationException}) concerning structural * interference detected during traversal. */ public static final int IMMUTABLE = 0x00000400; /** * Characteristic value signifying that the element source may be safely * concurrently modified (allowing additions, replacements, and/or removals) * by multiple threads without external synchronization. If so, the * Spliterator is expected to have a documented policy concerning the impact * of modifications during traversal. * * <p>A top-level Spliterator should not report both {@code CONCURRENT} and * {@code SIZED}, since the finite size, if known, may change if the source * is concurrently modified during traversal. Such a Spliterator is * inconsistent and no guarantees can be made about any computation using * that Spliterator. Sub-spliterators may report {@code SIZED} if the * sub-split size is known and additions or removals to the source are not * reflected when traversing. * * <p>A top-level Spliterator should not report both {@code CONCURRENT} and * {@code IMMUTABLE}, since they are mutually exclusive. Such a Spliterator * is inconsistent and no guarantees can be made about any computation using * that Spliterator. Sub-spliterators may report {@code IMMUTABLE} if * additions or removals to the source are not reflected when traversing. * * @apiNote Most concurrent collections maintain a consistency policy * guaranteeing accuracy with respect to elements present at the point of * Spliterator construction, but possibly not reflecting subsequent * additions or removals. */ public static final int CONCURRENT = 0x00001000; /** * Characteristic value signifying that all Spliterators resulting from * {@code trySplit()} will be both {@link #SIZED} and {@link #SUBSIZED}. * (This means that all child Spliterators, whether direct or indirect, will * be {@code SIZED}.) * * <p>A Spliterator that does not report {@code SIZED} as required by * {@code SUBSIZED} is inconsistent and no guarantees can be made about any * computation using that Spliterator. * * @apiNote Some spliterators, such as the top-level spliterator for an * approximately balanced binary tree, will report {@code SIZED} but not * {@code SUBSIZED}, since it is common to know the size of the entire tree * but not the exact sizes of subtrees. */ public static final int SUBSIZED = 0x00004000; /** * A Spliterator specialized for primitive values. * * @param <T> the type of elements returned by this Spliterator. The * type must be a wrapper type for a primitive type, such as {@code Integer} * for the primitive {@code int} type. * @param <T_CONS> the type of primitive consumer. The type must be a * primitive specialization of {@link java.util.function.Consumer} for * {@code T}, such as {@link java.util.function.IntConsumer} for * {@code Integer}. * @param <T_SPLITR> the type of primitive Spliterator. The type must be * a primitive specialization of Spliterator for {@code T}, such as * {@link Spliterator.OfInt} for {@code Integer}. * * @see Spliterator.OfInt * @see Spliterator.OfLong * @see Spliterator.OfDouble * @since 1.8 */ public interface OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>> extends Spliterator<T> { @Override T_SPLITR trySplit(); /** * If a remaining element exists, performs the given action on it, * returning {@code true}; else returns {@code false}. If this * Spliterator is {@link #ORDERED} the action is performed on the * next element in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @param action The action * @return {@code false} if no remaining elements existed * upon entry to this method, else {@code true}. * @throws NullPointerException if the specified action is null */ @SuppressWarnings("overloads") boolean tryAdvance(T_CONS action); /** * Performs the given action for each remaining element, sequentially in * the current thread, until all elements have been processed or the * action throws an exception. If this Spliterator is {@link #ORDERED}, * actions are performed in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @implSpec * The default implementation repeatedly invokes {@link #tryAdvance} * until it returns {@code false}. It should be overridden whenever * possible. * * @param action The action * @throws NullPointerException if the specified action is null */ @SuppressWarnings("overloads") default void forEachRemaining(T_CONS action) { do { } while (tryAdvance(action)); } } /** * A Spliterator specialized for {@code int} values. * @since 1.8 */ public interface OfInt extends OfPrimitive<Integer, IntConsumer, OfInt> { @Override OfInt trySplit(); @Override boolean tryAdvance(IntConsumer action); @Override default void forEachRemaining(IntConsumer action) { do { } while (tryAdvance(action)); } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code IntConsumer} then it is cast * to {@code IntConsumer} and passed to * {@link #tryAdvance(java.util.function.IntConsumer)}; otherwise * the action is adapted to an instance of {@code IntConsumer}, by * boxing the argument of {@code IntConsumer}, and then passed to * {@link #tryAdvance(java.util.function.IntConsumer)}. */ @Override default boolean tryAdvance(Consumer<? super Integer> action) { if (action instanceof IntConsumer) { return tryAdvance((IntConsumer) action); } else { // if (Tripwire.ENABLED) // Tripwire.trip(getClass(), // "{0} calling Spliterator.OfInt.tryAdvance((IntConsumer) action::accept)"); return tryAdvance((IntConsumer) action::accept); } } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code IntConsumer} then it is cast * to {@code IntConsumer} and passed to * {@link #forEachRemaining(java.util.function.IntConsumer)}; otherwise * the action is adapted to an instance of {@code IntConsumer}, by * boxing the argument of {@code IntConsumer}, and then passed to * {@link #forEachRemaining(java.util.function.IntConsumer)}. */ @Override default void forEachRemaining(Consumer<? super Integer> action) { if (action instanceof IntConsumer) { forEachRemaining((IntConsumer) action); } else { // if (Tripwire.ENABLED) // Tripwire.trip(getClass(), // "{0} calling Spliterator.OfInt.forEachRemaining((IntConsumer) action::accept)"); forEachRemaining((IntConsumer) action::accept); } } } /** * A Spliterator specialized for {@code long} values. * @since 1.8 */ public interface OfLong extends OfPrimitive<Long, LongConsumer, OfLong> { @Override OfLong trySplit(); @Override boolean tryAdvance(LongConsumer action); @Override default void forEachRemaining(LongConsumer action) { do { } while (tryAdvance(action)); } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code LongConsumer} then it is cast * to {@code LongConsumer} and passed to * {@link #tryAdvance(java.util.function.LongConsumer)}; otherwise * the action is adapted to an instance of {@code LongConsumer}, by * boxing the argument of {@code LongConsumer}, and then passed to * {@link #tryAdvance(java.util.function.LongConsumer)}. */ @Override default boolean tryAdvance(Consumer<? super Long> action) { if (action instanceof LongConsumer) { return tryAdvance((LongConsumer) action); } else { // if (Tripwire.ENABLED) // Tripwire.trip(getClass(), // "{0} calling Spliterator.OfLong.tryAdvance((LongConsumer) action::accept)"); return tryAdvance((LongConsumer) action::accept); } } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code LongConsumer} then it is cast * to {@code LongConsumer} and passed to * {@link #forEachRemaining(java.util.function.LongConsumer)}; otherwise * the action is adapted to an instance of {@code LongConsumer}, by * boxing the argument of {@code LongConsumer}, and then passed to * {@link #forEachRemaining(java.util.function.LongConsumer)}. */ @Override default void forEachRemaining(Consumer<? super Long> action) { if (action instanceof LongConsumer) { forEachRemaining((LongConsumer) action); } else { // if (Tripwire.ENABLED) // Tripwire.trip(getClass(), // "{0} calling Spliterator.OfLong.forEachRemaining((LongConsumer) action::accept)"); forEachRemaining((LongConsumer) action::accept); } } } /** * A Spliterator specialized for {@code double} values. * @since 1.8 */ public interface OfDouble extends OfPrimitive<Double, DoubleConsumer, OfDouble> { @Override OfDouble trySplit(); @Override boolean tryAdvance(DoubleConsumer action); @Override default void forEachRemaining(DoubleConsumer action) { do { } while (tryAdvance(action)); } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code DoubleConsumer} then it is * cast to {@code DoubleConsumer} and passed to * {@link #tryAdvance(java.util.function.DoubleConsumer)}; otherwise * the action is adapted to an instance of {@code DoubleConsumer}, by * boxing the argument of {@code DoubleConsumer}, and then passed to * {@link #tryAdvance(java.util.function.DoubleConsumer)}. */ @Override default boolean tryAdvance(Consumer<? super Double> action) { if (action instanceof DoubleConsumer) { return tryAdvance((DoubleConsumer) action); } else { // if (Tripwire.ENABLED) // Tripwire.trip(getClass(), // "{0} calling Spliterator.OfDouble.tryAdvance((DoubleConsumer) action::accept)"); return tryAdvance((DoubleConsumer) action::accept); } } /** * {@inheritDoc} * @implSpec * If the action is an instance of {@code DoubleConsumer} then it is * cast to {@code DoubleConsumer} and passed to * {@link #forEachRemaining(java.util.function.DoubleConsumer)}; * otherwise the action is adapted to an instance of * {@code DoubleConsumer}, by boxing the argument of * {@code DoubleConsumer}, and then passed to * {@link #forEachRemaining(java.util.function.DoubleConsumer)}. */ @Override default void forEachRemaining(Consumer<? super Double> action) { if (action instanceof DoubleConsumer) { forEachRemaining((DoubleConsumer) action); } else { // if (Tripwire.ENABLED) // Tripwire.trip(getClass(), // "{0} calling Spliterator.OfDouble.forEachRemaining((DoubleConsumer) action::accept)"); forEachRemaining((DoubleConsumer) action::accept); } } } }
googleapis/google-cloud-java
37,794
java-biglake/proto-google-cloud-biglake-v1alpha1/src/main/java/com/google/cloud/bigquery/biglake/v1alpha1/ListDatabasesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/biglake/v1alpha1/metastore.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.biglake.v1alpha1; /** * * * <pre> * Response message for the ListDatabases method. * </pre> * * Protobuf type {@code google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse} */ public final class ListDatabasesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) ListDatabasesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDatabasesResponse.newBuilder() to construct. private ListDatabasesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDatabasesResponse() { databases_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDatabasesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1alpha1_ListDatabasesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1alpha1_ListDatabasesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.class, com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.Builder.class); } public static final int DATABASES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Database> databases_; /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Database> getDatabasesList() { return databases_; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder> getDatabasesOrBuilderList() { return databases_; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ @java.lang.Override public int getDatabasesCount() { return databases_.size(); } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ @java.lang.Override public com.google.cloud.bigquery.biglake.v1alpha1.Database getDatabases(int index) { return databases_.get(index); } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ @java.lang.Override public com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder getDatabasesOrBuilder( int index) { return databases_.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 < databases_.size(); i++) { output.writeMessage(1, databases_.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 < databases_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, databases_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse)) { return super.equals(obj); } com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse other = (com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) obj; if (!getDatabasesList().equals(other.getDatabasesList())) 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 (getDatabasesCount() > 0) { hash = (37 * hash) + DATABASES_FIELD_NUMBER; hash = (53 * hash) + getDatabasesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for the ListDatabases method. * </pre> * * Protobuf type {@code google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1alpha1_ListDatabasesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1alpha1_ListDatabasesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.class, com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.Builder.class); } // Construct using com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (databasesBuilder_ == null) { databases_ = java.util.Collections.emptyList(); } else { databases_ = null; databasesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1alpha1_ListDatabasesResponse_descriptor; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse getDefaultInstanceForType() { return com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse build() { com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse buildPartial() { com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse result = new com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse result) { if (databasesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { databases_ = java.util.Collections.unmodifiableList(databases_); bitField0_ = (bitField0_ & ~0x00000001); } result.databases_ = databases_; } else { result.databases_ = databasesBuilder_.build(); } } private void buildPartial0( com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) { return mergeFrom((com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse other) { if (other == com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse.getDefaultInstance()) return this; if (databasesBuilder_ == null) { if (!other.databases_.isEmpty()) { if (databases_.isEmpty()) { databases_ = other.databases_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDatabasesIsMutable(); databases_.addAll(other.databases_); } onChanged(); } } else { if (!other.databases_.isEmpty()) { if (databasesBuilder_.isEmpty()) { databasesBuilder_.dispose(); databasesBuilder_ = null; databases_ = other.databases_; bitField0_ = (bitField0_ & ~0x00000001); databasesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDatabasesFieldBuilder() : null; } else { databasesBuilder_.addAllMessages(other.databases_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.bigquery.biglake.v1alpha1.Database m = input.readMessage( com.google.cloud.bigquery.biglake.v1alpha1.Database.parser(), extensionRegistry); if (databasesBuilder_ == null) { ensureDatabasesIsMutable(); databases_.add(m); } else { databasesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Database> databases_ = java.util.Collections.emptyList(); private void ensureDatabasesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { databases_ = new java.util.ArrayList<com.google.cloud.bigquery.biglake.v1alpha1.Database>( databases_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.biglake.v1alpha1.Database, com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder, com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder> databasesBuilder_; /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Database> getDatabasesList() { if (databasesBuilder_ == null) { return java.util.Collections.unmodifiableList(databases_); } else { return databasesBuilder_.getMessageList(); } } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public int getDatabasesCount() { if (databasesBuilder_ == null) { return databases_.size(); } else { return databasesBuilder_.getCount(); } } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public com.google.cloud.bigquery.biglake.v1alpha1.Database getDatabases(int index) { if (databasesBuilder_ == null) { return databases_.get(index); } else { return databasesBuilder_.getMessage(index); } } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder setDatabases( int index, com.google.cloud.bigquery.biglake.v1alpha1.Database value) { if (databasesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDatabasesIsMutable(); databases_.set(index, value); onChanged(); } else { databasesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder setDatabases( int index, com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder builderForValue) { if (databasesBuilder_ == null) { ensureDatabasesIsMutable(); databases_.set(index, builderForValue.build()); onChanged(); } else { databasesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder addDatabases(com.google.cloud.bigquery.biglake.v1alpha1.Database value) { if (databasesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDatabasesIsMutable(); databases_.add(value); onChanged(); } else { databasesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder addDatabases( int index, com.google.cloud.bigquery.biglake.v1alpha1.Database value) { if (databasesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDatabasesIsMutable(); databases_.add(index, value); onChanged(); } else { databasesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder addDatabases( com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder builderForValue) { if (databasesBuilder_ == null) { ensureDatabasesIsMutable(); databases_.add(builderForValue.build()); onChanged(); } else { databasesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder addDatabases( int index, com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder builderForValue) { if (databasesBuilder_ == null) { ensureDatabasesIsMutable(); databases_.add(index, builderForValue.build()); onChanged(); } else { databasesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder addAllDatabases( java.lang.Iterable<? extends com.google.cloud.bigquery.biglake.v1alpha1.Database> values) { if (databasesBuilder_ == null) { ensureDatabasesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, databases_); onChanged(); } else { databasesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder clearDatabases() { if (databasesBuilder_ == null) { databases_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { databasesBuilder_.clear(); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public Builder removeDatabases(int index) { if (databasesBuilder_ == null) { ensureDatabasesIsMutable(); databases_.remove(index); onChanged(); } else { databasesBuilder_.remove(index); } return this; } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder getDatabasesBuilder( int index) { return getDatabasesFieldBuilder().getBuilder(index); } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder getDatabasesOrBuilder( int index) { if (databasesBuilder_ == null) { return databases_.get(index); } else { return databasesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public java.util.List<? extends com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder> getDatabasesOrBuilderList() { if (databasesBuilder_ != null) { return databasesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(databases_); } } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder addDatabasesBuilder() { return getDatabasesFieldBuilder() .addBuilder(com.google.cloud.bigquery.biglake.v1alpha1.Database.getDefaultInstance()); } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder addDatabasesBuilder( int index) { return getDatabasesFieldBuilder() .addBuilder( index, com.google.cloud.bigquery.biglake.v1alpha1.Database.getDefaultInstance()); } /** * * * <pre> * The databases from the specified catalog. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Database databases = 1;</code> */ public java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder> getDatabasesBuilderList() { return getDatabasesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.biglake.v1alpha1.Database, com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder, com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder> getDatabasesFieldBuilder() { if (databasesBuilder_ == null) { databasesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.biglake.v1alpha1.Database, com.google.cloud.bigquery.biglake.v1alpha1.Database.Builder, com.google.cloud.bigquery.biglake.v1alpha1.DatabaseOrBuilder>( databases_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); databases_ = null; } return databasesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse) private static final com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse(); } public static com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDatabasesResponse> PARSER = new com.google.protobuf.AbstractParser<ListDatabasesResponse>() { @java.lang.Override public ListDatabasesResponse 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<ListDatabasesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDatabasesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,858
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/RubricBasedInstructionFollowingInput.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/evaluation_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Instance and metric spec for RubricBasedInstructionFollowing metric. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput} */ public final class RubricBasedInstructionFollowingInput extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput) RubricBasedInstructionFollowingInputOrBuilder { private static final long serialVersionUID = 0L; // Use RubricBasedInstructionFollowingInput.newBuilder() to construct. private RubricBasedInstructionFollowingInput( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RubricBasedInstructionFollowingInput() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new RubricBasedInstructionFollowingInput(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_RubricBasedInstructionFollowingInput_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_RubricBasedInstructionFollowingInput_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput.class, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput.Builder.class); } private int bitField0_; public static final int METRIC_SPEC_FIELD_NUMBER = 1; private com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metricSpec_; /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the metricSpec field is set. */ @java.lang.Override public boolean hasMetricSpec() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The metricSpec. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec getMetricSpec() { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec .getDefaultInstance() : metricSpec_; } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpecOrBuilder getMetricSpecOrBuilder() { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec .getDefaultInstance() : metricSpec_; } public static final int INSTANCE_FIELD_NUMBER = 2; private com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance_; /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the instance field is set. */ @java.lang.Override public boolean hasInstance() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The instance. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance getInstance() { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance .getDefaultInstance() : instance_; } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstanceOrBuilder getInstanceOrBuilder() { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance .getDefaultInstance() : instance_; } 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, getMetricSpec()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getInstance()); } 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, getMetricSpec()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getInstance()); } 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.RubricBasedInstructionFollowingInput)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput other = (com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput) obj; if (hasMetricSpec() != other.hasMetricSpec()) return false; if (hasMetricSpec()) { if (!getMetricSpec().equals(other.getMetricSpec())) return false; } if (hasInstance() != other.hasInstance()) return false; if (hasInstance()) { if (!getInstance().equals(other.getInstance())) 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 (hasMetricSpec()) { hash = (37 * hash) + METRIC_SPEC_FIELD_NUMBER; hash = (53 * hash) + getMetricSpec().hashCode(); } if (hasInstance()) { hash = (37 * hash) + INSTANCE_FIELD_NUMBER; hash = (53 * hash) + getInstance().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput 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.RubricBasedInstructionFollowingInput 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> * Instance and metric spec for RubricBasedInstructionFollowing metric. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput) com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInputOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_RubricBasedInstructionFollowingInput_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_RubricBasedInstructionFollowingInput_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput.class, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput.Builder .class); } // Construct using // com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getMetricSpecFieldBuilder(); getInstanceFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; metricSpec_ = null; if (metricSpecBuilder_ != null) { metricSpecBuilder_.dispose(); metricSpecBuilder_ = null; } instance_ = null; if (instanceBuilder_ != null) { instanceBuilder_.dispose(); instanceBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_RubricBasedInstructionFollowingInput_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput .getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput build() { com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput buildPartial() { com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput result = new com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.metricSpec_ = metricSpecBuilder_ == null ? metricSpec_ : metricSpecBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.instance_ = instanceBuilder_ == null ? instance_ : instanceBuilder_.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.RubricBasedInstructionFollowingInput) { return mergeFrom( (com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput other) { if (other == com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput .getDefaultInstance()) return this; if (other.hasMetricSpec()) { mergeMetricSpec(other.getMetricSpec()); } if (other.hasInstance()) { mergeInstance(other.getInstance()); } 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(getMetricSpecFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getInstanceFieldBuilder().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.RubricBasedInstructionFollowingSpec metricSpec_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec.Builder, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpecOrBuilder> metricSpecBuilder_; /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the metricSpec field is set. */ public boolean hasMetricSpec() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The metricSpec. */ public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec getMetricSpec() { if (metricSpecBuilder_ == null) { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec .getDefaultInstance() : metricSpec_; } else { return metricSpecBuilder_.getMessage(); } } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setMetricSpec( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec value) { if (metricSpecBuilder_ == null) { if (value == null) { throw new NullPointerException(); } metricSpec_ = value; } else { metricSpecBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setMetricSpec( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec.Builder builderForValue) { if (metricSpecBuilder_ == null) { metricSpec_ = builderForValue.build(); } else { metricSpecBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeMetricSpec( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec value) { if (metricSpecBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && metricSpec_ != null && metricSpec_ != com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec .getDefaultInstance()) { getMetricSpecBuilder().mergeFrom(value); } else { metricSpec_ = value; } } else { metricSpecBuilder_.mergeFrom(value); } if (metricSpec_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearMetricSpec() { bitField0_ = (bitField0_ & ~0x00000001); metricSpec_ = null; if (metricSpecBuilder_ != null) { metricSpecBuilder_.dispose(); metricSpecBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec.Builder getMetricSpecBuilder() { bitField0_ |= 0x00000001; onChanged(); return getMetricSpecFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpecOrBuilder getMetricSpecOrBuilder() { if (metricSpecBuilder_ != null) { return metricSpecBuilder_.getMessageOrBuilder(); } else { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec .getDefaultInstance() : metricSpec_; } } /** * * * <pre> * Required. Spec for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec.Builder, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpecOrBuilder> getMetricSpecFieldBuilder() { if (metricSpecBuilder_ == null) { metricSpecBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpec.Builder, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingSpecOrBuilder>( getMetricSpec(), getParentForChildren(), isClean()); metricSpec_ = null; } return metricSpecBuilder_; } private com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance.Builder, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstanceOrBuilder> instanceBuilder_; /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the instance field is set. */ public boolean hasInstance() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The instance. */ public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance getInstance() { if (instanceBuilder_ == null) { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance .getDefaultInstance() : instance_; } else { return instanceBuilder_.getMessage(); } } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setInstance( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance value) { if (instanceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } instance_ = value; } else { instanceBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setInstance( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance.Builder builderForValue) { if (instanceBuilder_ == null) { instance_ = builderForValue.build(); } else { instanceBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeInstance( com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance value) { if (instanceBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && instance_ != null && instance_ != com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance .getDefaultInstance()) { getInstanceBuilder().mergeFrom(value); } else { instance_ = value; } } else { instanceBuilder_.mergeFrom(value); } if (instance_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearInstance() { bitField0_ = (bitField0_ & ~0x00000002); instance_ = null; if (instanceBuilder_ != null) { instanceBuilder_.dispose(); instanceBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance.Builder getInstanceBuilder() { bitField0_ |= 0x00000002; onChanged(); return getInstanceFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstanceOrBuilder getInstanceOrBuilder() { if (instanceBuilder_ != null) { return instanceBuilder_.getMessageOrBuilder(); } else { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance .getDefaultInstance() : instance_; } } /** * * * <pre> * Required. Instance for RubricBasedInstructionFollowing metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance.Builder, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstanceOrBuilder> getInstanceFieldBuilder() { if (instanceBuilder_ == null) { instanceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance, com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInstance.Builder, com.google.cloud.aiplatform.v1beta1 .RubricBasedInstructionFollowingInstanceOrBuilder>( getInstance(), getParentForChildren(), isClean()); instance_ = null; } return instanceBuilder_; } @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.RubricBasedInstructionFollowingInput) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput) private static final com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput(); } public static com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RubricBasedInstructionFollowingInput> PARSER = new com.google.protobuf.AbstractParser<RubricBasedInstructionFollowingInput>() { @java.lang.Override public RubricBasedInstructionFollowingInput 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<RubricBasedInstructionFollowingInput> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RubricBasedInstructionFollowingInput> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RubricBasedInstructionFollowingInput getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,779
java-telcoautomation/proto-google-cloud-telcoautomation-v1alpha1/src/main/java/com/google/cloud/telcoautomation/v1alpha1/ListBlueprintsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/telcoautomation/v1alpha1/telcoautomation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.telcoautomation.v1alpha1; /** * * * <pre> * Response object for `ListBlueprints`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse} */ public final class ListBlueprintsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) ListBlueprintsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListBlueprintsResponse.newBuilder() to construct. private ListBlueprintsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListBlueprintsResponse() { blueprints_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListBlueprintsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_ListBlueprintsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_ListBlueprintsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.class, com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.Builder.class); } public static final int BLUEPRINTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.telcoautomation.v1alpha1.Blueprint> blueprints_; /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.telcoautomation.v1alpha1.Blueprint> getBlueprintsList() { return blueprints_; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder> getBlueprintsOrBuilderList() { return blueprints_; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ @java.lang.Override public int getBlueprintsCount() { return blueprints_.size(); } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.Blueprint getBlueprints(int index) { return blueprints_.get(index); } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder getBlueprintsOrBuilder( int index) { return blueprints_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < blueprints_.size(); i++) { output.writeMessage(1, blueprints_.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 < blueprints_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, blueprints_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse)) { return super.equals(obj); } com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse other = (com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) obj; if (!getBlueprintsList().equals(other.getBlueprintsList())) 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 (getBlueprintsCount() > 0) { hash = (37 * hash) + BLUEPRINTS_FIELD_NUMBER; hash = (53 * hash) + getBlueprintsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response object for `ListBlueprints`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_ListBlueprintsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_ListBlueprintsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.class, com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.Builder.class); } // Construct using com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (blueprintsBuilder_ == null) { blueprints_ = java.util.Collections.emptyList(); } else { blueprints_ = null; blueprintsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_ListBlueprintsResponse_descriptor; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse getDefaultInstanceForType() { return com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse build() { com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse buildPartial() { com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse result = new com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse result) { if (blueprintsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { blueprints_ = java.util.Collections.unmodifiableList(blueprints_); bitField0_ = (bitField0_ & ~0x00000001); } result.blueprints_ = blueprints_; } else { result.blueprints_ = blueprintsBuilder_.build(); } } private void buildPartial0( com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) { return mergeFrom((com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse other) { if (other == com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse.getDefaultInstance()) return this; if (blueprintsBuilder_ == null) { if (!other.blueprints_.isEmpty()) { if (blueprints_.isEmpty()) { blueprints_ = other.blueprints_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureBlueprintsIsMutable(); blueprints_.addAll(other.blueprints_); } onChanged(); } } else { if (!other.blueprints_.isEmpty()) { if (blueprintsBuilder_.isEmpty()) { blueprintsBuilder_.dispose(); blueprintsBuilder_ = null; blueprints_ = other.blueprints_; bitField0_ = (bitField0_ & ~0x00000001); blueprintsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getBlueprintsFieldBuilder() : null; } else { blueprintsBuilder_.addAllMessages(other.blueprints_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.telcoautomation.v1alpha1.Blueprint m = input.readMessage( com.google.cloud.telcoautomation.v1alpha1.Blueprint.parser(), extensionRegistry); if (blueprintsBuilder_ == null) { ensureBlueprintsIsMutable(); blueprints_.add(m); } else { blueprintsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.telcoautomation.v1alpha1.Blueprint> blueprints_ = java.util.Collections.emptyList(); private void ensureBlueprintsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { blueprints_ = new java.util.ArrayList<com.google.cloud.telcoautomation.v1alpha1.Blueprint>( blueprints_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Blueprint, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder, com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder> blueprintsBuilder_; /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public java.util.List<com.google.cloud.telcoautomation.v1alpha1.Blueprint> getBlueprintsList() { if (blueprintsBuilder_ == null) { return java.util.Collections.unmodifiableList(blueprints_); } else { return blueprintsBuilder_.getMessageList(); } } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public int getBlueprintsCount() { if (blueprintsBuilder_ == null) { return blueprints_.size(); } else { return blueprintsBuilder_.getCount(); } } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public com.google.cloud.telcoautomation.v1alpha1.Blueprint getBlueprints(int index) { if (blueprintsBuilder_ == null) { return blueprints_.get(index); } else { return blueprintsBuilder_.getMessage(index); } } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder setBlueprints( int index, com.google.cloud.telcoautomation.v1alpha1.Blueprint value) { if (blueprintsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBlueprintsIsMutable(); blueprints_.set(index, value); onChanged(); } else { blueprintsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder setBlueprints( int index, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder builderForValue) { if (blueprintsBuilder_ == null) { ensureBlueprintsIsMutable(); blueprints_.set(index, builderForValue.build()); onChanged(); } else { blueprintsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder addBlueprints(com.google.cloud.telcoautomation.v1alpha1.Blueprint value) { if (blueprintsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBlueprintsIsMutable(); blueprints_.add(value); onChanged(); } else { blueprintsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder addBlueprints( int index, com.google.cloud.telcoautomation.v1alpha1.Blueprint value) { if (blueprintsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBlueprintsIsMutable(); blueprints_.add(index, value); onChanged(); } else { blueprintsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder addBlueprints( com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder builderForValue) { if (blueprintsBuilder_ == null) { ensureBlueprintsIsMutable(); blueprints_.add(builderForValue.build()); onChanged(); } else { blueprintsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder addBlueprints( int index, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder builderForValue) { if (blueprintsBuilder_ == null) { ensureBlueprintsIsMutable(); blueprints_.add(index, builderForValue.build()); onChanged(); } else { blueprintsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder addAllBlueprints( java.lang.Iterable<? extends com.google.cloud.telcoautomation.v1alpha1.Blueprint> values) { if (blueprintsBuilder_ == null) { ensureBlueprintsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, blueprints_); onChanged(); } else { blueprintsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder clearBlueprints() { if (blueprintsBuilder_ == null) { blueprints_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { blueprintsBuilder_.clear(); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public Builder removeBlueprints(int index) { if (blueprintsBuilder_ == null) { ensureBlueprintsIsMutable(); blueprints_.remove(index); onChanged(); } else { blueprintsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder getBlueprintsBuilder( int index) { return getBlueprintsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder getBlueprintsOrBuilder( int index) { if (blueprintsBuilder_ == null) { return blueprints_.get(index); } else { return blueprintsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public java.util.List<? extends com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder> getBlueprintsOrBuilderList() { if (blueprintsBuilder_ != null) { return blueprintsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(blueprints_); } } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder addBlueprintsBuilder() { return getBlueprintsFieldBuilder() .addBuilder(com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance()); } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder addBlueprintsBuilder( int index) { return getBlueprintsFieldBuilder() .addBuilder( index, com.google.cloud.telcoautomation.v1alpha1.Blueprint.getDefaultInstance()); } /** * * * <pre> * The list of requested blueprints. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1alpha1.Blueprint blueprints = 1;</code> */ public java.util.List<com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder> getBlueprintsBuilderList() { return getBlueprintsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Blueprint, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder, com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder> getBlueprintsFieldBuilder() { if (blueprintsBuilder_ == null) { blueprintsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Blueprint, com.google.cloud.telcoautomation.v1alpha1.Blueprint.Builder, com.google.cloud.telcoautomation.v1alpha1.BlueprintOrBuilder>( blueprints_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); blueprints_ = null; } return blueprintsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse) private static final com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse(); } public static com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListBlueprintsResponse> PARSER = new com.google.protobuf.AbstractParser<ListBlueprintsResponse>() { @java.lang.Override public ListBlueprintsResponse 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<ListBlueprintsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListBlueprintsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.ListBlueprintsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,804
java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/ListVersionsResponse.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/version.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2; /** * * * <pre> * The response message for * [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.ListVersionsResponse} */ public final class ListVersionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.ListVersionsResponse) ListVersionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListVersionsResponse.newBuilder() to construct. private ListVersionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListVersionsResponse() { versions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListVersionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.VersionProto .internal_static_google_cloud_dialogflow_v2_ListVersionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.VersionProto .internal_static_google_cloud_dialogflow_v2_ListVersionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.ListVersionsResponse.class, com.google.cloud.dialogflow.v2.ListVersionsResponse.Builder.class); } public static final int VERSIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.v2.Version> versions_; /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.v2.Version> getVersionsList() { return versions_; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.v2.VersionOrBuilder> getVersionsOrBuilderList() { return versions_; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ @java.lang.Override public int getVersionsCount() { return versions_.size(); } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.Version getVersions(int index) { return versions_.get(index); } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.VersionOrBuilder getVersionsOrBuilder(int index) { return versions_.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 < versions_.size(); i++) { output.writeMessage(1, versions_.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 < versions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, versions_.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.ListVersionsResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.ListVersionsResponse other = (com.google.cloud.dialogflow.v2.ListVersionsResponse) obj; if (!getVersionsList().equals(other.getVersionsList())) 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 (getVersionsCount() > 0) { hash = (37 * hash) + VERSIONS_FIELD_NUMBER; hash = (53 * hash) + getVersionsList().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.ListVersionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.ListVersionsResponse 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.ListVersionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.ListVersionsResponse 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.ListVersionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.ListVersionsResponse 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.ListVersionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.ListVersionsResponse 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.ListVersionsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.ListVersionsResponse 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.ListVersionsResponse 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.ListVersionsResponse 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.ListVersionsResponse 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 * [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.ListVersionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.ListVersionsResponse) com.google.cloud.dialogflow.v2.ListVersionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.VersionProto .internal_static_google_cloud_dialogflow_v2_ListVersionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.VersionProto .internal_static_google_cloud_dialogflow_v2_ListVersionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.ListVersionsResponse.class, com.google.cloud.dialogflow.v2.ListVersionsResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.ListVersionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (versionsBuilder_ == null) { versions_ = java.util.Collections.emptyList(); } else { versions_ = null; versionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2.VersionProto .internal_static_google_cloud_dialogflow_v2_ListVersionsResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.ListVersionsResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.ListVersionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.ListVersionsResponse build() { com.google.cloud.dialogflow.v2.ListVersionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.ListVersionsResponse buildPartial() { com.google.cloud.dialogflow.v2.ListVersionsResponse result = new com.google.cloud.dialogflow.v2.ListVersionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.v2.ListVersionsResponse result) { if (versionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { versions_ = java.util.Collections.unmodifiableList(versions_); bitField0_ = (bitField0_ & ~0x00000001); } result.versions_ = versions_; } else { result.versions_ = versionsBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.v2.ListVersionsResponse 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.ListVersionsResponse) { return mergeFrom((com.google.cloud.dialogflow.v2.ListVersionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2.ListVersionsResponse other) { if (other == com.google.cloud.dialogflow.v2.ListVersionsResponse.getDefaultInstance()) return this; if (versionsBuilder_ == null) { if (!other.versions_.isEmpty()) { if (versions_.isEmpty()) { versions_ = other.versions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureVersionsIsMutable(); versions_.addAll(other.versions_); } onChanged(); } } else { if (!other.versions_.isEmpty()) { if (versionsBuilder_.isEmpty()) { versionsBuilder_.dispose(); versionsBuilder_ = null; versions_ = other.versions_; bitField0_ = (bitField0_ & ~0x00000001); versionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getVersionsFieldBuilder() : null; } else { versionsBuilder_.addAllMessages(other.versions_); } } } 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.Version m = input.readMessage( com.google.cloud.dialogflow.v2.Version.parser(), extensionRegistry); if (versionsBuilder_ == null) { ensureVersionsIsMutable(); versions_.add(m); } else { versionsBuilder_.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.Version> versions_ = java.util.Collections.emptyList(); private void ensureVersionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { versions_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2.Version>(versions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Version, com.google.cloud.dialogflow.v2.Version.Builder, com.google.cloud.dialogflow.v2.VersionOrBuilder> versionsBuilder_; /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2.Version> getVersionsList() { if (versionsBuilder_ == null) { return java.util.Collections.unmodifiableList(versions_); } else { return versionsBuilder_.getMessageList(); } } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public int getVersionsCount() { if (versionsBuilder_ == null) { return versions_.size(); } else { return versionsBuilder_.getCount(); } } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public com.google.cloud.dialogflow.v2.Version getVersions(int index) { if (versionsBuilder_ == null) { return versions_.get(index); } else { return versionsBuilder_.getMessage(index); } } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder setVersions(int index, com.google.cloud.dialogflow.v2.Version value) { if (versionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVersionsIsMutable(); versions_.set(index, value); onChanged(); } else { versionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder setVersions( int index, com.google.cloud.dialogflow.v2.Version.Builder builderForValue) { if (versionsBuilder_ == null) { ensureVersionsIsMutable(); versions_.set(index, builderForValue.build()); onChanged(); } else { versionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder addVersions(com.google.cloud.dialogflow.v2.Version value) { if (versionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVersionsIsMutable(); versions_.add(value); onChanged(); } else { versionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder addVersions(int index, com.google.cloud.dialogflow.v2.Version value) { if (versionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVersionsIsMutable(); versions_.add(index, value); onChanged(); } else { versionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder addVersions(com.google.cloud.dialogflow.v2.Version.Builder builderForValue) { if (versionsBuilder_ == null) { ensureVersionsIsMutable(); versions_.add(builderForValue.build()); onChanged(); } else { versionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder addVersions( int index, com.google.cloud.dialogflow.v2.Version.Builder builderForValue) { if (versionsBuilder_ == null) { ensureVersionsIsMutable(); versions_.add(index, builderForValue.build()); onChanged(); } else { versionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder addAllVersions( java.lang.Iterable<? extends com.google.cloud.dialogflow.v2.Version> values) { if (versionsBuilder_ == null) { ensureVersionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, versions_); onChanged(); } else { versionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder clearVersions() { if (versionsBuilder_ == null) { versions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { versionsBuilder_.clear(); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public Builder removeVersions(int index) { if (versionsBuilder_ == null) { ensureVersionsIsMutable(); versions_.remove(index); onChanged(); } else { versionsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public com.google.cloud.dialogflow.v2.Version.Builder getVersionsBuilder(int index) { return getVersionsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public com.google.cloud.dialogflow.v2.VersionOrBuilder getVersionsOrBuilder(int index) { if (versionsBuilder_ == null) { return versions_.get(index); } else { return versionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.v2.VersionOrBuilder> getVersionsOrBuilderList() { if (versionsBuilder_ != null) { return versionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(versions_); } } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public com.google.cloud.dialogflow.v2.Version.Builder addVersionsBuilder() { return getVersionsFieldBuilder() .addBuilder(com.google.cloud.dialogflow.v2.Version.getDefaultInstance()); } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public com.google.cloud.dialogflow.v2.Version.Builder addVersionsBuilder(int index) { return getVersionsFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.v2.Version.getDefaultInstance()); } /** * * * <pre> * The list of agent versions. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Version versions = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2.Version.Builder> getVersionsBuilderList() { return getVersionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Version, com.google.cloud.dialogflow.v2.Version.Builder, com.google.cloud.dialogflow.v2.VersionOrBuilder> getVersionsFieldBuilder() { if (versionsBuilder_ == null) { versionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Version, com.google.cloud.dialogflow.v2.Version.Builder, com.google.cloud.dialogflow.v2.VersionOrBuilder>( versions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); versions_ = null; } return versionsBuilder_; } 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.ListVersionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.ListVersionsResponse) private static final com.google.cloud.dialogflow.v2.ListVersionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.ListVersionsResponse(); } public static com.google.cloud.dialogflow.v2.ListVersionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListVersionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListVersionsResponse>() { @java.lang.Override public ListVersionsResponse 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<ListVersionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListVersionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.ListVersionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/commons-text
37,887
src/main/java/org/apache/commons/text/StringTokenizer.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.text; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.matcher.StringMatcher; import org.apache.commons.text.matcher.StringMatcherFactory; /** * Tokenizes a string based on delimiters (separators) and supporting quoting and ignored character concepts. * <p> * This class can split a String into many smaller strings. It aims to do a similar job to * {@link java.util.StringTokenizer StringTokenizer}, however it offers much more control and flexibility including * implementing the {@code ListIterator} interface. By default, it is set up like {@code StringTokenizer}. * <p> * The input String is split into a number of <em>tokens</em>. Each token is separated from the next String by a * <em>delimiter</em>. One or more delimiter characters must be specified. * <p> * Each token may be surrounded by quotes. The <em>quote</em> matcher specifies the quote character(s). A quote may be * escaped within a quoted section by duplicating itself. * <p> * Between each token and the delimiter are potentially characters that need trimming. The <em>trimmer</em> matcher * specifies these characters. One usage might be to trim whitespace characters. * <p> * At any point outside the quotes there might potentially be invalid characters. The <em>ignored</em> matcher specifies * these characters to be removed. One usage might be to remove new line characters. * <p> * Empty tokens may be removed or returned as null. * * <pre> * "a,b,c" - Three tokens "a","b","c" (comma delimiter) * " a, b , c " - Three tokens "a","b","c" (default CSV processing trims whitespace) * "a, ", b ,", c" - Three tokens "a, " , " b ", ", c" (quoted text untouched) * </pre> * * <table> * <caption>StringTokenizer properties and options</caption> * <tr> * <th>Property</th> * <th>Type</th> * <th>Default</th> * </tr> * <tr> * <td>delim</td> * <td>CharSetMatcher</td> * <td>{ \t\n\r\f}</td> * </tr> * <tr> * <td>quote</td> * <td>NoneMatcher</td> * <td>{}</td> * </tr> * <tr> * <td>ignore</td> * <td>NoneMatcher</td> * <td>{}</td> * </tr> * <tr> * <td>emptyTokenAsNull</td> * <td>boolean</td> * <td>false</td> * </tr> * <tr> * <td>ignoreEmptyTokens</td> * <td>boolean</td> * <td>true</td> * </tr> * </table> * * @since 1.3 */ public class StringTokenizer implements ListIterator<String>, Cloneable { /** Comma separated values tokenizer internal variable. */ // @formatter:off private static final StringTokenizer CSV_TOKENIZER_PROTOTYPE = new StringTokenizer() .setDelimiterMatcher(StringMatcherFactory.INSTANCE.commaMatcher()) .setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher()) .setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher()) .setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()) .setEmptyTokenAsNull(false) .setIgnoreEmptyTokens(false); // @formatter:on /** Tab separated values tokenizer internal variable. */ // @formatter:off private static final StringTokenizer TSV_TOKENIZER_PROTOTYPE = new StringTokenizer() .setDelimiterMatcher(StringMatcherFactory.INSTANCE.tabMatcher()) .setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher()) .setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher()) .setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()) .setEmptyTokenAsNull(false) .setIgnoreEmptyTokens(false); // @formatter:on /** * Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}. * * @return a clone of {@code CSV_TOKENIZER_PROTOTYPE}. */ private static StringTokenizer getCSVClone() { return (StringTokenizer) CSV_TOKENIZER_PROTOTYPE.clone(); } /** * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. * The default for CSV processing will be trim whitespace from both ends (which can be overridden with the * setTrimmer method). * <p> * You must call a "reset" method to set the string which you want to parse. * </p> * * @return a new tokenizer instance which parses Comma Separated Value strings */ public static StringTokenizer getCSVInstance() { return getCSVClone(); } /** * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. * The default for CSV processing will be trim whitespace from both ends (which can be overridden with the * setTrimmer method). * * @param input * the text to parse * @return a new tokenizer instance which parses Comma Separated Value strings */ public static StringTokenizer getCSVInstance(final char[] input) { return getCSVClone().reset(input); } /** * Gets a new tokenizer instance which parses Comma Separated Value strings initializing it with the given input. * The default for CSV processing will be trim whitespace from both ends (which can be overridden with the * setTrimmer method). * * @param input * the text to parse * @return a new tokenizer instance which parses Comma Separated Value strings */ public static StringTokenizer getCSVInstance(final String input) { return getCSVClone().reset(input); } /** * Returns a clone of {@code TSV_TOKENIZER_PROTOTYPE}. * * @return a clone of {@code TSV_TOKENIZER_PROTOTYPE}. */ private static StringTokenizer getTSVClone() { return (StringTokenizer) TSV_TOKENIZER_PROTOTYPE.clone(); } /** * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be * trim whitespace from both ends (which can be overridden with the setTrimmer method). * <p> * You must call a "reset" method to set the string which you want to parse. * </p> * * @return a new tokenizer instance which parses Tab Separated Value strings. */ public static StringTokenizer getTSVInstance() { return getTSVClone(); } /** * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be * trim whitespace from both ends (which can be overridden with the setTrimmer method). * * @param input * the string to parse * @return a new tokenizer instance which parses Tab Separated Value strings. */ public static StringTokenizer getTSVInstance(final char[] input) { return getTSVClone().reset(input); } /** * Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be * trim whitespace from both ends (which can be overridden with the setTrimmer method). * * @param input * the string to parse * @return a new tokenizer instance which parses Tab Separated Value strings. */ public static StringTokenizer getTSVInstance(final String input) { return getTSVClone().reset(input); } /** The text to work on. */ private char[] chars; /** The parsed tokens. */ private String[] tokens; /** The current iteration position. */ private int tokenPos; /** The delimiter matcher. */ private StringMatcher delimMatcher = StringMatcherFactory.INSTANCE.splitMatcher(); /** The quote matcher. */ private StringMatcher quoteMatcher = StringMatcherFactory.INSTANCE.noneMatcher(); /** The ignored matcher. */ private StringMatcher ignoredMatcher = StringMatcherFactory.INSTANCE.noneMatcher(); /** The trimmer matcher. */ private StringMatcher trimmerMatcher = StringMatcherFactory.INSTANCE.noneMatcher(); /** Whether to return empty tokens as null. */ private boolean emptyAsNull; /** Whether to ignore empty tokens. */ private boolean ignoreEmptyTokens = true; /** * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer, but with no text to * tokenize. * <p> * This constructor is normally used with {@link #reset(String)}. * </p> */ public StringTokenizer() { this.chars = null; } /** * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer. * * @param input * the string which is to be parsed, not cloned */ public StringTokenizer(final char[] input) { this.chars = input != null ? input.clone() : null; } /** * Constructs a tokenizer splitting on the specified character. * * @param input * the string which is to be parsed, not cloned * @param delim * the field delimiter character */ public StringTokenizer(final char[] input, final char delim) { this(input); setDelimiterChar(delim); } /** * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified * quote character. * * @param input * the string which is to be parsed, not cloned * @param delim * the field delimiter character * @param quote * the field quoted string character */ public StringTokenizer(final char[] input, final char delim, final char quote) { this(input, delim); setQuoteChar(quote); } /** * Constructs a tokenizer splitting on the specified string. * * @param input * the string which is to be parsed, not cloned * @param delim * the field delimiter string */ public StringTokenizer(final char[] input, final String delim) { this(input); setDelimiterString(delim); } /** * Constructs a tokenizer splitting using the specified delimiter matcher. * * @param input * the string which is to be parsed, not cloned * @param delim * the field delimiter matcher */ public StringTokenizer(final char[] input, final StringMatcher delim) { this(input); setDelimiterMatcher(delim); } /** * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified * quote matcher. * * @param input * the string which is to be parsed, not cloned * @param delim * the field delimiter character * @param quote * the field quoted string character */ public StringTokenizer(final char[] input, final StringMatcher delim, final StringMatcher quote) { this(input, delim); setQuoteMatcher(quote); } /** * Constructs a tokenizer splitting on space, tab, newline and form feed as per StringTokenizer. * * @param input * the string which is to be parsed */ public StringTokenizer(final String input) { this.chars = input != null ? input.toCharArray() : null; } /** * Constructs a tokenizer splitting on the specified delimiter character. * * @param input * the string which is to be parsed * @param delim * the field delimiter character */ public StringTokenizer(final String input, final char delim) { this(input); setDelimiterChar(delim); } /** * Constructs a tokenizer splitting on the specified delimiter character and handling quotes using the specified * quote character. * * @param input * the string which is to be parsed * @param delim * the field delimiter character * @param quote * the field quoted string character */ public StringTokenizer(final String input, final char delim, final char quote) { this(input, delim); setQuoteChar(quote); } /** * Constructs a tokenizer splitting on the specified delimiter string. * * @param input * the string which is to be parsed * @param delim * the field delimiter string */ public StringTokenizer(final String input, final String delim) { this(input); setDelimiterString(delim); } /** * Constructs a tokenizer splitting using the specified delimiter matcher. * * @param input * the string which is to be parsed * @param delim * the field delimiter matcher */ public StringTokenizer(final String input, final StringMatcher delim) { this(input); setDelimiterMatcher(delim); } /** * Constructs a tokenizer splitting using the specified delimiter matcher and handling quotes using the specified * quote matcher. * * @param input * the string which is to be parsed * @param delim * the field delimiter matcher * @param quote * the field quoted string matcher */ public StringTokenizer(final String input, final StringMatcher delim, final StringMatcher quote) { this(input, delim); setQuoteMatcher(quote); } /** * Unsupported ListIterator operation. * * @param obj * this parameter ignored. * @throws UnsupportedOperationException * always */ @Override public void add(final String obj) { throw new UnsupportedOperationException("add() is unsupported"); } /** * Adds a token to a list, paying attention to the parameters we've set. * * @param list * the list to add to * @param tok * the token to add */ private void addToken(final List<String> list, String tok) { if (tok == null || tok.isEmpty()) { if (isIgnoreEmptyTokens()) { return; } if (isEmptyTokenAsNull()) { tok = null; } } list.add(tok); } /** * Checks if tokenization has been done, and if not then do it. */ private void checkTokenized() { if (tokens == null) { final List<String> split; if (chars == null) { // still call tokenize as subclass may do some work split = tokenize(null, 0, 0); } else { split = tokenize(chars, 0, chars.length); } tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY); } } /** * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token * list. If a {@link CloneNotSupportedException} is caught, return {@code null}. * * @return a new instance of this Tokenizer which has been reset. */ @Override public Object clone() { try { return cloneReset(); } catch (final CloneNotSupportedException ex) { return null; } } /** * Creates a new instance of this Tokenizer. The new instance is reset so that it will be at the start of the token * list. * * @return a new instance of this Tokenizer which has been reset. * @throws CloneNotSupportedException * if there is a problem cloning */ Object cloneReset() throws CloneNotSupportedException { // this method exists to enable 100% test coverage final StringTokenizer cloned = (StringTokenizer) super.clone(); if (cloned.chars != null) { cloned.chars = cloned.chars.clone(); } cloned.reset(); return cloned; } /** * Gets the String content that the tokenizer is parsing. * * @return The string content being parsed */ public String getContent() { if (chars == null) { return null; } return new String(chars); } /** * Gets the field delimiter matcher. * * @return The delimiter matcher in use */ public StringMatcher getDelimiterMatcher() { return this.delimMatcher; } /** * Gets the ignored character matcher. * <p> * These characters are ignored when parsing the String, unless they are within a quoted region. The default value * is not to ignore anything. * </p> * * @return The ignored matcher in use */ public StringMatcher getIgnoredMatcher() { return ignoredMatcher; } /** * Gets the quote matcher currently in use. * <p> * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. The * default value is '"' (double quote). * </p> * * @return The quote matcher in use */ public StringMatcher getQuoteMatcher() { return quoteMatcher; } /** * Gets a copy of the full token list as an independent modifiable array. * * @return The tokens as a String array */ public String[] getTokenArray() { checkTokenized(); return tokens.clone(); } /** * Gets a copy of the full token list as an independent modifiable list. * * @return The tokens as a String list */ public List<String> getTokenList() { checkTokenized(); return new ArrayList<>(Arrays.asList(tokens)); } /** * Gets the trimmer character matcher. * <p> * These characters are trimmed off on each side of the delimiter until the token or quote is found. The default * value is not to trim anything. * </p> * * @return The trimmer matcher in use */ public StringMatcher getTrimmerMatcher() { return trimmerMatcher; } /** * Tests whether there are any more tokens. * * @return true if there are more tokens */ @Override public boolean hasNext() { checkTokenized(); return tokenPos < tokens.length; } /** * Tests whether there are any previous tokens that can be iterated to. * * @return true if there are previous tokens */ @Override public boolean hasPrevious() { checkTokenized(); return tokenPos > 0; } /** * Tests whether the tokenizer currently returns empty tokens as null. The default for this property is false. * * @return true if empty tokens are returned as null */ public boolean isEmptyTokenAsNull() { return this.emptyAsNull; } /** * Tests whether the tokenizer currently ignores empty tokens. The default for this property is true. * * @return true if empty tokens are not returned */ public boolean isIgnoreEmptyTokens() { return ignoreEmptyTokens; } /** * Tests if the characters at the index specified match the quote already matched in readNextToken(). * * @param srcChars * the character array being tokenized * @param pos * the position to check for a quote * @param len * the length of the character array being tokenized * @param quoteStart * the start position of the matched quote, 0 if no quoting * @param quoteLen * the length of the matched quote, 0 if no quoting * @return true if a quote is matched */ private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart, final int quoteLen) { for (int i = 0; i < quoteLen; i++) { if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) { return false; } } return true; } /** * Gets the next token. * * @return The next String token * @throws NoSuchElementException * if there are no more elements */ @Override public String next() { if (hasNext()) { return tokens[tokenPos++]; } throw new NoSuchElementException(); } /** * Gets the index of the next token to return. * * @return The next token index */ @Override public int nextIndex() { return tokenPos; } /** * Gets the next token from the String. Equivalent to {@link #next()} except it returns null rather than throwing * {@link NoSuchElementException} when no tokens remain. * * @return The next sequential token, or null when no more tokens are found */ public String nextToken() { if (hasNext()) { return tokens[tokenPos++]; } return null; } /** * Gets the token previous to the last returned token. * * @return The previous token */ @Override public String previous() { if (hasPrevious()) { return tokens[--tokenPos]; } throw new NoSuchElementException(); } /** * Gets the index of the previous token. * * @return The previous token index */ @Override public int previousIndex() { return tokenPos - 1; } /** * Gets the previous token from the String. * * @return The previous sequential token, or null when no more tokens are found */ public String previousToken() { if (hasPrevious()) { return tokens[--tokenPos]; } return null; } /** * Reads character by character through the String to get the next token. * * @param srcChars * the character array being tokenized * @param start * the first character of field * @param len * the length of the character array being tokenized * @param workArea * a temporary work area * @param tokenList * the list of parsed tokens * @return The starting position of the next field (the character immediately after the delimiter), or -1 if end of * string found */ private int readNextToken(final char[] srcChars, int start, final int len, final TextStringBuilder workArea, final List<String> tokenList) { // skip all leading whitespace, unless it is the // field delimiter or the quote character while (start < len) { final int removeLen = Math.max(getIgnoredMatcher().isMatch(srcChars, start, start, len), getTrimmerMatcher().isMatch(srcChars, start, start, len)); if (removeLen == 0 || getDelimiterMatcher().isMatch(srcChars, start, start, len) > 0 || getQuoteMatcher().isMatch(srcChars, start, start, len) > 0) { break; } start += removeLen; } // handle reaching end if (start >= len) { addToken(tokenList, StringUtils.EMPTY); return -1; } // handle empty token final int delimLen = getDelimiterMatcher().isMatch(srcChars, start, start, len); if (delimLen > 0) { addToken(tokenList, StringUtils.EMPTY); return start + delimLen; } // handle found token final int quoteLen = getQuoteMatcher().isMatch(srcChars, start, start, len); if (quoteLen > 0) { return readWithQuotes(srcChars, start + quoteLen, len, workArea, tokenList, start, quoteLen); } return readWithQuotes(srcChars, start, len, workArea, tokenList, 0, 0); } /** * Reads a possibly quoted string token. * * @param srcChars * the character array being tokenized * @param start * the first character of field * @param len * the length of the character array being tokenized * @param workArea * a temporary work area * @param tokenList * the list of parsed tokens * @param quoteStart * the start position of the matched quote, 0 if no quoting * @param quoteLen * the length of the matched quote, 0 if no quoting * @return The starting position of the next field (the character immediately after the delimiter, or if end of * string found, then the length of string */ private int readWithQuotes(final char[] srcChars, final int start, final int len, final TextStringBuilder workArea, final List<String> tokenList, final int quoteStart, final int quoteLen) { // Loop until we've found the end of the quoted // string or the end of the input workArea.clear(); int pos = start; boolean quoting = quoteLen > 0; int trimStart = 0; while (pos < len) { // quoting mode can occur several times throughout a string // we must switch between quoting and non-quoting until we // encounter a non-quoted delimiter, or end of string if (quoting) { // In quoting mode // If we've found a quote character, see if it's // followed by a second quote. If so, then we need // to actually put the quote character into the token // rather than end the token. if (isQuote(srcChars, pos, len, quoteStart, quoteLen)) { if (isQuote(srcChars, pos + quoteLen, len, quoteStart, quoteLen)) { // matched pair of quotes, thus an escaped quote workArea.append(srcChars, pos, quoteLen); pos += quoteLen * 2; trimStart = workArea.size(); continue; } // end of quoting quoting = false; pos += quoteLen; continue; } } else { // Not in quoting mode // check for delimiter, and thus end of token final int delimLen = getDelimiterMatcher().isMatch(srcChars, pos, start, len); if (delimLen > 0) { // return condition when end of token found addToken(tokenList, workArea.substring(0, trimStart)); return pos + delimLen; } // check for quote, and thus back into quoting mode if (quoteLen > 0 && isQuote(srcChars, pos, len, quoteStart, quoteLen)) { quoting = true; pos += quoteLen; continue; } // check for ignored (outside quotes), and ignore final int ignoredLen = getIgnoredMatcher().isMatch(srcChars, pos, start, len); if (ignoredLen > 0) { pos += ignoredLen; continue; } // check for trimmed character // don't yet know if its at the end, so copy to workArea // use trimStart to keep track of trim at the end final int trimmedLen = getTrimmerMatcher().isMatch(srcChars, pos, start, len); if (trimmedLen > 0) { workArea.append(srcChars, pos, trimmedLen); pos += trimmedLen; continue; } } // copy regular character from inside quotes workArea.append(srcChars[pos++]); trimStart = workArea.size(); } // return condition when end of string found addToken(tokenList, workArea.substring(0, trimStart)); return -1; } /** * Throws {@link UnsupportedOperationException} for this unsupported ListIterator operation. * * @throws UnsupportedOperationException * always */ @Override public void remove() { throw new UnsupportedOperationException("remove() is unsupported"); } /** * Resets this tokenizer, forgetting all parsing and iteration already completed. * <p> * This method allows the same tokenizer to be reused for the same String. * </p> * * @return this, to enable chaining */ public StringTokenizer reset() { tokenPos = 0; tokens = null; return this; } /** * Resets this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the * same settings on multiple input lines. * * @param input * the new character array to tokenize, not cloned, null sets no text to parse * @return this, to enable chaining */ public StringTokenizer reset(final char[] input) { reset(); this.chars = input != null ? input.clone() : null; return this; } /** * Resets this tokenizer, giving it a new input string to parse. In this manner you can re-use a tokenizer with the * same settings on multiple input lines. * * @param input * the new string to tokenize, null sets no text to parse * @return this, to enable chaining */ public StringTokenizer reset(final String input) { reset(); this.chars = input != null ? input.toCharArray() : null; return this; } /** * Throws {@link UnsupportedOperationException} for this unsupported ListIterator operation. * * @param obj * this parameter ignored. * @throws UnsupportedOperationException * always */ @Override public void set(final String obj) { throw new UnsupportedOperationException("set() is unsupported"); } /** * Sets the field delimiter character. * * @param delim * the delimiter character to use * @return this, to enable chaining */ public StringTokenizer setDelimiterChar(final char delim) { return setDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(delim)); } /** * Sets the field delimiter matcher. * <p> * The delimiter is used to separate one token from another. * </p> * * @param delim * the delimiter matcher to use * @return this, to enable chaining */ public StringTokenizer setDelimiterMatcher(final StringMatcher delim) { this.delimMatcher = delim == null ? StringMatcherFactory.INSTANCE.noneMatcher() : delim; return this; } /** * Sets the field delimiter string. * * @param delim * the delimiter string to use * @return this, to enable chaining */ public StringTokenizer setDelimiterString(final String delim) { return setDelimiterMatcher(StringMatcherFactory.INSTANCE.stringMatcher(delim)); } /** * Sets whether the tokenizer should return empty tokens as null. The default for this property is false. * * @param emptyAsNull * whether empty tokens are returned as null * @return this, to enable chaining */ public StringTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) { this.emptyAsNull = emptyAsNull; return this; } /** * Sets the character to ignore. * <p> * This character is ignored when parsing the String, unless it is within a quoted region. * </p> * * @param ignored * the ignored character to use * @return this, to enable chaining */ public StringTokenizer setIgnoredChar(final char ignored) { return setIgnoredMatcher(StringMatcherFactory.INSTANCE.charMatcher(ignored)); } /** * Sets the matcher for characters to ignore. * <p> * These characters are ignored when parsing the String, unless they are within a quoted region. * </p> * * @param ignored * the ignored matcher to use, null ignored * @return this, to enable chaining */ public StringTokenizer setIgnoredMatcher(final StringMatcher ignored) { if (ignored != null) { this.ignoredMatcher = ignored; } return this; } /** * Sets whether the tokenizer should ignore and not return empty tokens. The default for this property is true. * * @param ignoreEmptyTokens * whether empty tokens are not returned * @return this, to enable chaining */ public StringTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) { this.ignoreEmptyTokens = ignoreEmptyTokens; return this; } /** * Sets the quote character to use. * <p> * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. * </p> * * @param quote * the quote character to use * @return this, to enable chaining */ public StringTokenizer setQuoteChar(final char quote) { return setQuoteMatcher(StringMatcherFactory.INSTANCE.charMatcher(quote)); } /** * Sets the quote matcher to use. * <p> * The quote character is used to wrap data between the tokens. This enables delimiters to be entered as data. * </p> * * @param quote * the quote matcher to use, null ignored * @return this, to enable chaining */ public StringTokenizer setQuoteMatcher(final StringMatcher quote) { if (quote != null) { this.quoteMatcher = quote; } return this; } /** * Sets the matcher for characters to trim. * <p> * These characters are trimmed off on each side of the delimiter until the token or quote is found. * * @param trimmer * the trimmer matcher to use, null ignored * @return this, to enable chaining */ public StringTokenizer setTrimmerMatcher(final StringMatcher trimmer) { if (trimmer != null) { this.trimmerMatcher = trimmer; } return this; } /** * Gets the number of tokens found in the String. * * @return The number of matched tokens */ public int size() { checkTokenized(); return tokens.length; } /** * Internal method to performs the tokenization. * <p> * Most users of this class do not need to call this method. This method will be called automatically by other * (public) methods when required. * </p> * <p> * This method exists to allow subclasses to add code before or after the tokenization. For example, a subclass * could alter the character array, offset or count to be parsed, or call the tokenizer multiple times on multiple * strings. It is also be possible to filter the results. * </p> * <p> * {@code StrTokenizer} will always pass a zero offset and a count equal to the length of the array to this * method, however a subclass may pass other values, or even an entirely different array. * </p> * * @param srcChars * the character array being tokenized, may be null * @param offset * the start position within the character array, must be valid * @param count * the number of characters to tokenize, must be valid * @return The modifiable list of String tokens, unmodifiable if null array or zero count */ protected List<String> tokenize(final char[] srcChars, final int offset, final int count) { if (srcChars == null || count == 0) { return Collections.emptyList(); } final TextStringBuilder buf = new TextStringBuilder(); final List<String> tokenList = new ArrayList<>(); int pos = offset; // loop around the entire buffer while (pos >= 0 && pos < count) { // find next token pos = readNextToken(srcChars, pos, count, buf, tokenList); // handle case where end of string is a delimiter if (pos >= count) { addToken(tokenList, StringUtils.EMPTY); } } return tokenList; } /** * Gets the String content that the tokenizer is parsing. * * @return The string content being parsed */ @Override public String toString() { if (tokens == null) { return "StringTokenizer[not tokenized yet]"; } return "StringTokenizer" + getTokenList(); } }
googleapis/google-cloud-java
37,832
java-securesourcemanager/proto-google-cloud-securesourcemanager-v1/src/main/java/com/google/cloud/securesourcemanager/v1/UpdateIssueCommentRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/securesourcemanager/v1/secure_source_manager.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.securesourcemanager.v1; /** * * * <pre> * The request to update an issue comment. * </pre> * * Protobuf type {@code google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest} */ public final class UpdateIssueCommentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest) UpdateIssueCommentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateIssueCommentRequest.newBuilder() to construct. private UpdateIssueCommentRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateIssueCommentRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateIssueCommentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_UpdateIssueCommentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_UpdateIssueCommentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.class, com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.Builder.class); } private int bitField0_; public static final int ISSUE_COMMENT_FIELD_NUMBER = 1; private com.google.cloud.securesourcemanager.v1.IssueComment issueComment_; /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the issueComment field is set. */ @java.lang.Override public boolean hasIssueComment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The issueComment. */ @java.lang.Override public com.google.cloud.securesourcemanager.v1.IssueComment getIssueComment() { return issueComment_ == null ? com.google.cloud.securesourcemanager.v1.IssueComment.getDefaultInstance() : issueComment_; } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.securesourcemanager.v1.IssueCommentOrBuilder getIssueCommentOrBuilder() { return issueComment_ == null ? com.google.cloud.securesourcemanager.v1.IssueComment.getDefaultInstance() : issueComment_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getIssueComment()); } 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, getIssueComment()); } 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.securesourcemanager.v1.UpdateIssueCommentRequest)) { return super.equals(obj); } com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest other = (com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest) obj; if (hasIssueComment() != other.hasIssueComment()) return false; if (hasIssueComment()) { if (!getIssueComment().equals(other.getIssueComment())) 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 (hasIssueComment()) { hash = (37 * hash) + ISSUE_COMMENT_FIELD_NUMBER; hash = (53 * hash) + getIssueComment().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.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request to update an issue comment. * </pre> * * Protobuf type {@code google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest) com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_UpdateIssueCommentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_UpdateIssueCommentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.class, com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.Builder.class); } // Construct using // com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getIssueCommentFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; issueComment_ = null; if (issueCommentBuilder_ != null) { issueCommentBuilder_.dispose(); issueCommentBuilder_ = 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.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_UpdateIssueCommentRequest_descriptor; } @java.lang.Override public com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest getDefaultInstanceForType() { return com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest build() { com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest buildPartial() { com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest result = new com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.issueComment_ = issueCommentBuilder_ == null ? issueComment_ : issueCommentBuilder_.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.securesourcemanager.v1.UpdateIssueCommentRequest) { return mergeFrom((com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest other) { if (other == com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest.getDefaultInstance()) return this; if (other.hasIssueComment()) { mergeIssueComment(other.getIssueComment()); } 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(getIssueCommentFieldBuilder().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.securesourcemanager.v1.IssueComment issueComment_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.securesourcemanager.v1.IssueComment, com.google.cloud.securesourcemanager.v1.IssueComment.Builder, com.google.cloud.securesourcemanager.v1.IssueCommentOrBuilder> issueCommentBuilder_; /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the issueComment field is set. */ public boolean hasIssueComment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The issueComment. */ public com.google.cloud.securesourcemanager.v1.IssueComment getIssueComment() { if (issueCommentBuilder_ == null) { return issueComment_ == null ? com.google.cloud.securesourcemanager.v1.IssueComment.getDefaultInstance() : issueComment_; } else { return issueCommentBuilder_.getMessage(); } } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setIssueComment(com.google.cloud.securesourcemanager.v1.IssueComment value) { if (issueCommentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } issueComment_ = value; } else { issueCommentBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setIssueComment( com.google.cloud.securesourcemanager.v1.IssueComment.Builder builderForValue) { if (issueCommentBuilder_ == null) { issueComment_ = builderForValue.build(); } else { issueCommentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeIssueComment(com.google.cloud.securesourcemanager.v1.IssueComment value) { if (issueCommentBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && issueComment_ != null && issueComment_ != com.google.cloud.securesourcemanager.v1.IssueComment.getDefaultInstance()) { getIssueCommentBuilder().mergeFrom(value); } else { issueComment_ = value; } } else { issueCommentBuilder_.mergeFrom(value); } if (issueComment_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearIssueComment() { bitField0_ = (bitField0_ & ~0x00000001); issueComment_ = null; if (issueCommentBuilder_ != null) { issueCommentBuilder_.dispose(); issueCommentBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.securesourcemanager.v1.IssueComment.Builder getIssueCommentBuilder() { bitField0_ |= 0x00000001; onChanged(); return getIssueCommentFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.securesourcemanager.v1.IssueCommentOrBuilder getIssueCommentOrBuilder() { if (issueCommentBuilder_ != null) { return issueCommentBuilder_.getMessageOrBuilder(); } else { return issueComment_ == null ? com.google.cloud.securesourcemanager.v1.IssueComment.getDefaultInstance() : issueComment_; } } /** * * * <pre> * Required. The issue comment to update. * </pre> * * <code> * .google.cloud.securesourcemanager.v1.IssueComment issue_comment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.securesourcemanager.v1.IssueComment, com.google.cloud.securesourcemanager.v1.IssueComment.Builder, com.google.cloud.securesourcemanager.v1.IssueCommentOrBuilder> getIssueCommentFieldBuilder() { if (issueCommentBuilder_ == null) { issueCommentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.securesourcemanager.v1.IssueComment, com.google.cloud.securesourcemanager.v1.IssueComment.Builder, com.google.cloud.securesourcemanager.v1.IssueCommentOrBuilder>( getIssueComment(), getParentForChildren(), isClean()); issueComment_ = null; } return issueCommentBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Optional. Field mask is used to specify the fields to be overwritten in the * issue comment resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. A field will be overwritten if it is in the mask. * The special value "*" means full replacement. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest) private static final com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest(); } public static com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateIssueCommentRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateIssueCommentRequest>() { @java.lang.Override public UpdateIssueCommentRequest 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<UpdateIssueCommentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateIssueCommentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.securesourcemanager.v1.UpdateIssueCommentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graal
37,657
sdk/src/org.graalvm.jniutils/src/org/graalvm/jniutils/JNI.java
/* * Copyright (c) 2018, 2023, 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 org.graalvm.jniutils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.graalvm.nativeimage.ImageSingletons; import org.graalvm.nativeimage.c.CContext; import org.graalvm.nativeimage.c.function.CFunction.Transition; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.InvokeCFunctionPointer; import org.graalvm.nativeimage.c.struct.CField; import org.graalvm.nativeimage.c.struct.CPointerTo; import org.graalvm.nativeimage.c.struct.CStruct; import org.graalvm.nativeimage.c.type.CCharPointer; import org.graalvm.nativeimage.c.type.CDoublePointer; import org.graalvm.nativeimage.c.type.CFloatPointer; import org.graalvm.nativeimage.c.type.CIntPointer; import org.graalvm.nativeimage.c.type.CLongPointer; import org.graalvm.nativeimage.c.type.CShortPointer; import org.graalvm.nativeimage.c.type.VoidPointer; import org.graalvm.word.PointerBase; public final class JNI { public static final int JNI_OK = 0; public static final int JNI_ERR = -1; /* unknown error */ public static final int JNI_EDETACHED = -2; /* thread detached from the VM */ public static final int JNI_EVERSION = -3; /* JNI version error */ public static final int JNI_ENOMEM = -4; /* not enough memory */ public static final int JNI_EEXIST = -5; /* VM already created */ public static final int JNI_EINVAL = -6; /* invalid arguments */ public static final int JNI_VERSION_10 = 0x000a0000; private JNI() { throw new IllegalStateException("No instance allowed"); } public interface JMethodID extends PointerBase { } public interface JFieldID extends PointerBase { } public interface JObject extends PointerBase { } public interface JArray extends JObject { int MODE_WRITE_RELEASE = 0; int MODE_WRITE = 1; int MODE_RELEASE = 2; } public interface JBooleanArray extends JArray { } public interface JByteArray extends JArray { } public interface JCharArray extends JArray { } public interface JShortArray extends JArray { } public interface JIntArray extends JArray { } public interface JLongArray extends JArray { } public interface JFloatArray extends JArray { } public interface JDoubleArray extends JArray { } public interface JObjectArray extends JArray { } public interface JClass extends JObject { } public interface JString extends JObject { } public interface JThrowable extends JObject { } public interface JWeak extends JObject { } /** * Access to the {@code jvalue} JNI union. * * <pre> * typedef union jvalue { * jboolean z; * jbyte b; * jchar c; * jshort s; * jint i; * jlong j; * jfloat f; * jdouble d; * jobject l; * } jvalue; * </pre> */ @CContext(JNIHeaderDirectives.class) @CStruct("jvalue") public interface JValue extends PointerBase { // @formatter:off @CField("z") boolean getBoolean(); @CField("b") byte getByte(); @CField("c") char getChar(); @CField("s") short getShort(); @CField("i") int getInt(); @CField("j") long getLong(); @CField("f") float getFloat(); @CField("d") double getDouble(); @CField("l") JObject getJObject(); @CField("z") void setBoolean(boolean b); @CField("b") void setByte(byte b); @CField("c") void setChar(char ch); @CField("s") void setShort(short s); @CField("i") void setInt(int i); @CField("j") void setLong(long l); @CField("f") void setFloat(float f); @CField("d") void setDouble(double d); @CField("l") void setJObject(JObject obj); // @formatter:on /** * Gets JValue in an array of JValues pointed to by this object. */ JValue addressOf(int index); } @CContext(JNIHeaderDirectives.class) @CStruct(value = "JNIEnv_", addStructKeyword = true) public interface JNIEnv extends PointerBase { @CField("functions") JNINativeInterface getFunctions(); } @CPointerTo(JNIEnv.class) public interface JNIEnvPointer extends PointerBase { JNIEnv readJNIEnv(); void writeJNIEnv(JNIEnv env); } @CContext(JNIHeaderDirectives.class) @CStruct(value = "JNINativeInterface_", addStructKeyword = true) public interface JNINativeInterface extends PointerBase { @CField("NewString") NewString getNewString(); @CField("GetStringLength") GetStringLength getGetStringLength(); @CField("GetStringChars") GetStringChars getGetStringChars(); @CField("ReleaseStringChars") ReleaseStringChars getReleaseStringChars(); @CField("NewStringUTF") NewStringUTF8 getNewStringUTF(); @CField("GetStringUTFLength") GetStringUTFLength getGetStringUTFLength(); @CField("GetStringUTFChars") GetStringUTFChars getGetStringUTFChars(); @CField("ReleaseStringUTFChars") ReleaseStringUTFChars getReleaseStringUTFChars(); @CField("GetArrayLength") GetArrayLength getGetArrayLength(); @CField("NewLocalRef") NewLocalRef getNewLocalRef(); @CField("NewObjectArray") NewObjectArray getNewObjectArray(); @CField("NewBooleanArray") NewBooleanArray getNewBooleanArray(); @CField("NewByteArray") NewByteArray getNewByteArray(); @CField("NewCharArray") NewCharArray getNewCharArray(); @CField("NewShortArray") NewShortArray getNewShortArray(); @CField("NewIntArray") NewIntArray getNewIntArray(); @CField("NewLongArray") NewLongArray getNewLongArray(); @CField("NewFloatArray") NewFloatArray getNewFloatArray(); @CField("NewDoubleArray") NewDoubleArray getNewDoubleArray(); @CField("GetObjectArrayElement") GetObjectArrayElement getGetObjectArrayElement(); @CField("SetObjectArrayElement") SetObjectArrayElement getSetObjectArrayElement(); @CField("GetBooleanArrayElements") GetBooleanArrayElements getGetBooleanArrayElements(); @CField("GetByteArrayElements") GetByteArrayElements getGetByteArrayElements(); @CField("GetCharArrayElements") GetCharArrayElements getGetCharArrayElements(); @CField("GetShortArrayElements") GetShortArrayElements getGetShortArrayElements(); @CField("GetIntArrayElements") GetIntArrayElements getGetIntArrayElements(); @CField("GetLongArrayElements") GetLongArrayElements getGetLongArrayElements(); @CField("GetFloatArrayElements") GetFloatArrayElements getGetFloatArrayElements(); @CField("GetDoubleArrayElements") GetDoubleArrayElements getGetDoubleArrayElements(); @CField("ReleaseBooleanArrayElements") ReleaseBooleanArrayElements getReleaseBooleanArrayElements(); @CField("ReleaseByteArrayElements") ReleaseByteArrayElements getReleaseByteArrayElements(); @CField("ReleaseCharArrayElements") ReleaseCharArrayElements getReleaseCharArrayElements(); @CField("ReleaseShortArrayElements") ReleaseShortArrayElements getReleaseShortArrayElements(); @CField("ReleaseIntArrayElements") ReleaseIntArrayElements getReleaseIntArrayElements(); @CField("ReleaseLongArrayElements") ReleaseLongArrayElements getReleaseLongArrayElements(); @CField("ReleaseFloatArrayElements") ReleaseFloatArrayElements getReleaseFloatArrayElements(); @CField("ReleaseDoubleArrayElements") ReleaseDoubleArrayElements getReleaseDoubleArrayElements(); @CField("GetBooleanArrayRegion") GetBooleanArrayRegion getGetBooleanArrayRegion(); @CField("GetByteArrayRegion") GetByteArrayRegion getGetByteArrayRegion(); @CField("GetCharArrayRegion") GetCharArrayRegion getGetCharArrayRegion(); @CField("GetShortArrayRegion") GetShortArrayRegion getGetShortArrayRegion(); @CField("GetIntArrayRegion") GetIntArrayRegion getGetIntArrayRegion(); @CField("GetLongArrayRegion") GetLongArrayRegion getGetLongArrayRegion(); @CField("GetFloatArrayRegion") GetFloatArrayRegion getGetFloatArrayRegion(); @CField("GetDoubleArrayRegion") GetDoubleArrayRegion getGetDoubleArrayRegion(); @CField("SetBooleanArrayRegion") SetBooleanArrayRegion getSetBooleanArrayRegion(); @CField("SetByteArrayRegion") SetByteArrayRegion getSetByteArrayRegion(); @CField("SetCharArrayRegion") SetCharArrayRegion getSetCharArrayRegion(); @CField("SetShortArrayRegion") SetShortArrayRegion getSetShortArrayRegion(); @CField("SetIntArrayRegion") SetIntArrayRegion getSetIntArrayRegion(); @CField("SetLongArrayRegion") SetLongArrayRegion getSetLongArrayRegion(); @CField("SetFloatArrayRegion") SetFloatArrayRegion getSetFloatArrayRegion(); @CField("SetDoubleArrayRegion") SetDoubleArrayRegion getSetDoubleArrayRegion(); @CField("FindClass") FindClass getFindClass(); @CField("DefineClass") DefineClass getDefineClass(); @CField("IsSameObject") IsSameObject getIsSameObject(); @CField("GetObjectClass") GetObjectClass getGetObjectClass(); @CField("NewGlobalRef") NewGlobalRef getNewGlobalRef(); @CField("DeleteGlobalRef") DeleteGlobalRef getDeleteGlobalRef(); @CField("NewWeakGlobalRef") NewWeakGlobalRef getNewWeakGlobalRef(); @CField("DeleteWeakGlobalRef") DeleteWeakGlobalRef getDeleteWeakGlobalRef(); @CField("DeleteLocalRef") DeleteLocalRef getDeleteLocalRef(); @CField("PushLocalFrame") PushLocalFrame getPushLocalFrame(); @CField("PopLocalFrame") PopLocalFrame getPopLocalFrame(); @CField("NewObjectA") NewObjectA getNewObjectA(); @CField("GetStaticMethodID") GetStaticMethodID getGetStaticMethodID(); @CField("GetMethodID") GetMethodID getGetMethodID(); @CField("GetStaticFieldID") GetStaticFieldID getGetStaticFieldID(); @CField("GetFieldID") GetFieldID getGetFieldID(); @CField("CallStaticBooleanMethodA") CallStaticBooleanMethodA getCallStaticBooleanMethodA(); @CField("CallStaticIntMethodA") CallStaticIntMethodA getCallStaticIntMethodA(); @CField("CallStaticVoidMethodA") CallStaticVoidMethodA getCallStaticVoidMethodA(); @CField("CallStaticObjectMethodA") CallStaticObjectMethodA getCallStaticObjectMethodA(); @CField("CallStaticLongMethodA") CallStaticLongMethodA getCallStaticLongMethodA(); @CField("CallObjectMethodA") CallObjectMethodA getCallObjectMethodA(); @CField("CallVoidMethodA") CallVoidMethodA getCallVoidMethodA(); @CField("CallBooleanMethodA") CallBooleanMethodA getCallBooleanMethodA(); @CField("CallShortMethodA") CallShortMethodA getCallShortMethodA(); @CField("CallIntMethodA") CallIntMethodA getCallIntMethodA(); @CField("CallLongMethodA") CallLongMethodA getCallLongMethodA(); @CField("CallDoubleMethodA") CallDoubleMethodA getCallDoubleMethodA(); @CField("CallFloatMethodA") CallFloatMethodA getCallFloatMethodA(); @CField("CallByteMethodA") CallByteMethodA getCallByteMethodA(); @CField("CallCharMethodA") CallCharMethodA getCallCharMethodA(); @CField("GetStaticObjectField") GetStaticObjectField getGetStaticObjectField(); @CField("GetIntField") GetIntField getGetIntField(); @CField("GetStaticBooleanField") GetStaticBooleanField getGetStaticBooleanField(); @CField("SetStaticBooleanField") SetStaticBooleanField getSetStaticBooleanField(); @CField("ExceptionCheck") ExceptionCheck getExceptionCheck(); @CField("ExceptionOccurred") ExceptionOccurred getExceptionOccurred(); @CField("ExceptionClear") ExceptionClear getExceptionClear(); @CField("ExceptionDescribe") ExceptionDescribe getExceptionDescribe(); @CField("Throw") Throw getThrow(); @CField("GetObjectRefType") GetObjectRefType getGetObjectRefType(); @CField("GetDirectBufferAddress") GetDirectBufferAddress getGetDirectBufferAddress(); @CField("IsInstanceOf") IsInstanceOf getIsInstanceOf(); @CField("GetJavaVM") GetJavaVM getGetJavaVM(); } @CContext(JNIHeaderDirectives.class) @CStruct(value = "JavaVM_", addStructKeyword = true) public interface JavaVM extends PointerBase { @CField("functions") JNIInvokeInterface getFunctions(); } @CPointerTo(JavaVM.class) public interface JavaVMPointer extends PointerBase { JavaVM readJavaVM(); void writeJavaVM(JavaVM javaVM); } @CContext(JNIHeaderDirectives.class) @CStruct(value = "JavaVMAttachArgs", addStructKeyword = true) public interface JavaVMAttachArgs extends PointerBase { @CField("version") int getVersion(); @CField("version") void setVersion(int version); @CField("name") CCharPointer getName(); @CField("name") void setName(CCharPointer name); @CField("group") JObject getGroup(); @CField("group") void setGroup(JObject group); } @CContext(JNIHeaderDirectives.class) @CStruct(value = "JNIInvokeInterface_", addStructKeyword = true) public interface JNIInvokeInterface extends PointerBase { @CField("AttachCurrentThread") AttachCurrentThread getAttachCurrentThread(); @CField("AttachCurrentThreadAsDaemon") AttachCurrentThreadAsDaemon getAttachCurrentThreadAsDaemon(); @CField("DetachCurrentThread") DetachCurrentThread getDetachCurrentThread(); @CField("GetEnv") GetEnv getGetEnv(); } public interface CallStaticIntMethodA extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); } public interface CallStaticBooleanMethodA extends CFunctionPointer { @InvokeCFunctionPointer boolean call(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); } public interface CallStaticVoidMethodA extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); } public interface CallStaticObjectMethodA extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) JObject callNoTransition(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); } public interface CallStaticLongMethodA extends CFunctionPointer { @InvokeCFunctionPointer long call(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); } public interface CallObjectMethodA extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JObject object, JMethodID methodID, JValue args); } public interface CallVoidMethodA extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallBooleanMethodA extends CFunctionPointer { @InvokeCFunctionPointer boolean call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallShortMethodA extends CFunctionPointer { @InvokeCFunctionPointer short call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallIntMethodA extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallLongMethodA extends CFunctionPointer { @InvokeCFunctionPointer long call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallDoubleMethodA extends CFunctionPointer { @InvokeCFunctionPointer double call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallFloatMethodA extends CFunctionPointer { @InvokeCFunctionPointer float call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallByteMethodA extends CFunctionPointer { @InvokeCFunctionPointer byte call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface CallCharMethodA extends CFunctionPointer { @InvokeCFunctionPointer char call(JNIEnv env, JObject o, JMethodID methodID, JValue args); } public interface DeleteGlobalRef extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JObject gref); } public interface DeleteWeakGlobalRef extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JWeak wref); } public interface DeleteLocalRef extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JObject lref); } public interface PushLocalFrame extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, int capacity); } public interface PopLocalFrame extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JObject result); } public interface ExceptionCheck extends CFunctionPointer { @InvokeCFunctionPointer boolean call(JNIEnv env); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) boolean callNoTransition(JNIEnv env); } public interface ExceptionClear extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env); } public interface ExceptionDescribe extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) void callNoTransition(JNIEnv env); } public interface ExceptionOccurred extends CFunctionPointer { @InvokeCFunctionPointer JThrowable call(JNIEnv env); } public interface FindClass extends CFunctionPointer { @InvokeCFunctionPointer JClass call(JNIEnv env, CCharPointer name); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) JClass callNoTransition(JNIEnv env, CCharPointer name); } public interface DefineClass extends CFunctionPointer { @InvokeCFunctionPointer JClass call(JNIEnv env, CCharPointer name, JObject loader, CCharPointer buf, long bufLen); } public interface GetArrayLength extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JArray array); } public interface GetBooleanArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CCharPointer call(JNIEnv env, JBooleanArray array, JValue isCopy); } public interface GetByteArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CCharPointer call(JNIEnv env, JByteArray array, JValue isCopy); } public interface GetCharArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CShortPointer call(JNIEnv env, JCharArray array, JValue isCopy); } public interface GetShortArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CShortPointer call(JNIEnv env, JShortArray array, JValue isCopy); } public interface GetIntArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CIntPointer call(JNIEnv env, JIntArray array, JValue isCopy); } public interface GetLongArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CLongPointer call(JNIEnv env, JLongArray array, JValue isCopy); } public interface GetFloatArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CFloatPointer call(JNIEnv env, JFloatArray array, JValue isCopy); } public interface GetDoubleArrayElements extends CFunctionPointer { @InvokeCFunctionPointer CDoublePointer call(JNIEnv env, JDoubleArray array, JValue isCopy); } public interface GetMethodID extends CFunctionPointer { @InvokeCFunctionPointer JMethodID call(JNIEnv env, JClass clazz, CCharPointer name, CCharPointer sig); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) JMethodID callNoTransition(JNIEnv env, JClass clazz, CCharPointer name, CCharPointer sig); } public interface GetObjectArrayElement extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JObjectArray array, int index); } public interface GetObjectClass extends CFunctionPointer { @InvokeCFunctionPointer JClass call(JNIEnv env, JObject object); } public interface GetObjectRefType extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JObject obj); } public interface GetStaticMethodID extends CFunctionPointer { @InvokeCFunctionPointer JMethodID call(JNIEnv env, JClass clazz, CCharPointer name, CCharPointer sig); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) JMethodID callNoTransition(JNIEnv env, JClass clazz, CCharPointer name, CCharPointer sig); } public interface GetStringChars extends CFunctionPointer { @InvokeCFunctionPointer CShortPointer call(JNIEnv env, JString string, JValue isCopy); } public interface GetStringLength extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JString string); } public interface GetStringUTFChars extends CFunctionPointer { @InvokeCFunctionPointer CCharPointer call(JNIEnv env, JString string, JValue isCopy); } public interface GetStringUTFLength extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JString str); } public interface IsSameObject extends CFunctionPointer { @InvokeCFunctionPointer boolean call(JNIEnv env, JObject ref1, JObject ref2); } public interface NewBooleanArray extends CFunctionPointer { @InvokeCFunctionPointer JBooleanArray call(JNIEnv env, int len); } public interface NewByteArray extends CFunctionPointer { @InvokeCFunctionPointer JByteArray call(JNIEnv env, int len); } public interface NewCharArray extends CFunctionPointer { @InvokeCFunctionPointer JCharArray call(JNIEnv env, int len); } public interface NewShortArray extends CFunctionPointer { @InvokeCFunctionPointer JShortArray call(JNIEnv env, int len); } public interface NewIntArray extends CFunctionPointer { @InvokeCFunctionPointer JIntArray call(JNIEnv env, int len); } public interface NewLongArray extends CFunctionPointer { @InvokeCFunctionPointer JLongArray call(JNIEnv env, int len); } public interface NewFloatArray extends CFunctionPointer { @InvokeCFunctionPointer JFloatArray call(JNIEnv env, int len); } public interface NewDoubleArray extends CFunctionPointer { @InvokeCFunctionPointer JDoubleArray call(JNIEnv env, int len); } public interface NewGlobalRef extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JObject lobj); } public interface NewWeakGlobalRef extends CFunctionPointer { @InvokeCFunctionPointer JWeak call(JNIEnv env, JObject lobj); } public interface NewObjectA extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) JObject callNoTransition(JNIEnv env, JClass clazz, JMethodID methodID, JValue args); } public interface NewLocalRef extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JObject obj); } public interface NewObjectArray extends CFunctionPointer { @InvokeCFunctionPointer JObjectArray call(JNIEnv env, int len, JClass clazz, JObject init); } public interface NewString extends CFunctionPointer { @InvokeCFunctionPointer JString call(JNIEnv env, CShortPointer unicode, int len); } public interface NewStringUTF8 extends CFunctionPointer { @InvokeCFunctionPointer JString call(JNIEnv env, CCharPointer bytes); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) JString callNoTransition(JNIEnv env, CCharPointer bytes); } public interface ReleaseBooleanArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JBooleanArray array, CCharPointer elems, int mode); } public interface ReleaseByteArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JByteArray array, CCharPointer elems, int mode); } public interface ReleaseCharArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JCharArray array, CShortPointer elems, int mode); } public interface ReleaseShortArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JShortArray array, CShortPointer elems, int mode); } public interface ReleaseIntArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JIntArray array, CIntPointer elems, int mode); } public interface ReleaseLongArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JLongArray array, CLongPointer elems, int mode); } public interface ReleaseFloatArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JFloatArray array, CFloatPointer elems, int mode); } public interface ReleaseDoubleArrayElements extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JDoubleArray array, CDoublePointer elems, int mode); } public interface GetBooleanArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JBooleanArray array, int start, int len, CCharPointer buf); } public interface GetByteArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JByteArray array, int start, int len, CCharPointer buf); } public interface GetCharArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JCharArray array, int start, int len, CShortPointer buf); } public interface GetShortArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JShortArray array, int start, int len, CShortPointer buf); } public interface GetIntArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JIntArray array, int start, int len, CIntPointer buf); } public interface GetLongArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JLongArray array, int start, int len, CLongPointer buf); } public interface GetFloatArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JFloatArray array, int start, int len, CFloatPointer buf); } public interface GetDoubleArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JDoubleArray array, int start, int len, CDoublePointer buf); } public interface SetBooleanArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JBooleanArray array, int start, int len, CCharPointer buf); } public interface SetByteArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JByteArray array, int start, int len, CCharPointer buf); } public interface SetCharArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JCharArray array, int start, int len, CShortPointer buf); } public interface SetShortArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JShortArray array, int start, int len, CShortPointer buf); } public interface SetIntArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JIntArray array, int start, int len, CIntPointer buf); } public interface SetLongArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JLongArray array, int start, int len, CLongPointer buf); } public interface SetFloatArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JFloatArray array, int start, int len, CFloatPointer buf); } public interface SetDoubleArrayRegion extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JDoubleArray array, int start, int len, CDoublePointer buf); } public interface ReleaseStringChars extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JString string, CShortPointer chars); } public interface ReleaseStringUTFChars extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JString string, CCharPointer chars); } public interface SetObjectArrayElement extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JObjectArray array, int index, JObject val); } public interface Throw extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JThrowable throwable); @InvokeCFunctionPointer(transition = Transition.NO_TRANSITION) int callNoTransition(JNIEnv env, JThrowable throwable); } public interface GetDirectBufferAddress extends CFunctionPointer { @InvokeCFunctionPointer VoidPointer call(JNIEnv env, JObject buf); } public interface IsInstanceOf extends CFunctionPointer { @InvokeCFunctionPointer boolean call(JNIEnv env, JObject o, JClass c); } public interface GetStaticFieldID extends CFunctionPointer { @InvokeCFunctionPointer JFieldID call(JNIEnv env, JClass clazz, CCharPointer name, CCharPointer sig); } public interface GetFieldID extends CFunctionPointer { @InvokeCFunctionPointer JFieldID call(JNIEnv env, JClass c, CCharPointer name, CCharPointer sig); } public interface GetStaticObjectField extends CFunctionPointer { @InvokeCFunctionPointer JObject call(JNIEnv env, JClass clazz, JFieldID fieldID); } public interface GetIntField extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JObject o, JFieldID fieldId); } public interface GetStaticBooleanField extends CFunctionPointer { @InvokeCFunctionPointer boolean call(JNIEnv env, JClass clazz, JFieldID fieldID); } public interface SetStaticBooleanField extends CFunctionPointer { @InvokeCFunctionPointer void call(JNIEnv env, JClass clazz, JFieldID fieldID, boolean value); } public interface GetJavaVM extends CFunctionPointer { @InvokeCFunctionPointer int call(JNIEnv env, JavaVMPointer javaVMOut); } public interface AttachCurrentThread extends CFunctionPointer { @InvokeCFunctionPointer int call(JavaVM vm, JNIEnvPointer envOut, JavaVMAttachArgs args); } public interface AttachCurrentThreadAsDaemon extends CFunctionPointer { @InvokeCFunctionPointer int call(JavaVM vm, JNIEnvPointer envOut, JavaVMAttachArgs args); } public interface DetachCurrentThread extends CFunctionPointer { @InvokeCFunctionPointer int call(JavaVM vm); } public interface GetEnv extends CFunctionPointer { @InvokeCFunctionPointer int call(JavaVM vm, JNIEnvPointer envOut, int version); } static class JNIHeaderDirectives implements CContext.Directives { private static final String[] INCLUDES = {"jni.h", "jni_md.h"}; @Override public boolean isInConfiguration() { return ImageSingletons.contains(NativeBridgeSupport.class); } @Override public List<String> getOptions() { return Arrays.stream(findJNIHeaders()).map((p) -> "-I" + p.getParent()).collect(Collectors.toList()); } @Override public List<String> getHeaderFiles() { return Arrays.stream(findJNIHeaders()).map((p) -> '<' + p.toString() + '>').collect(Collectors.toList()); } private static Path[] findJNIHeaders() { Path javaHome = Paths.get(System.getProperty("java.home")); Path includeFolder = javaHome.resolve("include"); if (!Files.exists(includeFolder)) { Path parent = javaHome.getParent(); if (parent != null) { javaHome = parent; } } includeFolder = javaHome.resolve("include"); if (!Files.exists(includeFolder)) { throw new IllegalStateException("Cannot find 'include' folder in JDK."); } Path[] res = new Path[INCLUDES.length]; try { for (int i = 0; i < INCLUDES.length; i++) { String include = INCLUDES[i]; Optional<Path> includeFile = Files.find(includeFolder, 2, (p, attrs) -> include.equals(p.getFileName().toString())).findFirst(); if (!includeFile.isPresent()) { throw new IllegalStateException("Include: " + res[i] + " does not exist."); } res[i] = includeFile.get(); } return res; } catch (IOException ioe) { throw new RuntimeException(ioe); } } } }
apache/tinkerpop
38,212
gremlin-groovy/src/main/java/org/apache/tinkerpop/gremlin/groovy/engine/GremlinExecutor.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.tinkerpop.gremlin.groovy.engine; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.tinkerpop.gremlin.jsr223.CachedGremlinScriptEngineManager; import org.apache.tinkerpop.gremlin.jsr223.ConcurrentBindings; import org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin; import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptChecker; import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngine; import org.apache.tinkerpop.gremlin.jsr223.GremlinScriptEngineManager; import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalInterruptedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptException; import javax.script.SimpleBindings; import java.io.InterruptedIOException; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Stream; /** * Execute Gremlin scripts against a {@code ScriptEngine} instance. It is designed to host any JSR-223 enabled * {@code ScriptEngine} and assumes such engines are designed to be thread-safe in the evaluation. Script evaluation * functions return a {@link CompletableFuture} where scripts may timeout if their evaluation * takes too long. The default timeout is 8000ms. * <p/> * By default, the {@code GremlinExecutor} initializes itself to use a shared thread pool initialized with four * threads. This default thread pool is shared for both the task of executing script evaluations and for scheduling * timeouts. It is worth noting that a timeout simply triggers the returned {@link CompletableFuture} to abort, but * the thread processing the script will continue to evaluate until completion. This offers only marginal protection * against run-away scripts. * * @author Stephen Mallette (http://stephen.genoprime.com) */ public class GremlinExecutor implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GremlinExecutor.class); private GremlinScriptEngineManager gremlinScriptEngineManager; private final Map<String, Map<String, Map<String,Object>>> plugins; private final long evaluationTimeout; private final Bindings globalBindings; private final ExecutorService executorService; private final ScheduledExecutorService scheduledExecutorService; private final Consumer<Bindings> beforeEval; private final Consumer<Bindings> afterSuccess; private final BiConsumer<Bindings, Throwable> afterTimeout; private final BiConsumer<Bindings, Throwable> afterFailure; private final boolean suppliedExecutor; private final boolean suppliedScheduledExecutor; private GremlinExecutor(final Builder builder, final boolean suppliedExecutor, final boolean suppliedScheduledExecutor) { this.executorService = builder.executorService; this.scheduledExecutorService = builder.scheduledExecutorService; this.beforeEval = builder.beforeEval; this.afterSuccess = builder.afterSuccess; this.afterTimeout = builder.afterTimeout; this.afterFailure = builder.afterFailure; this.plugins = builder.plugins; this.evaluationTimeout = builder.evaluationTimeout; this.globalBindings = builder.globalBindings; this.gremlinScriptEngineManager = new CachedGremlinScriptEngineManager(); initializeGremlinScriptEngineManager(); this.suppliedExecutor = suppliedExecutor; this.suppliedScheduledExecutor = suppliedScheduledExecutor; } /** * Attempts to compile a script and cache it in the default {@link javax.script.ScriptEngine}. This is only * possible if the {@link javax.script.ScriptEngine} implementation implements {@link javax.script.Compilable}. * In the event that the default {@link javax.script.ScriptEngine} does not implement it, the method will * return empty. */ public Optional<CompiledScript> compile(final String script) throws ScriptException { return compile(script, Optional.empty()); } /** * Attempts to compile a script and cache it in the request {@link javax.script.ScriptEngine}. This is only * possible if the {@link javax.script.ScriptEngine} implementation implements {@link Compilable}. * In the event that the requested {@link javax.script.ScriptEngine} does not implement it, the method will * return empty. */ public Optional<CompiledScript> compile(final String script, final Optional<String> language) throws ScriptException { final String lang = language.orElse("gremlin-groovy"); try { final GremlinScriptEngine scriptEngine = gremlinScriptEngineManager.getEngineByName(lang); if (scriptEngine instanceof Compilable) return Optional.of(((Compilable) scriptEngine).compile(script)); else return Optional.empty(); } catch (UnsupportedOperationException uoe) { return Optional.empty(); } } /** * Evaluate a script with empty bindings. */ public CompletableFuture<Object> eval(final String script) { return eval(script, null, new SimpleBindings()); } /** * Evaluate a script with specified bindings. */ public CompletableFuture<Object> eval(final String script, final Bindings boundVars) { return eval(script, null, boundVars); } /** * Evaluate a script with a {@link Map} of bindings. */ public CompletableFuture<Object> eval(final String script, final Map<String, Object> boundVars) { return eval(script, null, new SimpleBindings(boundVars)); } /** * Evaluate a script. * * @param script the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings as a {@link Map} to evaluate in the context of the script */ public CompletableFuture<Object> eval(final String script, final String language, final Map<String, Object> boundVars) { return eval(script, language, new SimpleBindings(boundVars)); } /** * Evaluate a script. * * @param script the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script */ public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars) { return eval(script, language, boundVars, null, null, null); } /** * Evaluate a script and allow for the submission of a transform {@link Function} that will transform the * result after script evaluates but before transaction commit and before the returned {@link CompletableFuture} * is completed. * * @param gremlin the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param transformResult a {@link Function} that transforms the result - can be {@code null} */ public CompletableFuture<Object> eval(final String gremlin, final String language, final Map<String, Object> boundVars, final Function<Object, Object> transformResult) { return eval(gremlin, language, new SimpleBindings(boundVars), transformResult, null); } /** * Evaluate a script and allow for the submission of a transform {@link Function} that will transform the * result after script evaluates but before transaction commit and before the returned {@link CompletableFuture} * is completed. * * @param gremlin the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param timeOut optional override for evaluation timeout * @param transformResult a {@link Function} that transforms the result - can be {@code null} */ public CompletableFuture<Object> eval(final String gremlin, final String language, final Map<String, Object> boundVars, final Long timeOut, final Function<Object, Object> transformResult) { return eval(gremlin, language, new SimpleBindings(boundVars), timeOut, transformResult, null); } /** * Evaluate a script and allow for the submission of a {@link Consumer} that will take the result for additional * processing after the script evaluates and after the {@link CompletableFuture} is completed, but before the * transaction is committed. * * @param script the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param withResult a {@link Consumer} that accepts the result - can be {@code null} */ public CompletableFuture<Object> eval(final String script, final String language, final Map<String, Object> boundVars, final Consumer<Object> withResult) { return eval(script, language, new SimpleBindings(boundVars), null, withResult); } /** * Evaluate a script and allow for the submission of both a transform {@link Function} and {@link Consumer}. * The {@link Function} will transform the result after script evaluates but before transaction commit and before * the returned {@link CompletableFuture} is completed. The {@link Consumer} will take the result for additional * processing after the script evaluates and after the {@link CompletableFuture} is completed, but before the * transaction is committed. * * @param gremlin the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param transformResult a {@link Function} that transforms the result - can be {@code null} * @param withResult a {@link Consumer} that accepts the result - can be {@code null} */ public CompletableFuture<Object> eval(final String gremlin, final String language, final Bindings boundVars, final Function<Object, Object> transformResult, final Consumer<Object> withResult) { return eval(gremlin, language, boundVars, null, transformResult, withResult); } /** * Evaluate a script and allow for the submission of both a transform {@link Function} and {@link Consumer}. * The {@link Function} will transform the result after script evaluates but before transaction commit and before * the returned {@link CompletableFuture} is completed. The {@link Consumer} will take the result for additional * processing after the script evaluates and after the {@link CompletableFuture} is completed, but before the * transaction is committed. * * @param gremlin the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param timeOut optional override for evaluation timeout * @param transformResult a {@link Function} that transforms the result - can be {@code null} * @param withResult a {@link Consumer} that accepts the result - can be {@code null} */ public CompletableFuture<Object> eval(final String gremlin, final String language, final Bindings boundVars, final Long timeOut, final Function<Object, Object> transformResult, final Consumer<Object> withResult) { final LifeCycle lifeCycle = LifeCycle.build() .evaluationTimeoutOverride(timeOut) .transformResult(transformResult) .withResult(withResult).create(); return eval(gremlin, language, boundVars, lifeCycle); } /** * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle. * * @param gremlin the script to evaluate * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process */ public CompletableFuture<Object> eval(final String gremlin, final String language, final Bindings boundVars, final LifeCycle lifeCycle) { final String lang = Optional.ofNullable(language).orElse("gremlin-groovy"); if (logger.isDebugEnabled()) { logger.debug("Preparing to evaluate script - {} - in thread [{}]", gremlin, Thread.currentThread().getName()); } final Bindings bindings = new SimpleBindings(); bindings.putAll(globalBindings); bindings.putAll(boundVars); // override the timeout if the lifecycle has a value assigned. if the script contains with(timeout) // options then allow that value to override what's provided on the lifecycle final Optional<Long> timeoutDefinedInScript = GremlinScriptChecker.parse(gremlin).getTimeout(); final long scriptEvalTimeOut = timeoutDefinedInScript.orElse( lifeCycle.getEvaluationTimeoutOverride().orElse(evaluationTimeout)); final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>(); final FutureTask<Void> evalFuture = new FutureTask<>(() -> { try { lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings); logger.debug("Evaluating script - {} - in thread [{}]", gremlin, Thread.currentThread().getName()); final Object o =gremlinScriptEngineManager.getEngineByName(lang).eval(gremlin, bindings); // apply a transformation before sending back the result - useful when trying to force serialization // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some // transactional constraints final Object result = lifeCycle.getTransformResult().isPresent() ? lifeCycle.getTransformResult().get().apply(o) : o; // a mechanism for taking the final result and doing something with it in the same thread, but // AFTER the eval and transform are done and that future completed. this provides a final means // for working with the result in the same thread as it was eval'd if (lifeCycle.getWithResult().isPresent()) lifeCycle.getWithResult().get().accept(result); lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings); // the evaluationFuture must be completed after all processing as an exception in lifecycle events // that must raise as an exception to the caller who has the returned evaluationFuture. in other words, // if it occurs before this point, then the handle() method won't be called again if there is an // exception that ends up below trying to completeExceptionally() evaluationFuture.complete(result); } catch (Throwable ex) { final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex); // thread interruptions will typically come as the result of a timeout, so in those cases, // check for that situation and convert to TimeoutException if (root instanceof InterruptedException || root instanceof TraversalInterruptedException || root instanceof InterruptedIOException) { lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings, root); evaluationFuture.completeExceptionally(new TimeoutException( String.format("Evaluation exceeded the configured 'evaluationTimeout' threshold of %s ms or evaluation was otherwise cancelled directly for request [%s]: %s", scriptEvalTimeOut, gremlin, root.getMessage()))); } else { lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root); evaluationFuture.completeExceptionally(root); } } return null; }); final WeakReference<CompletableFuture<Object>> evaluationFutureRef = new WeakReference<>(evaluationFuture); final Future<?> executionFuture = executorService.submit(evalFuture); if (scriptEvalTimeOut > 0) { // Schedule a timeout in the thread pool for future execution final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> { if (executionFuture.cancel(true)) { final CompletableFuture<Object> ef = evaluationFutureRef.get(); if (ef != null) { ef.completeExceptionally(new TimeoutException( String.format("Evaluation exceeded the configured 'evaluationTimeout' threshold of %s ms or evaluation was otherwise cancelled directly for request [%s]", scriptEvalTimeOut, gremlin))); } } }, scriptEvalTimeOut, TimeUnit.MILLISECONDS); // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed with exception evaluationFuture.handleAsync((v, t) -> { if (!sf.isDone()) { logger.debug("Killing scheduled timeout on script evaluation - {} - as the eval completed (possibly with exception).", gremlin); sf.cancel(true); } // no return is necessary - nothing downstream is concerned with what happens in here return null; }, scheduledExecutorService); } return evaluationFuture; } public GremlinScriptEngineManager getScriptEngineManager() { return this.gremlinScriptEngineManager; } public ExecutorService getExecutorService() { return executorService; } public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } /** * {@inheritDoc} * <p/> * Executors are only closed if they were not supplied externally in the {@link GremlinExecutor.Builder} */ @Override public void close() throws Exception { closeAsync().join(); } /** * Executors are only closed if they were not supplied externally in the {@link GremlinExecutor.Builder} */ public CompletableFuture<Void> closeAsync() throws Exception { final CompletableFuture<Void> future = new CompletableFuture<>(); new Thread(() -> { // leave pools running if they are supplied externally. let the sender be responsible for shutting them down if (!suppliedExecutor) { executorService.shutdown(); try { if (!executorService.awaitTermination(180000, TimeUnit.MILLISECONDS)) logger.warn("Timeout while waiting for ExecutorService of GremlinExecutor to shutdown."); } catch (InterruptedException ie) { logger.warn("ExecutorService on GremlinExecutor may not have shutdown properly as shutdown thread terminated early."); } } // calls to shutdown are idempotent so no problems calling it twice if the pool is shared if (!suppliedScheduledExecutor) { scheduledExecutorService.shutdown(); try { if (!scheduledExecutorService.awaitTermination(180000, TimeUnit.MILLISECONDS)) logger.warn("Timeout while waiting for ScheduledExecutorService of GremlinExecutor to shutdown."); } catch (InterruptedException ie) { logger.warn("ScheduledExecutorService on GremlinExecutor may not have shutdown properly as shutdown thread terminated early."); } } future.complete(null); }, "gremlin-executor-close").start(); return future; } private void initializeGremlinScriptEngineManager() { for (Map.Entry<String, Map<String, Map<String,Object>>> config : plugins.entrySet()) { final String language = config.getKey(); final Map<String, Map<String,Object>> pluginConfigs = config.getValue(); for (Map.Entry<String, Map<String,Object>> pluginConfig : pluginConfigs.entrySet()) { try { final Class<?> clazz = Class.forName(pluginConfig.getKey()); // first try instance() and if that fails try to use build() try { final Method instanceMethod = clazz.getMethod("instance"); gremlinScriptEngineManager.addPlugin((GremlinPlugin) instanceMethod.invoke(null)); } catch (Exception ex) { final Method builderMethod = clazz.getMethod("build"); Object pluginBuilder = builderMethod.invoke(null); final Class<?> builderClazz = pluginBuilder.getClass(); final Map<String, Object> customizerConfigs = pluginConfig.getValue(); final Method[] methods = builderClazz.getMethods(); for (Map.Entry<String, Object> customizerConfig : customizerConfigs.entrySet()) { final Method configMethod = Stream.of(methods).filter(m -> { final Class<?> type = customizerConfig.getValue().getClass(); return m.getName().equals(customizerConfig.getKey()) && m.getParameters().length <= 1 && ClassUtils.isAssignable(type, m.getParameters()[0].getType(), true); }).findFirst() .orElseThrow(() -> new IllegalStateException("Could not find builder method '" + customizerConfig.getKey() + "' on " + builderClazz.getCanonicalName())); if (null == customizerConfig.getValue()) pluginBuilder = configMethod.invoke(pluginBuilder); else pluginBuilder = configMethod.invoke(pluginBuilder, customizerConfig.getValue()); } try { final Method appliesTo = builderClazz.getMethod("appliesTo", Collection.class); pluginBuilder = appliesTo.invoke(pluginBuilder, Collections.singletonList(language)); } catch (NoSuchMethodException ignored) { } final Method create = builderClazz.getMethod("create"); gremlinScriptEngineManager.addPlugin((GremlinPlugin) create.invoke(pluginBuilder)); } } catch (Exception ex) { throw new IllegalStateException(ex); } } } gremlinScriptEngineManager.setBindings(globalBindings); } /** * Create a {@code Builder} with the gremlin-groovy ScriptEngine configured. */ public static Builder build() { return new Builder(); } public final static class Builder { private long evaluationTimeout = 8000; private Map<String, Map<String, Map<String,Object>>> plugins = new HashMap<>(); private ExecutorService executorService = null; private ScheduledExecutorService scheduledExecutorService = null; private Consumer<Bindings> beforeEval = (b) -> { }; private Consumer<Bindings> afterSuccess = (b) -> { }; private BiConsumer<Bindings, Throwable> afterTimeout = (b, e) -> { }; private BiConsumer<Bindings, Throwable> afterFailure = (b, e) -> { }; private Bindings globalBindings = new ConcurrentBindings(); private Builder() { } /** * Add a configuration for a {@link GremlinPlugin} to the executor. The key is the fully qualified class name * of the {@link GremlinPlugin} instance and the value is a map of configuration values. In that map, the key * is the name of a builder method on the {@link GremlinPlugin} and the value is some argument to pass to that * method. */ public Builder addPlugins(final String engineName, final Map<String, Map<String,Object>> plugins) { this.plugins.put(engineName, plugins); return this; } /** * Bindings to apply to every script evaluated. Note that the entries of the supplied {@code Bindings} object * will be copied into a newly created {@link ConcurrentBindings} object * at the call of this method. */ public Builder globalBindings(final Bindings bindings) { this.globalBindings = new ConcurrentBindings(bindings); return this; } /** * Amount of time an evaluation has before it times out. Note that the time required covers both evaluation * as well as any time needed for a post result transformation (if the transformation function is supplied * to the {@link GremlinExecutor#eval}). * * @param evaluationTimeout Time in milliseconds that an evaluation is allowed to run and its * results potentially transformed. Set to zero to have no timeout set. */ public Builder evaluationTimeout(final long evaluationTimeout) { this.evaluationTimeout = evaluationTimeout; return this; } /** * The thread pool used to evaluate scripts. */ public Builder executorService(final ExecutorService executorService) { this.executorService = executorService; return this; } /** * The thread pool used to schedule timeouts on scripts. */ public Builder scheduledExecutorService(final ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; return this; } /** * A {@link Consumer} to execute just before the script evaluation. */ public Builder beforeEval(final Consumer<Bindings> beforeEval) { this.beforeEval = beforeEval; return this; } /** * A {@link Consumer} to execute just after successful script evaluation. Note that success will be called * after evaluation of the script in the engine and after the results have passed through transformation * (if a transform function is passed to the {@link GremlinExecutor#eval}. */ public Builder afterSuccess(final Consumer<Bindings> afterSuccess) { this.afterSuccess = afterSuccess; return this; } /** * @deprecated As of release 3.6.2, replaced by {@link #afterTimeout(BiConsumer)}. */ @Deprecated public Builder afterTimeout(final Consumer<Bindings> afterTimeout) { BiConsumer<Bindings, Throwable> updatedAfterTimeout = (b, t) -> { afterTimeout.accept(b); }; return afterTimeout(updatedAfterTimeout); } /** * A {@link BiConsumer} to execute if the script times out. */ public Builder afterTimeout(final BiConsumer<Bindings, Throwable> afterTimeout) { this.afterTimeout = afterTimeout; return this; } /** * A {@link Consumer} to execute in the event of failure. */ public Builder afterFailure(final BiConsumer<Bindings, Throwable> afterFailure) { this.afterFailure = afterFailure; return this; } public GremlinExecutor create() { final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("gremlin-executor-default-%d").build(); final AtomicBoolean poolCreatedByBuilder = new AtomicBoolean(); final AtomicBoolean suppliedExecutor = new AtomicBoolean(true); final AtomicBoolean suppliedScheduledExecutor = new AtomicBoolean(true); final ExecutorService es = Optional.ofNullable(executorService).orElseGet(() -> { poolCreatedByBuilder.set(true); suppliedExecutor.set(false); return Executors.newScheduledThreadPool(4, threadFactory); }); executorService = es; final ScheduledExecutorService ses = Optional.ofNullable(scheduledExecutorService).orElseGet(() -> { // if the pool is created by the builder and we need another just re-use it, otherwise create // a new one of those guys suppliedScheduledExecutor.set(false); return (poolCreatedByBuilder.get()) ? (ScheduledExecutorService) es : Executors.newScheduledThreadPool(4, threadFactory); }); scheduledExecutorService = ses; return new GremlinExecutor(this, suppliedExecutor.get(), suppliedScheduledExecutor.get()); } } /** * The lifecycle of execution within the {@link #eval(String, String, Bindings, LifeCycle)} method. Since scripts * are executed in a thread pool and graph transactions are bound to a thread all actions related to that script * evaluation, both before and after that evaluation, need to be executed in the same thread. This leads to a * lifecycle of actions that can occur within that evaluation. Note that some of these options can be globally * set on the {@code GremlinExecutor} itself through the {@link GremlinExecutor.Builder}. If specified here, * they will override those global settings. */ public static class LifeCycle { private final Optional<Consumer<Bindings>> beforeEval; private final Optional<Function<Object, Object>> transformResult; private final Optional<Consumer<Object>> withResult; private final Optional<Consumer<Bindings>> afterSuccess; private final Optional<BiConsumer<Bindings, Throwable>> afterTimeout; private final Optional<BiConsumer<Bindings, Throwable>> afterFailure; private final Optional<Long> evaluationTimeoutOverride; private LifeCycle(final Builder builder) { beforeEval = Optional.ofNullable(builder.beforeEval); transformResult = Optional.ofNullable(builder.transformResult); withResult = Optional.ofNullable(builder.withResult); afterSuccess = Optional.ofNullable(builder.afterSuccess); afterTimeout = Optional.ofNullable(builder.afterTimeout); afterFailure = Optional.ofNullable(builder.afterFailure); evaluationTimeoutOverride = Optional.ofNullable(builder.evaluationTimeoutOverride); } public Optional<Long> getEvaluationTimeoutOverride() { return evaluationTimeoutOverride; } public Optional<Consumer<Bindings>> getBeforeEval() { return beforeEval; } public Optional<Function<Object, Object>> getTransformResult() { return transformResult; } public Optional<Consumer<Object>> getWithResult() { return withResult; } public Optional<Consumer<Bindings>> getAfterSuccess() { return afterSuccess; } public Optional<BiConsumer<Bindings, Throwable>> getAfterTimeout() { return afterTimeout; } public Optional<BiConsumer<Bindings, Throwable>> getAfterFailure() { return afterFailure; } public static Builder build() { return new Builder(); } public static class Builder { private Consumer<Bindings> beforeEval = null; private Function<Object, Object> transformResult = null; private Consumer<Object> withResult = null; private Consumer<Bindings> afterSuccess = null; private BiConsumer<Bindings, Throwable> afterTimeout = null; private BiConsumer<Bindings, Throwable> afterFailure = null; private Long evaluationTimeoutOverride = null; /** * Specifies the function to execute prior to the script being evaluated. This function can also be * specified globally on {@link GremlinExecutor.Builder#beforeEval(Consumer)}. */ public Builder beforeEval(final Consumer<Bindings> beforeEval) { this.beforeEval = beforeEval; return this; } /** * Specifies the function to execute on the result of the script evaluation just after script evaluation * returns but before the script evaluation is marked as complete. */ public Builder transformResult(final Function<Object, Object> transformResult) { this.transformResult = transformResult; return this; } /** * Specifies the function to execute on the result of the script evaluation just after script evaluation * returns but before the script evaluation is marked as complete. */ public Builder withResult(final Consumer<Object> withResult) { this.withResult = withResult; return this; } /** * Specifies the function to execute after result transformations. This function can also be * specified globally on {@link GremlinExecutor.Builder#afterSuccess(Consumer)}. The script evaluation * will be marked as "complete" after this method. */ public Builder afterSuccess(final Consumer<Bindings> afterSuccess) { this.afterSuccess = afterSuccess; return this; } /** * Specifies the function to execute if the script evaluation times out. This * function can also be * specified globally on * {@link GremlinExecutor.Builder#afterTimeout(BiConsumer)}. */ public Builder afterTimeout(final BiConsumer<Bindings, Throwable> afterTimeout) { this.afterTimeout = afterTimeout; return this; } /** * Specifies the function to execute if the script evaluation times out. This * function can also be * specified globally on * {@link GremlinExecutor.Builder#afterTimeout(BiConsumer)}. */ public Builder afterTimeout(final Consumer<Bindings> afterTimeout) { this.afterTimeout = new BiConsumer<Bindings,Throwable>() { @Override public void accept(final Bindings arg0, final Throwable arg1) { // TODO Auto-generated method stub } }; return this; } /** * Specifies the function to execute if the script evaluation fails. This function can also be * specified globally on {@link GremlinExecutor.Builder#afterFailure(BiConsumer)}. */ public Builder afterFailure(final BiConsumer<Bindings, Throwable> afterFailure) { this.afterFailure = afterFailure; return this; } /** * An override to the global {@code evaluationTimeout} setting on the script engine. If this value * is set to {@code null} (the default) it will use the global setting. */ public Builder evaluationTimeoutOverride(final Long evaluationTimeoutOverride) { this.evaluationTimeoutOverride = evaluationTimeoutOverride; return this; } public LifeCycle create() { return new LifeCycle(this); } } } }
googleapis/google-cloud-java
37,779
java-gke-backup/proto-google-cloud-gke-backup-v1/src/main/java/com/google/cloud/gkebackup/v1/CreateRestoreRequest.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 CreateRestore. * </pre> * * Protobuf type {@code google.cloud.gkebackup.v1.CreateRestoreRequest} */ public final class CreateRestoreRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.gkebackup.v1.CreateRestoreRequest) CreateRestoreRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateRestoreRequest.newBuilder() to construct. private CreateRestoreRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateRestoreRequest() { parent_ = ""; restoreId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateRestoreRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkebackup.v1.GKEBackupProto .internal_static_google_cloud_gkebackup_v1_CreateRestoreRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkebackup.v1.GKEBackupProto .internal_static_google_cloud_gkebackup_v1_CreateRestoreRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkebackup.v1.CreateRestoreRequest.class, com.google.cloud.gkebackup.v1.CreateRestoreRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESTORE_FIELD_NUMBER = 2; private com.google.cloud.gkebackup.v1.Restore restore_; /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code>.google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the restore field is set. */ @java.lang.Override public boolean hasRestore() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code>.google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The restore. */ @java.lang.Override public com.google.cloud.gkebackup.v1.Restore getRestore() { return restore_ == null ? com.google.cloud.gkebackup.v1.Restore.getDefaultInstance() : restore_; } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code>.google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.gkebackup.v1.RestoreOrBuilder getRestoreOrBuilder() { return restore_ == null ? com.google.cloud.gkebackup.v1.Restore.getDefaultInstance() : restore_; } public static final int RESTORE_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object restoreId_ = ""; /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The restoreId. */ @java.lang.Override public java.lang.String getRestoreId() { java.lang.Object ref = restoreId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); restoreId_ = s; return s; } } /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for restoreId. */ @java.lang.Override public com.google.protobuf.ByteString getRestoreIdBytes() { java.lang.Object ref = restoreId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); restoreId_ = 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, getRestore()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(restoreId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, restoreId_); } 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, getRestore()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(restoreId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, restoreId_); } 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.CreateRestoreRequest)) { return super.equals(obj); } com.google.cloud.gkebackup.v1.CreateRestoreRequest other = (com.google.cloud.gkebackup.v1.CreateRestoreRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasRestore() != other.hasRestore()) return false; if (hasRestore()) { if (!getRestore().equals(other.getRestore())) return false; } if (!getRestoreId().equals(other.getRestoreId())) 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 (hasRestore()) { hash = (37 * hash) + RESTORE_FIELD_NUMBER; hash = (53 * hash) + getRestore().hashCode(); } hash = (37 * hash) + RESTORE_ID_FIELD_NUMBER; hash = (53 * hash) + getRestoreId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest 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.CreateRestoreRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest 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.CreateRestoreRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest 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.CreateRestoreRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest 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.CreateRestoreRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest 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.CreateRestoreRequest 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.CreateRestoreRequest 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.CreateRestoreRequest 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 CreateRestore. * </pre> * * Protobuf type {@code google.cloud.gkebackup.v1.CreateRestoreRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.gkebackup.v1.CreateRestoreRequest) com.google.cloud.gkebackup.v1.CreateRestoreRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkebackup.v1.GKEBackupProto .internal_static_google_cloud_gkebackup_v1_CreateRestoreRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkebackup.v1.GKEBackupProto .internal_static_google_cloud_gkebackup_v1_CreateRestoreRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkebackup.v1.CreateRestoreRequest.class, com.google.cloud.gkebackup.v1.CreateRestoreRequest.Builder.class); } // Construct using com.google.cloud.gkebackup.v1.CreateRestoreRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getRestoreFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; restore_ = null; if (restoreBuilder_ != null) { restoreBuilder_.dispose(); restoreBuilder_ = null; } restoreId_ = ""; 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_CreateRestoreRequest_descriptor; } @java.lang.Override public com.google.cloud.gkebackup.v1.CreateRestoreRequest getDefaultInstanceForType() { return com.google.cloud.gkebackup.v1.CreateRestoreRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.gkebackup.v1.CreateRestoreRequest build() { com.google.cloud.gkebackup.v1.CreateRestoreRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.gkebackup.v1.CreateRestoreRequest buildPartial() { com.google.cloud.gkebackup.v1.CreateRestoreRequest result = new com.google.cloud.gkebackup.v1.CreateRestoreRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.gkebackup.v1.CreateRestoreRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.restore_ = restoreBuilder_ == null ? restore_ : restoreBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.restoreId_ = restoreId_; } 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.CreateRestoreRequest) { return mergeFrom((com.google.cloud.gkebackup.v1.CreateRestoreRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.gkebackup.v1.CreateRestoreRequest other) { if (other == com.google.cloud.gkebackup.v1.CreateRestoreRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasRestore()) { mergeRestore(other.getRestore()); } if (!other.getRestoreId().isEmpty()) { restoreId_ = other.restoreId_; 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(getRestoreFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { restoreId_ = 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 RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The RestorePlan within which to create the Restore. * Format: `projects/&#42;&#47;locations/&#42;&#47;restorePlans/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.gkebackup.v1.Restore restore_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkebackup.v1.Restore, com.google.cloud.gkebackup.v1.Restore.Builder, com.google.cloud.gkebackup.v1.RestoreOrBuilder> restoreBuilder_; /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the restore field is set. */ public boolean hasRestore() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The restore. */ public com.google.cloud.gkebackup.v1.Restore getRestore() { if (restoreBuilder_ == null) { return restore_ == null ? com.google.cloud.gkebackup.v1.Restore.getDefaultInstance() : restore_; } else { return restoreBuilder_.getMessage(); } } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setRestore(com.google.cloud.gkebackup.v1.Restore value) { if (restoreBuilder_ == null) { if (value == null) { throw new NullPointerException(); } restore_ = value; } else { restoreBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setRestore(com.google.cloud.gkebackup.v1.Restore.Builder builderForValue) { if (restoreBuilder_ == null) { restore_ = builderForValue.build(); } else { restoreBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeRestore(com.google.cloud.gkebackup.v1.Restore value) { if (restoreBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && restore_ != null && restore_ != com.google.cloud.gkebackup.v1.Restore.getDefaultInstance()) { getRestoreBuilder().mergeFrom(value); } else { restore_ = value; } } else { restoreBuilder_.mergeFrom(value); } if (restore_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearRestore() { bitField0_ = (bitField0_ & ~0x00000002); restore_ = null; if (restoreBuilder_ != null) { restoreBuilder_.dispose(); restoreBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.gkebackup.v1.Restore.Builder getRestoreBuilder() { bitField0_ |= 0x00000002; onChanged(); return getRestoreFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.gkebackup.v1.RestoreOrBuilder getRestoreOrBuilder() { if (restoreBuilder_ != null) { return restoreBuilder_.getMessageOrBuilder(); } else { return restore_ == null ? com.google.cloud.gkebackup.v1.Restore.getDefaultInstance() : restore_; } } /** * * * <pre> * Required. The restore resource to create. * </pre> * * <code> * .google.cloud.gkebackup.v1.Restore restore = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkebackup.v1.Restore, com.google.cloud.gkebackup.v1.Restore.Builder, com.google.cloud.gkebackup.v1.RestoreOrBuilder> getRestoreFieldBuilder() { if (restoreBuilder_ == null) { restoreBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.gkebackup.v1.Restore, com.google.cloud.gkebackup.v1.Restore.Builder, com.google.cloud.gkebackup.v1.RestoreOrBuilder>( getRestore(), getParentForChildren(), isClean()); restore_ = null; } return restoreBuilder_; } private java.lang.Object restoreId_ = ""; /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The restoreId. */ public java.lang.String getRestoreId() { java.lang.Object ref = restoreId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); restoreId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for restoreId. */ public com.google.protobuf.ByteString getRestoreIdBytes() { java.lang.Object ref = restoreId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); restoreId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The restoreId to set. * @return This builder for chaining. */ public Builder setRestoreId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } restoreId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearRestoreId() { restoreId_ = getDefaultInstance().getRestoreId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. The client-provided short name for the Restore 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 Restores in this RestorePlan. * </pre> * * <code>string restore_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for restoreId to set. * @return This builder for chaining. */ public Builder setRestoreIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); restoreId_ = 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.CreateRestoreRequest) } // @@protoc_insertion_point(class_scope:google.cloud.gkebackup.v1.CreateRestoreRequest) private static final com.google.cloud.gkebackup.v1.CreateRestoreRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.gkebackup.v1.CreateRestoreRequest(); } public static com.google.cloud.gkebackup.v1.CreateRestoreRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateRestoreRequest> PARSER = new com.google.protobuf.AbstractParser<CreateRestoreRequest>() { @java.lang.Override public CreateRestoreRequest 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<CreateRestoreRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateRestoreRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.gkebackup.v1.CreateRestoreRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
38,018
java-confidentialcomputing/google-cloud-confidentialcomputing/src/main/java/com/google/cloud/confidentialcomputing/v1/ConfidentialComputingClient.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.confidentialcomputing.v1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.confidentialcomputing.v1.stub.ConfidentialComputingStub; import com.google.cloud.confidentialcomputing.v1.stub.ConfidentialComputingStubSettings; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service describing handlers for resources * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * Challenge challenge = Challenge.newBuilder().build(); * Challenge response = confidentialComputingClient.createChallenge(parent, challenge); * } * }</pre> * * <p>Note: close() needs to be called on the ConfidentialComputingClient object to clean up * resources such as threads. In the example above, try-with-resources is used, which automatically * calls close(). * * <table> * <caption>Methods</caption> * <tr> * <th>Method</th> * <th>Description</th> * <th>Method Variants</th> * </tr> * <tr> * <td><p> CreateChallenge</td> * <td><p> Creates a new Challenge in a given project and location.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> createChallenge(CreateChallengeRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> createChallenge(LocationName parent, Challenge challenge) * <li><p> createChallenge(String parent, Challenge challenge) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> createChallengeCallable() * </ul> * </td> * </tr> * <tr> * <td><p> VerifyAttestation</td> * <td><p> Verifies the provided attestation info, returning a signed attestation token.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> verifyAttestation(VerifyAttestationRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> verifyAttestationCallable() * </ul> * </td> * </tr> * <tr> * <td><p> VerifyConfidentialSpace</td> * <td><p> Verifies whether the provided attestation info is valid, returning a signed attestation token if so.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> verifyConfidentialSpace(VerifyConfidentialSpaceRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> verifyConfidentialSpaceCallable() * </ul> * </td> * </tr> * <tr> * <td><p> VerifyConfidentialGke</td> * <td><p> Verifies the provided Confidential GKE attestation info, returning a signed OIDC token.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> verifyConfidentialGke(VerifyConfidentialGkeRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> verifyConfidentialGkeCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ListLocations</td> * <td><p> Lists information about the supported locations for this service.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> listLocations(ListLocationsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> listLocationsPagedCallable() * <li><p> listLocationsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GetLocation</td> * <td><p> Gets information about a location.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> getLocation(GetLocationRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getLocationCallable() * </ul> * </td> * </tr> * </table> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of ConfidentialComputingSettings * to create(). For example: * * <p>To customize credentials: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * ConfidentialComputingSettings confidentialComputingSettings = * ConfidentialComputingSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create(confidentialComputingSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * ConfidentialComputingSettings confidentialComputingSettings = * ConfidentialComputingSettings.newBuilder().setEndpoint(myEndpoint).build(); * ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create(confidentialComputingSettings); * }</pre> * * <p>To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over * the wire: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * ConfidentialComputingSettings confidentialComputingSettings = * ConfidentialComputingSettings.newHttpJsonBuilder().build(); * ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create(confidentialComputingSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class ConfidentialComputingClient implements BackgroundResource { private final ConfidentialComputingSettings settings; private final ConfidentialComputingStub stub; /** Constructs an instance of ConfidentialComputingClient with default settings. */ public static final ConfidentialComputingClient create() throws IOException { return create(ConfidentialComputingSettings.newBuilder().build()); } /** * Constructs an instance of ConfidentialComputingClient, using the given settings. The channels * are created based on the settings passed in, or defaults for any settings that are not set. */ public static final ConfidentialComputingClient create(ConfidentialComputingSettings settings) throws IOException { return new ConfidentialComputingClient(settings); } /** * Constructs an instance of ConfidentialComputingClient, using the given stub for making calls. * This is for advanced usage - prefer using create(ConfidentialComputingSettings). */ public static final ConfidentialComputingClient create(ConfidentialComputingStub stub) { return new ConfidentialComputingClient(stub); } /** * Constructs an instance of ConfidentialComputingClient, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected ConfidentialComputingClient(ConfidentialComputingSettings settings) throws IOException { this.settings = settings; this.stub = ((ConfidentialComputingStubSettings) settings.getStubSettings()).createStub(); } protected ConfidentialComputingClient(ConfidentialComputingStub stub) { this.settings = null; this.stub = stub; } public final ConfidentialComputingSettings getSettings() { return settings; } public ConfidentialComputingStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a new Challenge in a given project and location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * Challenge challenge = Challenge.newBuilder().build(); * Challenge response = confidentialComputingClient.createChallenge(parent, challenge); * } * }</pre> * * @param parent Required. The resource name of the location where the Challenge will be used, in * the format `projects/&#42;/locations/&#42;`. * @param challenge Required. The Challenge to be created. Currently this field can be empty as * all the Challenge fields are set by the server. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Challenge createChallenge(LocationName parent, Challenge challenge) { CreateChallengeRequest request = CreateChallengeRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setChallenge(challenge) .build(); return createChallenge(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a new Challenge in a given project and location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * String parent = LocationName.of("[PROJECT]", "[LOCATION]").toString(); * Challenge challenge = Challenge.newBuilder().build(); * Challenge response = confidentialComputingClient.createChallenge(parent, challenge); * } * }</pre> * * @param parent Required. The resource name of the location where the Challenge will be used, in * the format `projects/&#42;/locations/&#42;`. * @param challenge Required. The Challenge to be created. Currently this field can be empty as * all the Challenge fields are set by the server. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Challenge createChallenge(String parent, Challenge challenge) { CreateChallengeRequest request = CreateChallengeRequest.newBuilder().setParent(parent).setChallenge(challenge).build(); return createChallenge(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a new Challenge in a given project and location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * CreateChallengeRequest request = * CreateChallengeRequest.newBuilder() * .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString()) * .setChallenge(Challenge.newBuilder().build()) * .build(); * Challenge response = confidentialComputingClient.createChallenge(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Challenge createChallenge(CreateChallengeRequest request) { return createChallengeCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a new Challenge in a given project and location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * CreateChallengeRequest request = * CreateChallengeRequest.newBuilder() * .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString()) * .setChallenge(Challenge.newBuilder().build()) * .build(); * ApiFuture<Challenge> future = * confidentialComputingClient.createChallengeCallable().futureCall(request); * // Do something. * Challenge response = future.get(); * } * }</pre> */ public final UnaryCallable<CreateChallengeRequest, Challenge> createChallengeCallable() { return stub.createChallengeCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Verifies the provided attestation info, returning a signed attestation token. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * VerifyAttestationRequest request = * VerifyAttestationRequest.newBuilder() * .setChallenge(ChallengeName.of("[PROJECT]", "[LOCATION]", "[UUID]").toString()) * .setGcpCredentials(GcpCredentials.newBuilder().build()) * .setTpmAttestation(TpmAttestation.newBuilder().build()) * .setConfidentialSpaceInfo(ConfidentialSpaceInfo.newBuilder().build()) * .setTokenOptions(TokenOptions.newBuilder().build()) * .setAttester("attester542920370") * .build(); * VerifyAttestationResponse response = confidentialComputingClient.verifyAttestation(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final VerifyAttestationResponse verifyAttestation(VerifyAttestationRequest request) { return verifyAttestationCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Verifies the provided attestation info, returning a signed attestation token. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * VerifyAttestationRequest request = * VerifyAttestationRequest.newBuilder() * .setChallenge(ChallengeName.of("[PROJECT]", "[LOCATION]", "[UUID]").toString()) * .setGcpCredentials(GcpCredentials.newBuilder().build()) * .setTpmAttestation(TpmAttestation.newBuilder().build()) * .setConfidentialSpaceInfo(ConfidentialSpaceInfo.newBuilder().build()) * .setTokenOptions(TokenOptions.newBuilder().build()) * .setAttester("attester542920370") * .build(); * ApiFuture<VerifyAttestationResponse> future = * confidentialComputingClient.verifyAttestationCallable().futureCall(request); * // Do something. * VerifyAttestationResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<VerifyAttestationRequest, VerifyAttestationResponse> verifyAttestationCallable() { return stub.verifyAttestationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Verifies whether the provided attestation info is valid, returning a signed attestation token * if so. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * VerifyConfidentialSpaceRequest request = * VerifyConfidentialSpaceRequest.newBuilder() * .setChallenge(ChallengeName.of("[PROJECT]", "[LOCATION]", "[UUID]").toString()) * .setGcpCredentials(GcpCredentials.newBuilder().build()) * .addAllSignedEntities(new ArrayList<SignedEntity>()) * .setGceShieldedIdentity(GceShieldedIdentity.newBuilder().build()) * .setOptions( * VerifyConfidentialSpaceRequest.ConfidentialSpaceOptions.newBuilder().build()) * .build(); * VerifyConfidentialSpaceResponse response = * confidentialComputingClient.verifyConfidentialSpace(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final VerifyConfidentialSpaceResponse verifyConfidentialSpace( VerifyConfidentialSpaceRequest request) { return verifyConfidentialSpaceCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Verifies whether the provided attestation info is valid, returning a signed attestation token * if so. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * VerifyConfidentialSpaceRequest request = * VerifyConfidentialSpaceRequest.newBuilder() * .setChallenge(ChallengeName.of("[PROJECT]", "[LOCATION]", "[UUID]").toString()) * .setGcpCredentials(GcpCredentials.newBuilder().build()) * .addAllSignedEntities(new ArrayList<SignedEntity>()) * .setGceShieldedIdentity(GceShieldedIdentity.newBuilder().build()) * .setOptions( * VerifyConfidentialSpaceRequest.ConfidentialSpaceOptions.newBuilder().build()) * .build(); * ApiFuture<VerifyConfidentialSpaceResponse> future = * confidentialComputingClient.verifyConfidentialSpaceCallable().futureCall(request); * // Do something. * VerifyConfidentialSpaceResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<VerifyConfidentialSpaceRequest, VerifyConfidentialSpaceResponse> verifyConfidentialSpaceCallable() { return stub.verifyConfidentialSpaceCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Verifies the provided Confidential GKE attestation info, returning a signed OIDC token. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * VerifyConfidentialGkeRequest request = * VerifyConfidentialGkeRequest.newBuilder() * .setChallenge(ChallengeName.of("[PROJECT]", "[LOCATION]", "[UUID]").toString()) * .build(); * VerifyConfidentialGkeResponse response = * confidentialComputingClient.verifyConfidentialGke(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final VerifyConfidentialGkeResponse verifyConfidentialGke( VerifyConfidentialGkeRequest request) { return verifyConfidentialGkeCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Verifies the provided Confidential GKE attestation info, returning a signed OIDC token. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * VerifyConfidentialGkeRequest request = * VerifyConfidentialGkeRequest.newBuilder() * .setChallenge(ChallengeName.of("[PROJECT]", "[LOCATION]", "[UUID]").toString()) * .build(); * ApiFuture<VerifyConfidentialGkeResponse> future = * confidentialComputingClient.verifyConfidentialGkeCallable().futureCall(request); * // Do something. * VerifyConfidentialGkeResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<VerifyConfidentialGkeRequest, VerifyConfidentialGkeResponse> verifyConfidentialGkeCallable() { return stub.verifyConfidentialGkeCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Location element : confidentialComputingClient.listLocations(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListLocationsPagedResponse listLocations(ListLocationsRequest request) { return listLocationsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Location> future = * confidentialComputingClient.listLocationsPagedCallable().futureCall(request); * // Do something. * for (Location element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return stub.listLocationsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListLocationsResponse response = * confidentialComputingClient.listLocationsCallable().call(request); * for (Location element : response.getLocationsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return stub.listLocationsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets information about a location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * Location response = confidentialComputingClient.getLocation(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Location getLocation(GetLocationRequest request) { return getLocationCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets information about a location. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ConfidentialComputingClient confidentialComputingClient = * ConfidentialComputingClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * ApiFuture<Location> future = * confidentialComputingClient.getLocationCallable().futureCall(request); * // Do something. * Location response = future.get(); * } * }</pre> */ public final UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return stub.getLocationCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListLocationsPagedResponse extends AbstractPagedListResponse< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage, ListLocationsFixedSizeCollection> { public static ApiFuture<ListLocationsPagedResponse> createAsync( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ApiFuture<ListLocationsResponse> futureResponse) { ApiFuture<ListLocationsPage> futurePage = ListLocationsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListLocationsPagedResponse(input), MoreExecutors.directExecutor()); } private ListLocationsPagedResponse(ListLocationsPage page) { super(page, ListLocationsFixedSizeCollection.createEmptyCollection()); } } public static class ListLocationsPage extends AbstractPage< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage> { private ListLocationsPage( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ListLocationsResponse response) { super(context, response); } private static ListLocationsPage createEmptyPage() { return new ListLocationsPage(null, null); } @Override protected ListLocationsPage createPage( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ListLocationsResponse response) { return new ListLocationsPage(context, response); } @Override public ApiFuture<ListLocationsPage> createPageAsync( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ApiFuture<ListLocationsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListLocationsFixedSizeCollection extends AbstractFixedSizeCollection< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage, ListLocationsFixedSizeCollection> { private ListLocationsFixedSizeCollection(List<ListLocationsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListLocationsFixedSizeCollection createEmptyCollection() { return new ListLocationsFixedSizeCollection(null, 0); } @Override protected ListLocationsFixedSizeCollection createCollection( List<ListLocationsPage> pages, int collectionSize) { return new ListLocationsFixedSizeCollection(pages, collectionSize); } } }
googleapis/google-cloud-java
37,760
java-appengine-admin/proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/UpdateDomainMappingRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/appengine/v1/appengine.proto // Protobuf Java Version: 3.25.8 package com.google.appengine.v1; /** * * * <pre> * Request message for `DomainMappings.UpdateDomainMapping`. * </pre> * * Protobuf type {@code google.appengine.v1.UpdateDomainMappingRequest} */ public final class UpdateDomainMappingRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.appengine.v1.UpdateDomainMappingRequest) UpdateDomainMappingRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateDomainMappingRequest.newBuilder() to construct. private UpdateDomainMappingRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateDomainMappingRequest() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateDomainMappingRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateDomainMappingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateDomainMappingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.appengine.v1.UpdateDomainMappingRequest.class, com.google.appengine.v1.UpdateDomainMappingRequest.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DOMAIN_MAPPING_FIELD_NUMBER = 2; private com.google.appengine.v1.DomainMapping domainMapping_; /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> * * @return Whether the domainMapping field is set. */ @java.lang.Override public boolean hasDomainMapping() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> * * @return The domainMapping. */ @java.lang.Override public com.google.appengine.v1.DomainMapping getDomainMapping() { return domainMapping_ == null ? com.google.appengine.v1.DomainMapping.getDefaultInstance() : domainMapping_; } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ @java.lang.Override public com.google.appengine.v1.DomainMappingOrBuilder getDomainMappingOrBuilder() { return domainMapping_ == null ? com.google.appengine.v1.DomainMapping.getDefaultInstance() : domainMapping_; } public static final int UPDATE_MASK_FIELD_NUMBER = 3; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getDomainMapping()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getDomainMapping()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, 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.appengine.v1.UpdateDomainMappingRequest)) { return super.equals(obj); } com.google.appengine.v1.UpdateDomainMappingRequest other = (com.google.appengine.v1.UpdateDomainMappingRequest) obj; if (!getName().equals(other.getName())) return false; if (hasDomainMapping() != other.hasDomainMapping()) return false; if (hasDomainMapping()) { if (!getDomainMapping().equals(other.getDomainMapping())) 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(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasDomainMapping()) { hash = (37 * hash) + DOMAIN_MAPPING_FIELD_NUMBER; hash = (53 * hash) + getDomainMapping().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.appengine.v1.UpdateDomainMappingRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.UpdateDomainMappingRequest 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.UpdateDomainMappingRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.UpdateDomainMappingRequest 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.UpdateDomainMappingRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.UpdateDomainMappingRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.appengine.v1.UpdateDomainMappingRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.appengine.v1.UpdateDomainMappingRequest 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.UpdateDomainMappingRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.appengine.v1.UpdateDomainMappingRequest 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.UpdateDomainMappingRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.appengine.v1.UpdateDomainMappingRequest 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.UpdateDomainMappingRequest 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 `DomainMappings.UpdateDomainMapping`. * </pre> * * Protobuf type {@code google.appengine.v1.UpdateDomainMappingRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.appengine.v1.UpdateDomainMappingRequest) com.google.appengine.v1.UpdateDomainMappingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateDomainMappingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateDomainMappingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.appengine.v1.UpdateDomainMappingRequest.class, com.google.appengine.v1.UpdateDomainMappingRequest.Builder.class); } // Construct using com.google.appengine.v1.UpdateDomainMappingRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getDomainMappingFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; domainMapping_ = null; if (domainMappingBuilder_ != null) { domainMappingBuilder_.dispose(); domainMappingBuilder_ = 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.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateDomainMappingRequest_descriptor; } @java.lang.Override public com.google.appengine.v1.UpdateDomainMappingRequest getDefaultInstanceForType() { return com.google.appengine.v1.UpdateDomainMappingRequest.getDefaultInstance(); } @java.lang.Override public com.google.appengine.v1.UpdateDomainMappingRequest build() { com.google.appengine.v1.UpdateDomainMappingRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.appengine.v1.UpdateDomainMappingRequest buildPartial() { com.google.appengine.v1.UpdateDomainMappingRequest result = new com.google.appengine.v1.UpdateDomainMappingRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.appengine.v1.UpdateDomainMappingRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.domainMapping_ = domainMappingBuilder_ == null ? domainMapping_ : domainMappingBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 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.appengine.v1.UpdateDomainMappingRequest) { return mergeFrom((com.google.appengine.v1.UpdateDomainMappingRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.appengine.v1.UpdateDomainMappingRequest other) { if (other == com.google.appengine.v1.UpdateDomainMappingRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasDomainMapping()) { mergeDomainMapping(other.getDomainMapping()); } 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: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getDomainMappingFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/domainMappings/example.com`. * </pre> * * <code>string name = 1;</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.appengine.v1.DomainMapping domainMapping_; private com.google.protobuf.SingleFieldBuilderV3< com.google.appengine.v1.DomainMapping, com.google.appengine.v1.DomainMapping.Builder, com.google.appengine.v1.DomainMappingOrBuilder> domainMappingBuilder_; /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> * * @return Whether the domainMapping field is set. */ public boolean hasDomainMapping() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> * * @return The domainMapping. */ public com.google.appengine.v1.DomainMapping getDomainMapping() { if (domainMappingBuilder_ == null) { return domainMapping_ == null ? com.google.appengine.v1.DomainMapping.getDefaultInstance() : domainMapping_; } else { return domainMappingBuilder_.getMessage(); } } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ public Builder setDomainMapping(com.google.appengine.v1.DomainMapping value) { if (domainMappingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } domainMapping_ = value; } else { domainMappingBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ public Builder setDomainMapping(com.google.appengine.v1.DomainMapping.Builder builderForValue) { if (domainMappingBuilder_ == null) { domainMapping_ = builderForValue.build(); } else { domainMappingBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ public Builder mergeDomainMapping(com.google.appengine.v1.DomainMapping value) { if (domainMappingBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && domainMapping_ != null && domainMapping_ != com.google.appengine.v1.DomainMapping.getDefaultInstance()) { getDomainMappingBuilder().mergeFrom(value); } else { domainMapping_ = value; } } else { domainMappingBuilder_.mergeFrom(value); } if (domainMapping_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ public Builder clearDomainMapping() { bitField0_ = (bitField0_ & ~0x00000002); domainMapping_ = null; if (domainMappingBuilder_ != null) { domainMappingBuilder_.dispose(); domainMappingBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ public com.google.appengine.v1.DomainMapping.Builder getDomainMappingBuilder() { bitField0_ |= 0x00000002; onChanged(); return getDomainMappingFieldBuilder().getBuilder(); } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ public com.google.appengine.v1.DomainMappingOrBuilder getDomainMappingOrBuilder() { if (domainMappingBuilder_ != null) { return domainMappingBuilder_.getMessageOrBuilder(); } else { return domainMapping_ == null ? com.google.appengine.v1.DomainMapping.getDefaultInstance() : domainMapping_; } } /** * * * <pre> * A domain mapping containing the updated resource. Only fields set * in the field mask will be updated. * </pre> * * <code>.google.appengine.v1.DomainMapping domain_mapping = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.appengine.v1.DomainMapping, com.google.appengine.v1.DomainMapping.Builder, com.google.appengine.v1.DomainMappingOrBuilder> getDomainMappingFieldBuilder() { if (domainMappingBuilder_ == null) { domainMappingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.appengine.v1.DomainMapping, com.google.appengine.v1.DomainMapping.Builder, com.google.appengine.v1.DomainMappingOrBuilder>( getDomainMapping(), getParentForChildren(), isClean()); domainMapping_ = null; } return domainMappingBuilder_; } 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. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</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. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</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_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000004); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000004; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</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. Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</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.appengine.v1.UpdateDomainMappingRequest) } // @@protoc_insertion_point(class_scope:google.appengine.v1.UpdateDomainMappingRequest) private static final com.google.appengine.v1.UpdateDomainMappingRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.appengine.v1.UpdateDomainMappingRequest(); } public static com.google.appengine.v1.UpdateDomainMappingRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateDomainMappingRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateDomainMappingRequest>() { @java.lang.Override public UpdateDomainMappingRequest 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<UpdateDomainMappingRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateDomainMappingRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.appengine.v1.UpdateDomainMappingRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,855
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/UpdateIndexEndpointRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/visionai/v1/warehouse.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.visionai.v1; /** * * * <pre> * Request message for UpdateIndexEndpoint. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.UpdateIndexEndpointRequest} */ public final class UpdateIndexEndpointRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.UpdateIndexEndpointRequest) UpdateIndexEndpointRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateIndexEndpointRequest.newBuilder() to construct. private UpdateIndexEndpointRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateIndexEndpointRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateIndexEndpointRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_UpdateIndexEndpointRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_UpdateIndexEndpointRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.class, com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.Builder.class); } private int bitField0_; public static final int INDEX_ENDPOINT_FIELD_NUMBER = 1; private com.google.cloud.visionai.v1.IndexEndpoint indexEndpoint_; /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the indexEndpoint field is set. */ @java.lang.Override public boolean hasIndexEndpoint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The indexEndpoint. */ @java.lang.Override public com.google.cloud.visionai.v1.IndexEndpoint getIndexEndpoint() { return indexEndpoint_ == null ? com.google.cloud.visionai.v1.IndexEndpoint.getDefaultInstance() : indexEndpoint_; } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.visionai.v1.IndexEndpointOrBuilder getIndexEndpointOrBuilder() { return indexEndpoint_ == null ? com.google.cloud.visionai.v1.IndexEndpoint.getDefaultInstance() : indexEndpoint_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getIndexEndpoint()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getIndexEndpoint()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.visionai.v1.UpdateIndexEndpointRequest)) { return super.equals(obj); } com.google.cloud.visionai.v1.UpdateIndexEndpointRequest other = (com.google.cloud.visionai.v1.UpdateIndexEndpointRequest) obj; if (hasIndexEndpoint() != other.hasIndexEndpoint()) return false; if (hasIndexEndpoint()) { if (!getIndexEndpoint().equals(other.getIndexEndpoint())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasIndexEndpoint()) { hash = (37 * hash) + INDEX_ENDPOINT_FIELD_NUMBER; hash = (53 * hash) + getIndexEndpoint().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.visionai.v1.UpdateIndexEndpointRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for UpdateIndexEndpoint. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.UpdateIndexEndpointRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.UpdateIndexEndpointRequest) com.google.cloud.visionai.v1.UpdateIndexEndpointRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_UpdateIndexEndpointRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_UpdateIndexEndpointRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.class, com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.Builder.class); } // Construct using com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getIndexEndpointFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; indexEndpoint_ = null; if (indexEndpointBuilder_ != null) { indexEndpointBuilder_.dispose(); indexEndpointBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_UpdateIndexEndpointRequest_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.UpdateIndexEndpointRequest getDefaultInstanceForType() { return com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.UpdateIndexEndpointRequest build() { com.google.cloud.visionai.v1.UpdateIndexEndpointRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.UpdateIndexEndpointRequest buildPartial() { com.google.cloud.visionai.v1.UpdateIndexEndpointRequest result = new com.google.cloud.visionai.v1.UpdateIndexEndpointRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.visionai.v1.UpdateIndexEndpointRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.indexEndpoint_ = indexEndpointBuilder_ == null ? indexEndpoint_ : indexEndpointBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.visionai.v1.UpdateIndexEndpointRequest) { return mergeFrom((com.google.cloud.visionai.v1.UpdateIndexEndpointRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.UpdateIndexEndpointRequest other) { if (other == com.google.cloud.visionai.v1.UpdateIndexEndpointRequest.getDefaultInstance()) return this; if (other.hasIndexEndpoint()) { mergeIndexEndpoint(other.getIndexEndpoint()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getIndexEndpointFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.visionai.v1.IndexEndpoint indexEndpoint_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.IndexEndpoint, com.google.cloud.visionai.v1.IndexEndpoint.Builder, com.google.cloud.visionai.v1.IndexEndpointOrBuilder> indexEndpointBuilder_; /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the indexEndpoint field is set. */ public boolean hasIndexEndpoint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The indexEndpoint. */ public com.google.cloud.visionai.v1.IndexEndpoint getIndexEndpoint() { if (indexEndpointBuilder_ == null) { return indexEndpoint_ == null ? com.google.cloud.visionai.v1.IndexEndpoint.getDefaultInstance() : indexEndpoint_; } else { return indexEndpointBuilder_.getMessage(); } } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setIndexEndpoint(com.google.cloud.visionai.v1.IndexEndpoint value) { if (indexEndpointBuilder_ == null) { if (value == null) { throw new NullPointerException(); } indexEndpoint_ = value; } else { indexEndpointBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setIndexEndpoint( com.google.cloud.visionai.v1.IndexEndpoint.Builder builderForValue) { if (indexEndpointBuilder_ == null) { indexEndpoint_ = builderForValue.build(); } else { indexEndpointBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeIndexEndpoint(com.google.cloud.visionai.v1.IndexEndpoint value) { if (indexEndpointBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && indexEndpoint_ != null && indexEndpoint_ != com.google.cloud.visionai.v1.IndexEndpoint.getDefaultInstance()) { getIndexEndpointBuilder().mergeFrom(value); } else { indexEndpoint_ = value; } } else { indexEndpointBuilder_.mergeFrom(value); } if (indexEndpoint_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearIndexEndpoint() { bitField0_ = (bitField0_ & ~0x00000001); indexEndpoint_ = null; if (indexEndpointBuilder_ != null) { indexEndpointBuilder_.dispose(); indexEndpointBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.visionai.v1.IndexEndpoint.Builder getIndexEndpointBuilder() { bitField0_ |= 0x00000001; onChanged(); return getIndexEndpointFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.visionai.v1.IndexEndpointOrBuilder getIndexEndpointOrBuilder() { if (indexEndpointBuilder_ != null) { return indexEndpointBuilder_.getMessageOrBuilder(); } else { return indexEndpoint_ == null ? com.google.cloud.visionai.v1.IndexEndpoint.getDefaultInstance() : indexEndpoint_; } } /** * * * <pre> * Required. The resource being updated. * </pre> * * <code> * .google.cloud.visionai.v1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.IndexEndpoint, com.google.cloud.visionai.v1.IndexEndpoint.Builder, com.google.cloud.visionai.v1.IndexEndpointOrBuilder> getIndexEndpointFieldBuilder() { if (indexEndpointBuilder_ == null) { indexEndpointBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.IndexEndpoint, com.google.cloud.visionai.v1.IndexEndpoint.Builder, com.google.cloud.visionai.v1.IndexEndpointOrBuilder>( getIndexEndpoint(), getParentForChildren(), isClean()); indexEndpoint_ = null; } return indexEndpointBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </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. Field mask is used to specify the fields to be overwritten in the * IndexEndpoint resource by the update. * The fields specified in the update_mask are relative to the resource, not * the full request. * A field of the resource will be overwritten if it is in the mask. * Empty field mask is not allowed. * If the mask is "*", then this is a full replacement of the resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.UpdateIndexEndpointRequest) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.UpdateIndexEndpointRequest) private static final com.google.cloud.visionai.v1.UpdateIndexEndpointRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.UpdateIndexEndpointRequest(); } public static com.google.cloud.visionai.v1.UpdateIndexEndpointRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateIndexEndpointRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateIndexEndpointRequest>() { @java.lang.Override public UpdateIndexEndpointRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdateIndexEndpointRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateIndexEndpointRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.UpdateIndexEndpointRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
38,065
java-workspaceevents/google-cloud-workspaceevents/src/main/java/com/google/apps/events/subscriptions/v1beta/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.v1beta.stub; import static com.google.apps.events.subscriptions.v1beta.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.v1beta.CreateSubscriptionMetadata; import com.google.apps.events.subscriptions.v1beta.CreateSubscriptionRequest; import com.google.apps.events.subscriptions.v1beta.DeleteSubscriptionMetadata; import com.google.apps.events.subscriptions.v1beta.DeleteSubscriptionRequest; import com.google.apps.events.subscriptions.v1beta.GetSubscriptionRequest; import com.google.apps.events.subscriptions.v1beta.ListSubscriptionsRequest; import com.google.apps.events.subscriptions.v1beta.ListSubscriptionsResponse; import com.google.apps.events.subscriptions.v1beta.ReactivateSubscriptionMetadata; import com.google.apps.events.subscriptions.v1beta.ReactivateSubscriptionRequest; import com.google.apps.events.subscriptions.v1beta.Subscription; import com.google.apps.events.subscriptions.v1beta.UpdateSubscriptionMetadata; import com.google.apps.events.subscriptions.v1beta.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> */ @BetaApi @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/drive") .add("https://www.googleapis.com/auth/drive.file") .add("https://www.googleapis.com/auth/drive.metadata") .add("https://www.googleapis.com/auth/drive.metadata.readonly") .add("https://www.googleapis.com/auth/drive.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/sdk-platform-java
37,838
java-iam/proto-google-iam-v3beta/src/main/java/com/google/iam/v3beta/SearchTargetPolicyBindingsResponse.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/iam/v3beta/policy_bindings_service.proto // Protobuf Java Version: 3.25.8 package com.google.iam.v3beta; /** * * * <pre> * Response message for SearchTargetPolicyBindings method. * </pre> * * Protobuf type {@code google.iam.v3beta.SearchTargetPolicyBindingsResponse} */ public final class SearchTargetPolicyBindingsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.iam.v3beta.SearchTargetPolicyBindingsResponse) SearchTargetPolicyBindingsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use SearchTargetPolicyBindingsResponse.newBuilder() to construct. private SearchTargetPolicyBindingsResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchTargetPolicyBindingsResponse() { policyBindings_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchTargetPolicyBindingsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.iam.v3beta.PolicyBindingsServiceProto .internal_static_google_iam_v3beta_SearchTargetPolicyBindingsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.iam.v3beta.PolicyBindingsServiceProto .internal_static_google_iam_v3beta_SearchTargetPolicyBindingsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.class, com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.Builder.class); } public static final int POLICY_BINDINGS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.iam.v3beta.PolicyBinding> policyBindings_; /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ @java.lang.Override public java.util.List<com.google.iam.v3beta.PolicyBinding> getPolicyBindingsList() { return policyBindings_; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.iam.v3beta.PolicyBindingOrBuilder> getPolicyBindingsOrBuilderList() { return policyBindings_; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ @java.lang.Override public int getPolicyBindingsCount() { return policyBindings_.size(); } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ @java.lang.Override public com.google.iam.v3beta.PolicyBinding getPolicyBindings(int index) { return policyBindings_.get(index); } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ @java.lang.Override public com.google.iam.v3beta.PolicyBindingOrBuilder getPolicyBindingsOrBuilder(int index) { return policyBindings_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</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 < policyBindings_.size(); i++) { output.writeMessage(1, policyBindings_.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 < policyBindings_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, policyBindings_.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.iam.v3beta.SearchTargetPolicyBindingsResponse)) { return super.equals(obj); } com.google.iam.v3beta.SearchTargetPolicyBindingsResponse other = (com.google.iam.v3beta.SearchTargetPolicyBindingsResponse) obj; if (!getPolicyBindingsList().equals(other.getPolicyBindingsList())) 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 (getPolicyBindingsCount() > 0) { hash = (37 * hash) + POLICY_BINDINGS_FIELD_NUMBER; hash = (53 * hash) + getPolicyBindingsList().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.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse 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.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse 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.iam.v3beta.SearchTargetPolicyBindingsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse 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.iam.v3beta.SearchTargetPolicyBindingsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse 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.iam.v3beta.SearchTargetPolicyBindingsResponse 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 SearchTargetPolicyBindings method. * </pre> * * Protobuf type {@code google.iam.v3beta.SearchTargetPolicyBindingsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.iam.v3beta.SearchTargetPolicyBindingsResponse) com.google.iam.v3beta.SearchTargetPolicyBindingsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.iam.v3beta.PolicyBindingsServiceProto .internal_static_google_iam_v3beta_SearchTargetPolicyBindingsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.iam.v3beta.PolicyBindingsServiceProto .internal_static_google_iam_v3beta_SearchTargetPolicyBindingsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.class, com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.Builder.class); } // Construct using com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (policyBindingsBuilder_ == null) { policyBindings_ = java.util.Collections.emptyList(); } else { policyBindings_ = null; policyBindingsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.iam.v3beta.PolicyBindingsServiceProto .internal_static_google_iam_v3beta_SearchTargetPolicyBindingsResponse_descriptor; } @java.lang.Override public com.google.iam.v3beta.SearchTargetPolicyBindingsResponse getDefaultInstanceForType() { return com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.getDefaultInstance(); } @java.lang.Override public com.google.iam.v3beta.SearchTargetPolicyBindingsResponse build() { com.google.iam.v3beta.SearchTargetPolicyBindingsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.iam.v3beta.SearchTargetPolicyBindingsResponse buildPartial() { com.google.iam.v3beta.SearchTargetPolicyBindingsResponse result = new com.google.iam.v3beta.SearchTargetPolicyBindingsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.iam.v3beta.SearchTargetPolicyBindingsResponse result) { if (policyBindingsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { policyBindings_ = java.util.Collections.unmodifiableList(policyBindings_); bitField0_ = (bitField0_ & ~0x00000001); } result.policyBindings_ = policyBindings_; } else { result.policyBindings_ = policyBindingsBuilder_.build(); } } private void buildPartial0(com.google.iam.v3beta.SearchTargetPolicyBindingsResponse 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.iam.v3beta.SearchTargetPolicyBindingsResponse) { return mergeFrom((com.google.iam.v3beta.SearchTargetPolicyBindingsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.iam.v3beta.SearchTargetPolicyBindingsResponse other) { if (other == com.google.iam.v3beta.SearchTargetPolicyBindingsResponse.getDefaultInstance()) return this; if (policyBindingsBuilder_ == null) { if (!other.policyBindings_.isEmpty()) { if (policyBindings_.isEmpty()) { policyBindings_ = other.policyBindings_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePolicyBindingsIsMutable(); policyBindings_.addAll(other.policyBindings_); } onChanged(); } } else { if (!other.policyBindings_.isEmpty()) { if (policyBindingsBuilder_.isEmpty()) { policyBindingsBuilder_.dispose(); policyBindingsBuilder_ = null; policyBindings_ = other.policyBindings_; bitField0_ = (bitField0_ & ~0x00000001); policyBindingsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPolicyBindingsFieldBuilder() : null; } else { policyBindingsBuilder_.addAllMessages(other.policyBindings_); } } } 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.iam.v3beta.PolicyBinding m = input.readMessage( com.google.iam.v3beta.PolicyBinding.parser(), extensionRegistry); if (policyBindingsBuilder_ == null) { ensurePolicyBindingsIsMutable(); policyBindings_.add(m); } else { policyBindingsBuilder_.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.iam.v3beta.PolicyBinding> policyBindings_ = java.util.Collections.emptyList(); private void ensurePolicyBindingsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { policyBindings_ = new java.util.ArrayList<com.google.iam.v3beta.PolicyBinding>(policyBindings_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.iam.v3beta.PolicyBinding, com.google.iam.v3beta.PolicyBinding.Builder, com.google.iam.v3beta.PolicyBindingOrBuilder> policyBindingsBuilder_; /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public java.util.List<com.google.iam.v3beta.PolicyBinding> getPolicyBindingsList() { if (policyBindingsBuilder_ == null) { return java.util.Collections.unmodifiableList(policyBindings_); } else { return policyBindingsBuilder_.getMessageList(); } } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public int getPolicyBindingsCount() { if (policyBindingsBuilder_ == null) { return policyBindings_.size(); } else { return policyBindingsBuilder_.getCount(); } } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public com.google.iam.v3beta.PolicyBinding getPolicyBindings(int index) { if (policyBindingsBuilder_ == null) { return policyBindings_.get(index); } else { return policyBindingsBuilder_.getMessage(index); } } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder setPolicyBindings(int index, com.google.iam.v3beta.PolicyBinding value) { if (policyBindingsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePolicyBindingsIsMutable(); policyBindings_.set(index, value); onChanged(); } else { policyBindingsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder setPolicyBindings( int index, com.google.iam.v3beta.PolicyBinding.Builder builderForValue) { if (policyBindingsBuilder_ == null) { ensurePolicyBindingsIsMutable(); policyBindings_.set(index, builderForValue.build()); onChanged(); } else { policyBindingsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder addPolicyBindings(com.google.iam.v3beta.PolicyBinding value) { if (policyBindingsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePolicyBindingsIsMutable(); policyBindings_.add(value); onChanged(); } else { policyBindingsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder addPolicyBindings(int index, com.google.iam.v3beta.PolicyBinding value) { if (policyBindingsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePolicyBindingsIsMutable(); policyBindings_.add(index, value); onChanged(); } else { policyBindingsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder addPolicyBindings(com.google.iam.v3beta.PolicyBinding.Builder builderForValue) { if (policyBindingsBuilder_ == null) { ensurePolicyBindingsIsMutable(); policyBindings_.add(builderForValue.build()); onChanged(); } else { policyBindingsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder addPolicyBindings( int index, com.google.iam.v3beta.PolicyBinding.Builder builderForValue) { if (policyBindingsBuilder_ == null) { ensurePolicyBindingsIsMutable(); policyBindings_.add(index, builderForValue.build()); onChanged(); } else { policyBindingsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder addAllPolicyBindings( java.lang.Iterable<? extends com.google.iam.v3beta.PolicyBinding> values) { if (policyBindingsBuilder_ == null) { ensurePolicyBindingsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, policyBindings_); onChanged(); } else { policyBindingsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder clearPolicyBindings() { if (policyBindingsBuilder_ == null) { policyBindings_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { policyBindingsBuilder_.clear(); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public Builder removePolicyBindings(int index) { if (policyBindingsBuilder_ == null) { ensurePolicyBindingsIsMutable(); policyBindings_.remove(index); onChanged(); } else { policyBindingsBuilder_.remove(index); } return this; } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public com.google.iam.v3beta.PolicyBinding.Builder getPolicyBindingsBuilder(int index) { return getPolicyBindingsFieldBuilder().getBuilder(index); } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public com.google.iam.v3beta.PolicyBindingOrBuilder getPolicyBindingsOrBuilder(int index) { if (policyBindingsBuilder_ == null) { return policyBindings_.get(index); } else { return policyBindingsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public java.util.List<? extends com.google.iam.v3beta.PolicyBindingOrBuilder> getPolicyBindingsOrBuilderList() { if (policyBindingsBuilder_ != null) { return policyBindingsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(policyBindings_); } } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public com.google.iam.v3beta.PolicyBinding.Builder addPolicyBindingsBuilder() { return getPolicyBindingsFieldBuilder() .addBuilder(com.google.iam.v3beta.PolicyBinding.getDefaultInstance()); } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public com.google.iam.v3beta.PolicyBinding.Builder addPolicyBindingsBuilder(int index) { return getPolicyBindingsFieldBuilder() .addBuilder(index, com.google.iam.v3beta.PolicyBinding.getDefaultInstance()); } /** * * * <pre> * The policy bindings bound to the specified target. * </pre> * * <code>repeated .google.iam.v3beta.PolicyBinding policy_bindings = 1;</code> */ public java.util.List<com.google.iam.v3beta.PolicyBinding.Builder> getPolicyBindingsBuilderList() { return getPolicyBindingsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.iam.v3beta.PolicyBinding, com.google.iam.v3beta.PolicyBinding.Builder, com.google.iam.v3beta.PolicyBindingOrBuilder> getPolicyBindingsFieldBuilder() { if (policyBindingsBuilder_ == null) { policyBindingsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.iam.v3beta.PolicyBinding, com.google.iam.v3beta.PolicyBinding.Builder, com.google.iam.v3beta.PolicyBindingOrBuilder>( policyBindings_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); policyBindings_ = null; } return policyBindingsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. 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 [(.google.api.field_behavior) = OPTIONAL];</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.iam.v3beta.SearchTargetPolicyBindingsResponse) } // @@protoc_insertion_point(class_scope:google.iam.v3beta.SearchTargetPolicyBindingsResponse) private static final com.google.iam.v3beta.SearchTargetPolicyBindingsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.iam.v3beta.SearchTargetPolicyBindingsResponse(); } public static com.google.iam.v3beta.SearchTargetPolicyBindingsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchTargetPolicyBindingsResponse> PARSER = new com.google.protobuf.AbstractParser<SearchTargetPolicyBindingsResponse>() { @java.lang.Override public SearchTargetPolicyBindingsResponse 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<SearchTargetPolicyBindingsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchTargetPolicyBindingsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.iam.v3beta.SearchTargetPolicyBindingsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
hibernate/hibernate-orm
35,833
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/H2LegacyDialect.java
/* * SPDX-License-Identifier: Apache-2.0 * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.community.dialect; import java.sql.CallableStatement; import java.sql.SQLException; import java.sql.Types; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.checkerframework.checker.nullness.qual.Nullable; import org.hibernate.PessimisticLockException; import org.hibernate.QueryTimeoutException; import org.hibernate.boot.model.FunctionContributions; import org.hibernate.boot.model.TypeContributions; import org.hibernate.dialect.*; import org.hibernate.dialect.aggregate.AggregateSupport; import org.hibernate.dialect.aggregate.H2AggregateSupport; import org.hibernate.dialect.function.CommonFunctionFactory; import org.hibernate.dialect.identity.H2FinalTableIdentityColumnSupport; import org.hibernate.dialect.identity.H2IdentityColumnSupport; import org.hibernate.dialect.identity.IdentityColumnSupport; import org.hibernate.dialect.lock.internal.H2LockingSupport; import org.hibernate.dialect.lock.spi.LockingSupport; import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.pagination.LimitOffsetLimitHandler; import org.hibernate.dialect.pagination.OffsetFetchLimitHandler; import org.hibernate.dialect.sequence.H2V1SequenceSupport; import org.hibernate.dialect.sequence.H2V2SequenceSupport; import org.hibernate.dialect.sequence.SequenceSupport; import org.hibernate.dialect.temptable.StandardLocalTemporaryTableStrategy; import org.hibernate.dialect.temptable.TemporaryTableKind; import org.hibernate.dialect.temptable.TemporaryTableStrategy; import org.hibernate.dialect.type.H2DurationIntervalSecondJdbcType; import org.hibernate.dialect.type.H2JsonArrayJdbcTypeConstructor; import org.hibernate.dialect.type.H2JsonJdbcType; import org.hibernate.dialect.unique.CreateTableUniqueDelegate; import org.hibernate.dialect.unique.UniqueDelegate; import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor; import org.hibernate.exception.spi.ViolatedConstraintNameExtractor; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.StringHelper; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.spi.RuntimeModelCreationContext; import org.hibernate.query.sqm.CastType; import org.hibernate.query.common.FetchClauseType; import org.hibernate.query.sqm.IntervalType; import org.hibernate.dialect.NullOrdering; import org.hibernate.query.common.TemporalUnit; import org.hibernate.query.sqm.mutation.spi.BeforeUseAction; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableInsertStrategy; import org.hibernate.query.sqm.mutation.internal.temptable.LocalTemporaryTableMutationStrategy; import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy; import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy; import org.hibernate.service.ServiceRegistry; import org.hibernate.sql.ast.SqlAstNodeRenderingMode; import org.hibernate.sql.ast.SqlAstTranslator; import org.hibernate.sql.ast.SqlAstTranslatorFactory; import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.StandardSqlAstTranslatorFactory; import org.hibernate.sql.ast.tree.Statement; import org.hibernate.sql.exec.spi.JdbcOperation; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorH2DatabaseImpl; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorNoOpImpl; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; import org.hibernate.type.descriptor.jdbc.EnumJdbcType; import org.hibernate.type.descriptor.jdbc.JdbcType; import org.hibernate.type.descriptor.jdbc.OrdinalEnumJdbcType; import org.hibernate.type.descriptor.jdbc.TimeAsTimestampWithTimeZoneJdbcType; import org.hibernate.type.descriptor.jdbc.TimeUtcAsJdbcTimeJdbcType; import org.hibernate.type.descriptor.jdbc.TimeUtcAsOffsetTimeJdbcType; import org.hibernate.type.descriptor.jdbc.TimestampUtcAsInstantJdbcType; import org.hibernate.type.descriptor.jdbc.UUIDJdbcType; import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; import org.hibernate.type.descriptor.sql.internal.DdlTypeImpl; import org.hibernate.type.descriptor.sql.internal.NativeEnumDdlTypeImpl; import org.hibernate.type.descriptor.sql.internal.NativeOrdinalEnumDdlTypeImpl; import org.hibernate.type.descriptor.sql.spi.DdlTypeRegistry; import org.hibernate.type.spi.TypeConfiguration; import jakarta.persistence.TemporalType; import static org.hibernate.internal.CoreMessageLogger.CORE_LOGGER; import static org.hibernate.query.common.TemporalUnit.SECOND; import static org.hibernate.type.SqlTypes.ARRAY; import static org.hibernate.type.SqlTypes.BIGINT; import static org.hibernate.type.SqlTypes.BINARY; import static org.hibernate.type.SqlTypes.CHAR; import static org.hibernate.type.SqlTypes.DECIMAL; import static org.hibernate.type.SqlTypes.DOUBLE; import static org.hibernate.type.SqlTypes.FLOAT; import static org.hibernate.type.SqlTypes.GEOMETRY; import static org.hibernate.type.SqlTypes.INTERVAL_SECOND; import static org.hibernate.type.SqlTypes.JSON; import static org.hibernate.type.SqlTypes.LONG32NVARCHAR; import static org.hibernate.type.SqlTypes.LONG32VARBINARY; import static org.hibernate.type.SqlTypes.LONG32VARCHAR; import static org.hibernate.type.SqlTypes.NCHAR; import static org.hibernate.type.SqlTypes.NUMERIC; import static org.hibernate.type.SqlTypes.NVARCHAR; import static org.hibernate.type.SqlTypes.OTHER; import static org.hibernate.type.SqlTypes.TIMESTAMP_UTC; import static org.hibernate.type.SqlTypes.TIMESTAMP_WITH_TIMEZONE; import static org.hibernate.type.SqlTypes.TIME_WITH_TIMEZONE; import static org.hibernate.type.SqlTypes.UUID; import static org.hibernate.type.SqlTypes.VARBINARY; import static org.hibernate.type.SqlTypes.VARCHAR; import static org.hibernate.type.descriptor.DateTimeUtils.appendAsDate; import static org.hibernate.type.descriptor.DateTimeUtils.appendAsLocalTime; import static org.hibernate.type.descriptor.DateTimeUtils.appendAsTime; import static org.hibernate.type.descriptor.DateTimeUtils.appendAsTimestampWithMillis; import static org.hibernate.type.descriptor.DateTimeUtils.appendAsTimestampWithNanos; /** * A legacy {@linkplain Dialect SQL dialect} for H2. * * @author Thomas Mueller * @author Jürgen Kreitler */ public class H2LegacyDialect extends Dialect { private final LimitHandler limitHandler; private final boolean ansiSequence; private final boolean cascadeConstraints; private final boolean useLocalTime; private final SequenceInformationExtractor sequenceInformationExtractor; private final String querySequenceString; private final UniqueDelegate uniqueDelegate = new CreateTableUniqueDelegate( this ); public H2LegacyDialect(DialectResolutionInfo info) { this( parseVersion( info ) ); registerKeywords( info ); } public H2LegacyDialect() { this( SimpleDatabaseVersion.ZERO_VERSION ); } public H2LegacyDialect(DatabaseVersion version) { super(version); // https://github.com/h2database/h2database/commit/b2cdf84e0b84eb8a482fa7dccdccc1ab95241440 limitHandler = version.isSameOrAfter( 1, 4, 195 ) ? OffsetFetchLimitHandler.INSTANCE : LimitOffsetLimitHandler.OFFSET_ONLY_INSTANCE; if ( version.isBefore( 1, 2, 139 ) ) { CORE_LOGGER.unsupportedMultiTableBulkHqlJpaql( version.getMajor(), version.getMinor(), version.getMicro() ); } // supportsTuplesInSubqueries = version.isSameOrAfter( 1, 4, 198 ); // Prior to 1.4.200 there was no support for 'current value for sequence_name' // After 2.0.202 there is no support for 'sequence_name.nextval' and 'sequence_name.currval' ansiSequence = version.isSameOrAfter( 1, 4, 200 ); // Prior to 1.4.200 the 'cascade' in 'drop table' was implicit cascadeConstraints = version.isSameOrAfter( 1, 4, 200 ); // 1.4.200 introduced changes in current_time and current_timestamp useLocalTime = version.isSameOrAfter( 1, 4, 200 ); if ( version.isSameOrAfter( 1, 4, 32 ) ) { this.sequenceInformationExtractor = version.isSameOrAfter( 1, 4, 201 ) ? SequenceInformationExtractorLegacyImpl.INSTANCE : SequenceInformationExtractorH2DatabaseImpl.INSTANCE; this.querySequenceString = "select * from INFORMATION_SCHEMA.SEQUENCES"; } else { this.sequenceInformationExtractor = SequenceInformationExtractorNoOpImpl.INSTANCE; this.querySequenceString = null; } } private static DatabaseVersion parseVersion(DialectResolutionInfo info) { return DatabaseVersion.make( info.getMajor(), info.getMinor(), parseBuildId( info ) ); } private static int parseBuildId(DialectResolutionInfo info) { final String databaseVersion = info.getDatabaseVersion(); if ( databaseVersion == null ) { return 0; } final String[] bits = StringHelper.split( ". ", databaseVersion ); return bits.length > 2 ? Integer.parseInt( bits[2] ) : 0; } @Override public boolean getDefaultNonContextualLobCreation() { // http://code.google.com/p/h2database/issues/detail?id=235 return true; } @Override public boolean supportsStandardArrays() { return getVersion().isSameOrAfter( 2 ); } @Override public boolean useArrayForMultiValuedParameters() { // Performance is worse than the in-predicate version return false; } @Override protected String columnType(int sqlTypeCode) { switch ( sqlTypeCode ) { // prior to version 2.0, H2 reported NUMERIC columns as DECIMAL, // which caused problems for schema update tool case NUMERIC: return getVersion().isBefore( 2 ) ? columnType( DECIMAL ) : super.columnType( sqlTypeCode ); // Support was only added in 2.0 case TIME_WITH_TIMEZONE: return getVersion().isBefore( 2 ) ? columnType( TIMESTAMP_WITH_TIMEZONE ) : super.columnType( sqlTypeCode ); case NCHAR: return columnType( CHAR ); case NVARCHAR: return columnType( VARCHAR ); default: return super.columnType( sqlTypeCode ); } } @Override protected String castType(int sqlTypeCode) { switch ( sqlTypeCode ) { case CHAR: case NCHAR: return "char"; case VARCHAR: case NVARCHAR: case LONG32VARCHAR: case LONG32NVARCHAR: return "varchar"; case BINARY: case VARBINARY: case LONG32VARBINARY: return "varbinary"; } return super.castType( sqlTypeCode ); } @Override protected void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { super.registerColumnTypes( typeContributions, serviceRegistry ); final DdlTypeRegistry ddlTypeRegistry = typeContributions.getTypeConfiguration().getDdlTypeRegistry(); if ( getVersion().isBefore( 2 ) ) { ddlTypeRegistry.addDescriptor( new DdlTypeImpl( ARRAY, "array", this ) ); } if ( getVersion().isSameOrAfter( 1, 4, 197 ) ) { ddlTypeRegistry.addDescriptor( new DdlTypeImpl( UUID, "uuid", this ) ); ddlTypeRegistry.addDescriptor( new DdlTypeImpl( GEOMETRY, "geometry", this ) ); if ( getVersion().isSameOrAfter( 1, 4, 198 ) ) { ddlTypeRegistry.addDescriptor( new DdlTypeImpl( INTERVAL_SECOND, "interval second($p,$s)", this ) ); } if ( getVersion().isSameOrAfter( 1, 4, 200 ) ) { ddlTypeRegistry.addDescriptor( new DdlTypeImpl( JSON, "json", this ) ); } } ddlTypeRegistry.addDescriptor( new NativeEnumDdlTypeImpl( this ) ); ddlTypeRegistry.addDescriptor( new NativeOrdinalEnumDdlTypeImpl( this ) ); } @Override public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { super.contributeTypes( typeContributions, serviceRegistry ); final JdbcTypeRegistry jdbcTypeRegistry = typeContributions.getTypeConfiguration() .getJdbcTypeRegistry(); if ( getVersion().isBefore( 2 ) ) { // Support for TIME_WITH_TIMEZONE was only added in 2.0 jdbcTypeRegistry.addDescriptor( TimeAsTimestampWithTimeZoneJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptor( TimeUtcAsJdbcTimeJdbcType.INSTANCE ); } else { jdbcTypeRegistry.addDescriptor( TimeUtcAsOffsetTimeJdbcType.INSTANCE ); } jdbcTypeRegistry.addDescriptor( TIMESTAMP_UTC, TimestampUtcAsInstantJdbcType.INSTANCE ); if ( getVersion().isSameOrAfter( 1, 4, 197 ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( UUIDJdbcType.INSTANCE ); } if ( getVersion().isSameOrAfter( 1, 4, 198 ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( H2DurationIntervalSecondJdbcType.INSTANCE ); } if ( getVersion().isSameOrAfter( 1, 4, 200 ) ) { jdbcTypeRegistry.addDescriptorIfAbsent( H2JsonJdbcType.INSTANCE ); // Replace the standard array constructor jdbcTypeRegistry.addTypeConstructor( H2JsonArrayJdbcTypeConstructor.INSTANCE ); } jdbcTypeRegistry.addDescriptor( EnumJdbcType.INSTANCE ); jdbcTypeRegistry.addDescriptor( OrdinalEnumJdbcType.INSTANCE ); } @Override public AggregateSupport getAggregateSupport() { return H2AggregateSupport.valueOf( this ); } @Override public int getDefaultStatementBatchSize() { return 15; } public boolean hasOddDstBehavior() { // H2 1.4.200 has a bug: https://github.com/h2database/h2database/issues/3184 return getVersion().isSameOrAfter( 1, 4, 200 ); } @Override public void initializeFunctionRegistry(FunctionContributions functionContributions) { super.initializeFunctionRegistry(functionContributions); CommonFunctionFactory functionFactory = new CommonFunctionFactory(functionContributions); // H2 needs an actual argument type for aggregates like SUM, AVG, MIN, MAX to determine the result type functionFactory.aggregates( this, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER ); // AVG by default uses the input type, so we possibly need to cast the argument type, hence a special function functionFactory.avg_castingNonDoubleArguments( this, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER ); functionFactory.pi(); functionFactory.cot(); functionFactory.radians(); functionFactory.degrees(); functionFactory.log10(); functionFactory.mod_operator(); functionFactory.rand(); functionFactory.soundex(); functionFactory.translate(); functionFactory.bitand(); functionFactory.bitor(); functionFactory.bitxor(); functionFactory.bitnot(); functionFactory.bitAndOr(); functionFactory.yearMonthDay(); functionFactory.hourMinuteSecond(); functionFactory.dayOfWeekMonthYear(); functionFactory.weekQuarter(); functionFactory.daynameMonthname(); if ( useLocalTime ) { functionFactory.localtimeLocaltimestamp(); } functionFactory.trunc_dateTrunc(); functionFactory.dateTrunc(); functionFactory.bitLength(); functionFactory.octetLength(); functionFactory.ascii(); functionFactory.octetLength(); functionFactory.space(); functionFactory.repeat(); functionFactory.chr_char(); functionFactory.instr(); functionFactory.substr(); //also natively supports ANSI-style substring() functionFactory.position(); functionFactory.trim1(); functionFactory.concat_pipeOperator(); functionFactory.nowCurdateCurtime(); functionFactory.sysdate(); functionFactory.insert(); // functionFactory.everyAny(); //this would work too functionFactory.everyAny_boolAndOr(); functionFactory.median(); functionFactory.stddevPopSamp(); functionFactory.varPopSamp(); if ( getVersion().isSame( 1, 4, 200 ) ) { // See https://github.com/h2database/h2database/issues/2518 functionFactory.format_toChar(); } else { functionFactory.format_formatdatetime(); } functionFactory.rownum(); if ( getVersion().isSameOrAfter( 1, 4, 200 ) ) { functionFactory.windowFunctions(); functionFactory.inverseDistributionOrderedSetAggregates(); functionFactory.hypotheticalOrderedSetAggregates(); if ( getVersion().isSameOrAfter( 2 ) ) { functionFactory.listagg( null ); functionFactory.array(); functionFactory.arrayAggregate(); functionFactory.arrayPosition_h2( getMaximumArraySize() ); functionFactory.arrayPositions_h2( getMaximumArraySize() ); functionFactory.arrayLength_cardinality(); functionFactory.arrayConcat_operator(); functionFactory.arrayPrepend_operator(); functionFactory.arrayAppend_operator(); functionFactory.arrayContains_h2( getMaximumArraySize() ); functionFactory.arrayIntersects_h2( getMaximumArraySize() ); functionFactory.arrayGet_h2(); functionFactory.arraySet_h2( getMaximumArraySize() ); functionFactory.arrayRemove_h2( getMaximumArraySize() ); functionFactory.arrayRemoveIndex_h2( getMaximumArraySize() ); functionFactory.arraySlice(); functionFactory.arrayReplace_h2( getMaximumArraySize() ); functionFactory.arrayTrim_trim_array(); functionFactory.arrayFill_h2(); functionFactory.arrayToString_h2( getMaximumArraySize() ); if ( getVersion().isSameOrAfter( 2, 2, 220 ) ) { functionFactory.jsonValue_h2(); functionFactory.jsonQuery_h2(); functionFactory.jsonExists_h2(); functionFactory.jsonArrayAgg_h2(); functionFactory.jsonObjectAgg_h2(); } } else { functionFactory.jsonObject(); functionFactory.jsonArray(); // Use group_concat until 2.x as listagg was buggy functionFactory.listagg_groupConcat(); } functionFactory.xmlelement_h2(); functionFactory.xmlcomment(); functionFactory.xmlforest_h2(); functionFactory.xmlconcat_h2(); functionFactory.xmlpi_h2(); } else { functionFactory.listagg_groupConcat(); } functionFactory.unnest_h2( getMaximumArraySize() ); functionFactory.generateSeries_h2( getMaximumSeriesSize() ); functionFactory.jsonTable_h2( getMaximumArraySize() ); if ( getVersion().isSameOrAfter( 1, 4, 193 ) ) { functionFactory.regexpLike(); } } /** * H2 requires a very special emulation, because {@code unnest} is pretty much useless, * due to https://github.com/h2database/h2database/issues/1815. * This emulation uses {@code array_get}, {@code array_length} and {@code system_range} functions to roughly achieve the same, * but requires that {@code system_range} is fed with a "maximum array size". */ protected int getMaximumArraySize() { return 1000; } /** * Since H2 doesn't support ordinality for the {@code system_range} function or {@code lateral}, * it's impossible to use {@code system_range} for non-constant cases. * Luckily, correlation can be emulated, but requires that there is an upper bound on the amount * of elements that the series can return. */ protected int getMaximumSeriesSize() { return 10000; } @Override public @Nullable String getDefaultOrdinalityColumnName() { return "nord"; } @Override public void augmentPhysicalTableTypes(List<String> tableTypesList) { if ( getVersion().isSameOrAfter( 2 ) ) { tableTypesList.add( "BASE TABLE" ); } } @Override protected Integer resolveSqlTypeCode(String columnTypeName, TypeConfiguration typeConfiguration) { switch ( columnTypeName ) { case "FLOAT(24)": // Use REAL instead of FLOAT to get Float as recommended Java type return Types.REAL; } return super.resolveSqlTypeCode( columnTypeName, typeConfiguration ); } @Override public JdbcType resolveSqlTypeDescriptor( String columnTypeName, int jdbcTypeCode, int precision, int scale, JdbcTypeRegistry jdbcTypeRegistry) { // As of H2 2.0 we get a FLOAT type code even though it is a DOUBLE switch ( jdbcTypeCode ) { case FLOAT: if ( "DOUBLE PRECISION".equals( columnTypeName ) ) { return jdbcTypeRegistry.getDescriptor( DOUBLE ); } break; case OTHER: if ( "GEOMETRY".equals( columnTypeName ) ) { return jdbcTypeRegistry.getDescriptor( GEOMETRY ); } else if ( "JSON".equals( columnTypeName ) ) { return jdbcTypeRegistry.getDescriptor( JSON ); } break; } return super.resolveSqlTypeDescriptor( columnTypeName, jdbcTypeCode, precision, scale, jdbcTypeRegistry ); } @Override protected Integer resolveSqlTypeCode(String typeName, String baseTypeName, TypeConfiguration typeConfiguration) { switch ( baseTypeName ) { case "CHARACTER VARYING": return VARCHAR; } return super.resolveSqlTypeCode( typeName, baseTypeName, typeConfiguration ); } @Override public int getMaxVarcharLength() { return 1_048_576; } @Override public String currentTime() { return useLocalTime ? "localtime" : super.currentTime(); } @Override public String currentTimestamp() { return useLocalTime ? "localtimestamp" : super.currentTimestamp(); } @Override public String currentTimestampWithTimeZone() { return "current_timestamp"; } @Override public SqlAstTranslatorFactory getSqlAstTranslatorFactory() { return new StandardSqlAstTranslatorFactory() { @Override protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator(SessionFactoryImplementor sessionFactory, Statement statement) { return new H2LegacySqlAstTranslator<>( sessionFactory, statement ); } }; } /** * In H2, the extract() function does not return * fractional seconds for the field * {@link TemporalUnit#SECOND}. We work around * this here with two calls to extract(). */ @Override public String extractPattern(TemporalUnit unit) { return unit == SECOND ? "(" + super.extractPattern(unit) + "+extract(nanosecond from ?2)/1e9)" : super.extractPattern(unit); } @Override public String castPattern(CastType from, CastType to) { if ( from == CastType.STRING && to == CastType.BOOLEAN ) { return "cast(?1 as ?2)"; } else { return super.castPattern( from, to ); } } @Override public String timestampaddPattern(TemporalUnit unit, TemporalType temporalType, IntervalType intervalType) { if ( intervalType != null ) { return "(?2+?3)"; } return "dateadd(?1,?2,?3)"; } @Override public String timestampdiffPattern(TemporalUnit unit, TemporalType fromTemporalType, TemporalType toTemporalType) { if ( unit == null ) { return "(?3-?2)"; } return "datediff(?1,?2,?3)"; } @Override public void appendDateTimeLiteral( SqlAppender appender, TemporalAccessor temporalAccessor, TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, temporalAccessor ); appender.appendSql( '\'' ); break; case TIME: if ( supportsTimeLiteralOffset() && temporalAccessor.isSupported( ChronoField.OFFSET_SECONDS ) ) { appender.appendSql( "time with time zone '" ); appendAsTime( appender, temporalAccessor, supportsTemporalLiteralOffset(), jdbcTimeZone ); } else { appender.appendSql( "time '" ); appendAsLocalTime( appender, temporalAccessor ); } appender.appendSql( '\'' ); break; case TIMESTAMP: if ( supportsTemporalLiteralOffset() && temporalAccessor.isSupported( ChronoField.OFFSET_SECONDS ) ) { appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithNanos( appender, temporalAccessor, true, jdbcTimeZone ); appender.appendSql( '\'' ); } else { appender.appendSql( "timestamp '" ); appendAsTimestampWithNanos( appender, temporalAccessor, false, jdbcTimeZone ); appender.appendSql( '\'' ); } break; default: throw new IllegalArgumentException(); } } @Override public void appendDateTimeLiteral(SqlAppender appender, Date date, TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, date ); appender.appendSql( '\'' ); break; case TIME: if ( supportsTimeLiteralOffset() ) { appender.appendSql( "time with time zone '" ); appendAsTime( appender, date, jdbcTimeZone ); } else { appender.appendSql( "time '" ); appendAsLocalTime( appender, date ); } appender.appendSql( '\'' ); break; case TIMESTAMP: appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithNanos( appender, date, jdbcTimeZone ); appender.appendSql( '\'' ); break; default: throw new IllegalArgumentException(); } } @Override public void appendDateTimeLiteral( SqlAppender appender, Calendar calendar, TemporalType precision, TimeZone jdbcTimeZone) { switch ( precision ) { case DATE: appender.appendSql( "date '" ); appendAsDate( appender, calendar ); appender.appendSql( '\'' ); break; case TIME: if ( supportsTimeLiteralOffset() ) { appender.appendSql( "time with time zone '" ); appendAsTime( appender, calendar, jdbcTimeZone ); } else { appender.appendSql( "time '" ); appendAsLocalTime( appender, calendar ); } appender.appendSql( '\'' ); break; case TIMESTAMP: appender.appendSql( "timestamp with time zone '" ); appendAsTimestampWithMillis( appender, calendar, jdbcTimeZone ); appender.appendSql( '\'' ); break; default: throw new IllegalArgumentException(); } } public boolean supportsTimeLiteralOffset() { return getVersion().isSameOrAfter( 1, 4, 200 ); } @Override public boolean supportsTemporalLiteralOffset() { return true; } @Override public TimeZoneSupport getTimeZoneSupport() { return TimeZoneSupport.NATIVE; } @Override public void appendBooleanValueString(SqlAppender appender, boolean bool) { appender.appendSql( bool ); } @Override public LimitHandler getLimitHandler() { return limitHandler; } @Override public LockingSupport getLockingSupport() { return getVersion().isSameOrAfter( 2, 2, 220 ) ? H2LockingSupport.INSTANCE : H2LockingSupport.LEGACY_INSTANCE; } @Override public boolean supportsDistinctFromPredicate() { return true; } @Override public boolean supportsIfExistsAfterTableName() { return !supportsIfExistsBeforeTableName(); } @Override public boolean supportsIfExistsBeforeTableName() { return cascadeConstraints; } @Override public boolean supportsIfExistsAfterAlterTable() { return cascadeConstraints; } @Override public boolean supportsIfExistsBeforeConstraintName() { return true; } @Override public String getCascadeConstraintsString() { return cascadeConstraints ? " cascade " : super.getCascadeConstraintsString(); } @Override public boolean supportsCommentOn() { return true; } @Override public boolean dropConstraints() { return false; } @Override public SequenceSupport getSequenceSupport() { return ansiSequence ? H2V2SequenceSupport.INSTANCE: H2V1SequenceSupport.INSTANCE; } @Override public String getQuerySequencesString() { return querySequenceString; } @Override public SequenceInformationExtractor getSequenceInformationExtractor() { return sequenceInformationExtractor; } @Override public NullOrdering getNullOrdering() { return NullOrdering.SMALLEST; } @Override public SqmMultiTableMutationStrategy getFallbackSqmMutationStrategy( EntityMappingType entityDescriptor, RuntimeModelCreationContext runtimeModelCreationContext) { return new LocalTemporaryTableMutationStrategy( entityDescriptor, runtimeModelCreationContext ); } @Override public SqmMultiTableInsertStrategy getFallbackSqmInsertStrategy( EntityMappingType entityDescriptor, RuntimeModelCreationContext runtimeModelCreationContext) { return new LocalTemporaryTableInsertStrategy( entityDescriptor, runtimeModelCreationContext ); } @Override public TemporaryTableKind getSupportedTemporaryTableKind() { return TemporaryTableKind.LOCAL; } @Override public TemporaryTableStrategy getLocalTemporaryTableStrategy() { return StandardLocalTemporaryTableStrategy.INSTANCE; } @Override public BeforeUseAction getTemporaryTableBeforeUseAction() { return StandardLocalTemporaryTableStrategy.INSTANCE.getTemporaryTableBeforeUseAction(); } @Override public ViolatedConstraintNameExtractor getViolatedConstraintNameExtractor() { return EXTRACTOR; } private static final ViolatedConstraintNameExtractor EXTRACTOR = new TemplatedViolatedConstraintNameExtractor( sqle -> { // 23000: Check constraint violation: {0} // 23001: Unique index or primary key violation: {0} if ( sqle.getSQLState().startsWith( "23" ) ) { final String message = sqle.getMessage(); final int idx = message.indexOf( "violation: " ); if ( idx > 0 ) { String constraintName = message.substring( idx + "violation: ".length() ); if ( sqle.getSQLState().equals( "23506" ) ) { constraintName = constraintName.substring( 1, constraintName.indexOf( ':' ) ); } return constraintName; } } return null; } ); @Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return (sqlException, message, sql) -> { final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException ); final String constraintName; switch (errorCode) { case 23505: // Unique constraint violation constraintName = getViolatedConstraintNameExtractor().extractConstraintName(sqlException); return new ConstraintViolationException( message, sqlException, sql, ConstraintViolationException.ConstraintKind.UNIQUE, constraintName ); case 40001: // DEADLOCK DETECTED return new LockAcquisitionException(message, sqlException, sql); case 50200: // LOCK NOT AVAILABLE return new PessimisticLockException(message, sqlException, sql); case 90006: // NULL not allowed for column [90006-145] constraintName = getViolatedConstraintNameExtractor().extractConstraintName(sqlException); return new ConstraintViolationException(message, sqlException, sql, constraintName); case 57014: return new QueryTimeoutException( message, sqlException, sql ); } return null; }; } @Override public boolean supportsCurrentTimestampSelection() { return true; } @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } @Override public String getCurrentTimestampSelectString() { return "call current_timestamp()"; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public boolean supportsLobValueChangePropagation() { return false; } @Override public boolean supportsTupleCounts() { return true; } @Override public boolean requiresParensForTupleDistinctCounts() { return true; } @Override public boolean doesReadCommittedCauseWritersToBlockReaders() { // see http://groups.google.com/group/h2-database/browse_thread/thread/562d8a49e2dabe99?hl=en return true; } @Override public SelectItemReferenceStrategy getGroupBySelectItemReferenceStrategy() { return SelectItemReferenceStrategy.ALIAS; } @Override public boolean supportsOffsetInSubquery() { return true; } @Override public boolean supportsWindowFunctions() { return getVersion().isSameOrAfter( 1, 4, 200 ); } @Override public boolean supportsRecursiveCTE() { return getVersion().isSameOrAfter( 1, 4, 196 ); } @Override public boolean supportsFetchClause(FetchClauseType type) { return getVersion().isSameOrAfter( 1, 4, 198 ); } @Override public FunctionalDependencyAnalysisSupport getFunctionalDependencyAnalysisSupport() { return FunctionalDependencyAnalysisSupportImpl.TABLE_GROUP_AND_CONSTANTS; } @Override public IdentityColumnSupport getIdentityColumnSupport() { return getVersion().isSameOrAfter( 2 ) ? H2FinalTableIdentityColumnSupport.INSTANCE : H2IdentityColumnSupport.INSTANCE; } @Override public int registerResultSetOutParameter(CallableStatement statement, int position) throws SQLException { return position; } @Override public String getQueryHintString(String query, String hints) { return addUseIndexQueryHint( query, hints ); } @Override public void appendDatetimeFormat(SqlAppender appender, String format) { if ( getVersion().isSame( 1, 4, 200 ) ) { // See https://github.com/h2database/h2database/issues/2518 appender.appendSql( OracleDialect.datetimeFormat( format, true, true ).result() ); } else { appender.appendSql( new Replacer( format, "'", "''" ) .replace("e", "u") .replace( "xxx", "XXX" ) .replace( "xx", "XX" ) .replace( "x", "X" ) .result() ); } } public String translateExtractField(TemporalUnit unit) { switch ( unit ) { case DAY_OF_MONTH: return "day"; case WEEK: return "iso_week"; default: return unit.toString(); } } @Override public String generatedAs(String generatedAs) { return " generated always as (" + generatedAs + ")"; } @Override public boolean canDisableConstraints() { return true; } @Override public String getEnableConstraintsStatement() { return "set referential_integrity true"; } @Override public String getEnumTypeDeclaration(String name, String[] values) { StringBuilder type = new StringBuilder(); type.append( "enum (" ); String separator = ""; for ( String value : values ) { type.append( separator ).append('\'').append( value ).append('\''); separator = ","; } return type.append( ')' ).toString(); } @Override public String getDisableConstraintsStatement() { return "set referential_integrity false"; } @Override public UniqueDelegate getUniqueDelegate() { return uniqueDelegate; } @Override public String rowId(String rowId) { return "_rowid_"; } @Override public int rowIdSqlType() { return BIGINT; } @Override public DmlTargetColumnQualifierSupport getDmlTargetColumnQualifierSupport() { return DmlTargetColumnQualifierSupport.TABLE_ALIAS; } @Override public String getCaseInsensitiveLike() { if ( getVersion().isSameOrAfter( 1, 4, 194 ) ) { return "ilike"; } else { return super.getCaseInsensitiveLike(); } } @Override public boolean supportsPartitionBy() { return getVersion().isSameOrAfter( 1, 4, 200 ); } @Override public boolean supportsCaseInsensitiveLike() { return getVersion().isSameOrAfter( 1, 4, 194 ); } @Override public boolean supportsValuesList() { return true; } @Override public String getDual() { return "dual"; } @Override public boolean supportsFilterClause() { return getVersion().isSameOrAfter( 1, 4, 197 ); } @Override public boolean supportsRowConstructor() { return getVersion().isSameOrAfter( 2 ); } @Override public boolean supportsArrayConstructor() { return getVersion().isSameOrAfter( 2 ); } @Override public boolean supportsJoinInMutationStatementSubquery() { return false; } @Override public boolean supportsNullPrecedence() { // Support for nulls clause in listagg was added in 2.0 return getVersion().isSameOrAfter( 2 ); } @Override public boolean supportsRowValueConstructorSyntax() { // Just a guess return getVersion().isSameOrAfter( 1, 4, 197 ); } @Override public boolean supportsRowValueConstructorDistinctFromSyntax() { // Seems that before, this was buggy return getVersion().isSameOrAfter( 1, 4, 200 ); } @Override public boolean supportsWithClauseInSubquery() { return false; } @Override public boolean supportsRowValueConstructorSyntaxInQuantifiedPredicates() { // Just a guess return getVersion().isSameOrAfter( 1, 4, 197 ); } @Override public boolean supportsRowValueConstructorSyntaxInInList() { // Just a guess return getVersion().isSameOrAfter( 1, 4, 197 ); } }
googleapis/google-cloud-java
37,778
java-automl/proto-google-cloud-automl-v1beta1/src/main/java/com/google/cloud/automl/v1beta1/ListDatasetsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/automl/v1beta1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.automl.v1beta1; /** * * * <pre> * Request message for [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.ListDatasetsRequest} */ public final class ListDatasetsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.ListDatasetsRequest) ListDatasetsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListDatasetsRequest.newBuilder() to construct. private ListDatasetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDatasetsRequest() { parent_ = ""; filter_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDatasetsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.ListDatasetsRequest.class, com.google.cloud.automl.v1beta1.ListDatasetsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 4; private int pageSize_ = 0; /** * * * <pre> * Requested page size. Server may return fewer results than requested. * If unspecified, server will pick a default size. * </pre> * * <code>int32 page_size = 4;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, filter_); } if (pageSize_ != 0) { output.writeInt32(4, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, filter_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(4, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.automl.v1beta1.ListDatasetsRequest)) { return super.equals(obj); } com.google.cloud.automl.v1beta1.ListDatasetsRequest other = (com.google.cloud.automl.v1beta1.ListDatasetsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getFilter().equals(other.getFilter())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.automl.v1beta1.ListDatasetsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.ListDatasetsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.automl.v1beta1.ListDatasetsRequest) com.google.cloud.automl.v1beta1.ListDatasetsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.ListDatasetsRequest.class, com.google.cloud.automl.v1beta1.ListDatasetsRequest.Builder.class); } // Construct using com.google.cloud.automl.v1beta1.ListDatasetsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; filter_ = ""; pageSize_ = 0; pageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListDatasetsRequest_descriptor; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListDatasetsRequest getDefaultInstanceForType() { return com.google.cloud.automl.v1beta1.ListDatasetsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.automl.v1beta1.ListDatasetsRequest build() { com.google.cloud.automl.v1beta1.ListDatasetsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListDatasetsRequest buildPartial() { com.google.cloud.automl.v1beta1.ListDatasetsRequest result = new com.google.cloud.automl.v1beta1.ListDatasetsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.automl.v1beta1.ListDatasetsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.filter_ = filter_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.pageToken_ = pageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.automl.v1beta1.ListDatasetsRequest) { return mergeFrom((com.google.cloud.automl.v1beta1.ListDatasetsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.automl.v1beta1.ListDatasetsRequest other) { if (other == com.google.cloud.automl.v1beta1.ListDatasetsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000002; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 26: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 26 case 32: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 32 case 50: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 50 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project from which to list datasets. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * An expression for filtering the results of the request. * * * `dataset_metadata` - for existence of the case (e.g. * `image_classification_dataset_metadata:*`). Some examples of * using the filter are: * * * `translation_dataset_metadata:*` --&gt; The dataset has * `translation_dataset_metadata`. * </pre> * * <code>string filter = 3;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Requested page size. Server may return fewer results than requested. * If unspecified, server will pick a default size. * </pre> * * <code>int32 page_size = 4;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Requested page size. Server may return fewer results than requested. * If unspecified, server will pick a default size. * </pre> * * <code>int32 page_size = 4;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Requested page size. Server may return fewer results than requested. * If unspecified, server will pick a default size. * </pre> * * <code>int32 page_size = 4;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000004); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * A token identifying a page of results for the server to return * Typically obtained via * [ListDatasetsResponse.next_page_token][google.cloud.automl.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [AutoMl.ListDatasets][google.cloud.automl.v1beta1.AutoMl.ListDatasets] call. * </pre> * * <code>string page_token = 6;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.automl.v1beta1.ListDatasetsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.ListDatasetsRequest) private static final com.google.cloud.automl.v1beta1.ListDatasetsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.automl.v1beta1.ListDatasetsRequest(); } public static com.google.cloud.automl.v1beta1.ListDatasetsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDatasetsRequest> PARSER = new com.google.protobuf.AbstractParser<ListDatasetsRequest>() { @java.lang.Override public ListDatasetsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListDatasetsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDatasetsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListDatasetsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,776
java-bigqueryreservation/proto-google-cloud-bigqueryreservation-v1/src/main/java/com/google/cloud/bigquery/reservation/v1/CreateAssignmentRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/reservation/v1/reservation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.reservation.v1; /** * * * <pre> * The request for * [ReservationService.CreateAssignment][google.cloud.bigquery.reservation.v1.ReservationService.CreateAssignment]. * Note: "bigquery.reservationAssignments.create" permission is required on the * related assignee. * </pre> * * Protobuf type {@code google.cloud.bigquery.reservation.v1.CreateAssignmentRequest} */ public final class CreateAssignmentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.reservation.v1.CreateAssignmentRequest) CreateAssignmentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateAssignmentRequest.newBuilder() to construct. private CreateAssignmentRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateAssignmentRequest() { parent_ = ""; assignmentId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateAssignmentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.reservation.v1.ReservationProto .internal_static_google_cloud_bigquery_reservation_v1_CreateAssignmentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.reservation.v1.ReservationProto .internal_static_google_cloud_bigquery_reservation_v1_CreateAssignmentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.class, com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </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 ASSIGNMENT_FIELD_NUMBER = 2; private com.google.cloud.bigquery.reservation.v1.Assignment assignment_; /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> * * @return Whether the assignment field is set. */ @java.lang.Override public boolean hasAssignment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> * * @return The assignment. */ @java.lang.Override public com.google.cloud.bigquery.reservation.v1.Assignment getAssignment() { return assignment_ == null ? com.google.cloud.bigquery.reservation.v1.Assignment.getDefaultInstance() : assignment_; } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ @java.lang.Override public com.google.cloud.bigquery.reservation.v1.AssignmentOrBuilder getAssignmentOrBuilder() { return assignment_ == null ? com.google.cloud.bigquery.reservation.v1.Assignment.getDefaultInstance() : assignment_; } public static final int ASSIGNMENT_ID_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object assignmentId_ = ""; /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @return The assignmentId. */ @java.lang.Override public java.lang.String getAssignmentId() { java.lang.Object ref = assignmentId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assignmentId_ = s; return s; } } /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @return The bytes for assignmentId. */ @java.lang.Override public com.google.protobuf.ByteString getAssignmentIdBytes() { java.lang.Object ref = assignmentId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); assignmentId_ = 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, getAssignment()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assignmentId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, assignmentId_); } 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, getAssignment()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assignmentId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, assignmentId_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest)) { return super.equals(obj); } com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest other = (com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasAssignment() != other.hasAssignment()) return false; if (hasAssignment()) { if (!getAssignment().equals(other.getAssignment())) return false; } if (!getAssignmentId().equals(other.getAssignmentId())) 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 (hasAssignment()) { hash = (37 * hash) + ASSIGNMENT_FIELD_NUMBER; hash = (53 * hash) + getAssignment().hashCode(); } hash = (37 * hash) + ASSIGNMENT_ID_FIELD_NUMBER; hash = (53 * hash) + getAssignmentId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request for * [ReservationService.CreateAssignment][google.cloud.bigquery.reservation.v1.ReservationService.CreateAssignment]. * Note: "bigquery.reservationAssignments.create" permission is required on the * related assignee. * </pre> * * Protobuf type {@code google.cloud.bigquery.reservation.v1.CreateAssignmentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.reservation.v1.CreateAssignmentRequest) com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.reservation.v1.ReservationProto .internal_static_google_cloud_bigquery_reservation_v1_CreateAssignmentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.reservation.v1.ReservationProto .internal_static_google_cloud_bigquery_reservation_v1_CreateAssignmentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.class, com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.Builder.class); } // Construct using com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getAssignmentFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; assignment_ = null; if (assignmentBuilder_ != null) { assignmentBuilder_.dispose(); assignmentBuilder_ = null; } assignmentId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.reservation.v1.ReservationProto .internal_static_google_cloud_bigquery_reservation_v1_CreateAssignmentRequest_descriptor; } @java.lang.Override public com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest getDefaultInstanceForType() { return com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest build() { com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest buildPartial() { com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest result = new com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.assignment_ = assignmentBuilder_ == null ? assignment_ : assignmentBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assignmentId_ = assignmentId_; } 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.bigquery.reservation.v1.CreateAssignmentRequest) { return mergeFrom((com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest other) { if (other == com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasAssignment()) { mergeAssignment(other.getAssignment()); } if (!other.getAssignmentId().isEmpty()) { assignmentId_ = other.assignmentId_; 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(getAssignmentFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 34: { assignmentId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource name of the assignment * E.g. `projects/myproject/locations/US/reservations/team1-prod` * </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.bigquery.reservation.v1.Assignment assignment_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.reservation.v1.Assignment, com.google.cloud.bigquery.reservation.v1.Assignment.Builder, com.google.cloud.bigquery.reservation.v1.AssignmentOrBuilder> assignmentBuilder_; /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> * * @return Whether the assignment field is set. */ public boolean hasAssignment() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> * * @return The assignment. */ public com.google.cloud.bigquery.reservation.v1.Assignment getAssignment() { if (assignmentBuilder_ == null) { return assignment_ == null ? com.google.cloud.bigquery.reservation.v1.Assignment.getDefaultInstance() : assignment_; } else { return assignmentBuilder_.getMessage(); } } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ public Builder setAssignment(com.google.cloud.bigquery.reservation.v1.Assignment value) { if (assignmentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } assignment_ = value; } else { assignmentBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ public Builder setAssignment( com.google.cloud.bigquery.reservation.v1.Assignment.Builder builderForValue) { if (assignmentBuilder_ == null) { assignment_ = builderForValue.build(); } else { assignmentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ public Builder mergeAssignment(com.google.cloud.bigquery.reservation.v1.Assignment value) { if (assignmentBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && assignment_ != null && assignment_ != com.google.cloud.bigquery.reservation.v1.Assignment.getDefaultInstance()) { getAssignmentBuilder().mergeFrom(value); } else { assignment_ = value; } } else { assignmentBuilder_.mergeFrom(value); } if (assignment_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ public Builder clearAssignment() { bitField0_ = (bitField0_ & ~0x00000002); assignment_ = null; if (assignmentBuilder_ != null) { assignmentBuilder_.dispose(); assignmentBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ public com.google.cloud.bigquery.reservation.v1.Assignment.Builder getAssignmentBuilder() { bitField0_ |= 0x00000002; onChanged(); return getAssignmentFieldBuilder().getBuilder(); } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ public com.google.cloud.bigquery.reservation.v1.AssignmentOrBuilder getAssignmentOrBuilder() { if (assignmentBuilder_ != null) { return assignmentBuilder_.getMessageOrBuilder(); } else { return assignment_ == null ? com.google.cloud.bigquery.reservation.v1.Assignment.getDefaultInstance() : assignment_; } } /** * * * <pre> * Assignment resource to create. * </pre> * * <code>.google.cloud.bigquery.reservation.v1.Assignment assignment = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.reservation.v1.Assignment, com.google.cloud.bigquery.reservation.v1.Assignment.Builder, com.google.cloud.bigquery.reservation.v1.AssignmentOrBuilder> getAssignmentFieldBuilder() { if (assignmentBuilder_ == null) { assignmentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.reservation.v1.Assignment, com.google.cloud.bigquery.reservation.v1.Assignment.Builder, com.google.cloud.bigquery.reservation.v1.AssignmentOrBuilder>( getAssignment(), getParentForChildren(), isClean()); assignment_ = null; } return assignmentBuilder_; } private java.lang.Object assignmentId_ = ""; /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @return The assignmentId. */ public java.lang.String getAssignmentId() { java.lang.Object ref = assignmentId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assignmentId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @return The bytes for assignmentId. */ public com.google.protobuf.ByteString getAssignmentIdBytes() { java.lang.Object ref = assignmentId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); assignmentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @param value The assignmentId to set. * @return This builder for chaining. */ public Builder setAssignmentId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } assignmentId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @return This builder for chaining. */ public Builder clearAssignmentId() { assignmentId_ = getDefaultInstance().getAssignmentId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * The optional assignment ID. Assignment name will be generated automatically * if this field is empty. * This field must only contain lower case alphanumeric characters or dashes. * Max length is 64 characters. * </pre> * * <code>string assignment_id = 4;</code> * * @param value The bytes for assignmentId to set. * @return This builder for chaining. */ public Builder setAssignmentIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assignmentId_ = 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.bigquery.reservation.v1.CreateAssignmentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.reservation.v1.CreateAssignmentRequest) private static final com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest(); } public static com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateAssignmentRequest> PARSER = new com.google.protobuf.AbstractParser<CreateAssignmentRequest>() { @java.lang.Override public CreateAssignmentRequest 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<CreateAssignmentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateAssignmentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,803
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListExtensionsResponse.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/extension_registry_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Response message for * [ExtensionRegistryService.ListExtensions][google.cloud.aiplatform.v1beta1.ExtensionRegistryService.ListExtensions] * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListExtensionsResponse} */ public final class ListExtensionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListExtensionsResponse) ListExtensionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListExtensionsResponse.newBuilder() to construct. private ListExtensionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListExtensionsResponse() { extensions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListExtensionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.ExtensionRegistryServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListExtensionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.ExtensionRegistryServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListExtensionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.class, com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.Builder.class); } public static final int EXTENSIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1beta1.Extension> extensions_; /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.Extension> getExtensionsList() { return extensions_; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder> getExtensionsOrBuilderList() { return extensions_; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ @java.lang.Override public int getExtensionsCount() { return extensions_.size(); } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.Extension getExtensions(int index) { return extensions_.get(index); } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder getExtensionsOrBuilder(int index) { return extensions_.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 * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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 * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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 < extensions_.size(); i++) { output.writeMessage(1, extensions_.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 < extensions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, extensions_.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.ListExtensionsResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse other = (com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse) obj; if (!getExtensionsList().equals(other.getExtensionsList())) 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 (getExtensionsCount() > 0) { hash = (37 * hash) + EXTENSIONS_FIELD_NUMBER; hash = (53 * hash) + getExtensionsList().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.ListExtensionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse 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.ListExtensionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse 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.ListExtensionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse 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.ListExtensionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse 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.ListExtensionsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse 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.ListExtensionsResponse 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.ListExtensionsResponse 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.ListExtensionsResponse 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 * [ExtensionRegistryService.ListExtensions][google.cloud.aiplatform.v1beta1.ExtensionRegistryService.ListExtensions] * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListExtensionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListExtensionsResponse) com.google.cloud.aiplatform.v1beta1.ListExtensionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.ExtensionRegistryServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListExtensionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.ExtensionRegistryServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListExtensionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.class, com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (extensionsBuilder_ == null) { extensions_ = java.util.Collections.emptyList(); } else { extensions_ = null; extensionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.ExtensionRegistryServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListExtensionsResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse build() { com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse buildPartial() { com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse result = new com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse result) { if (extensionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { extensions_ = java.util.Collections.unmodifiableList(extensions_); bitField0_ = (bitField0_ & ~0x00000001); } result.extensions_ = extensions_; } else { result.extensions_ = extensionsBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse 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.ListExtensionsResponse) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse other) { if (other == com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse.getDefaultInstance()) return this; if (extensionsBuilder_ == null) { if (!other.extensions_.isEmpty()) { if (extensions_.isEmpty()) { extensions_ = other.extensions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureExtensionsIsMutable(); extensions_.addAll(other.extensions_); } onChanged(); } } else { if (!other.extensions_.isEmpty()) { if (extensionsBuilder_.isEmpty()) { extensionsBuilder_.dispose(); extensionsBuilder_ = null; extensions_ = other.extensions_; bitField0_ = (bitField0_ & ~0x00000001); extensionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getExtensionsFieldBuilder() : null; } else { extensionsBuilder_.addAllMessages(other.extensions_); } } } 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.Extension m = input.readMessage( com.google.cloud.aiplatform.v1beta1.Extension.parser(), extensionRegistry); if (extensionsBuilder_ == null) { ensureExtensionsIsMutable(); extensions_.add(m); } else { extensionsBuilder_.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.Extension> extensions_ = java.util.Collections.emptyList(); private void ensureExtensionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { extensions_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Extension>(extensions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Extension, com.google.cloud.aiplatform.v1beta1.Extension.Builder, com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder> extensionsBuilder_; /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.Extension> getExtensionsList() { if (extensionsBuilder_ == null) { return java.util.Collections.unmodifiableList(extensions_); } else { return extensionsBuilder_.getMessageList(); } } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public int getExtensionsCount() { if (extensionsBuilder_ == null) { return extensions_.size(); } else { return extensionsBuilder_.getCount(); } } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Extension getExtensions(int index) { if (extensionsBuilder_ == null) { return extensions_.get(index); } else { return extensionsBuilder_.getMessage(index); } } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder setExtensions(int index, com.google.cloud.aiplatform.v1beta1.Extension value) { if (extensionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtensionsIsMutable(); extensions_.set(index, value); onChanged(); } else { extensionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder setExtensions( int index, com.google.cloud.aiplatform.v1beta1.Extension.Builder builderForValue) { if (extensionsBuilder_ == null) { ensureExtensionsIsMutable(); extensions_.set(index, builderForValue.build()); onChanged(); } else { extensionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder addExtensions(com.google.cloud.aiplatform.v1beta1.Extension value) { if (extensionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtensionsIsMutable(); extensions_.add(value); onChanged(); } else { extensionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder addExtensions(int index, com.google.cloud.aiplatform.v1beta1.Extension value) { if (extensionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExtensionsIsMutable(); extensions_.add(index, value); onChanged(); } else { extensionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder addExtensions( com.google.cloud.aiplatform.v1beta1.Extension.Builder builderForValue) { if (extensionsBuilder_ == null) { ensureExtensionsIsMutable(); extensions_.add(builderForValue.build()); onChanged(); } else { extensionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder addExtensions( int index, com.google.cloud.aiplatform.v1beta1.Extension.Builder builderForValue) { if (extensionsBuilder_ == null) { ensureExtensionsIsMutable(); extensions_.add(index, builderForValue.build()); onChanged(); } else { extensionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder addAllExtensions( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Extension> values) { if (extensionsBuilder_ == null) { ensureExtensionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, extensions_); onChanged(); } else { extensionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder clearExtensions() { if (extensionsBuilder_ == null) { extensions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { extensionsBuilder_.clear(); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public Builder removeExtensions(int index) { if (extensionsBuilder_ == null) { ensureExtensionsIsMutable(); extensions_.remove(index); onChanged(); } else { extensionsBuilder_.remove(index); } return this; } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Extension.Builder getExtensionsBuilder(int index) { return getExtensionsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder getExtensionsOrBuilder( int index) { if (extensionsBuilder_ == null) { return extensions_.get(index); } else { return extensionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder> getExtensionsOrBuilderList() { if (extensionsBuilder_ != null) { return extensionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(extensions_); } } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Extension.Builder addExtensionsBuilder() { return getExtensionsFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1beta1.Extension.getDefaultInstance()); } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Extension.Builder addExtensionsBuilder(int index) { return getExtensionsFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1beta1.Extension.getDefaultInstance()); } /** * * * <pre> * List of Extension in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Extension extensions = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.Extension.Builder> getExtensionsBuilderList() { return getExtensionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Extension, com.google.cloud.aiplatform.v1beta1.Extension.Builder, com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder> getExtensionsFieldBuilder() { if (extensionsBuilder_ == null) { extensionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Extension, com.google.cloud.aiplatform.v1beta1.Extension.Builder, com.google.cloud.aiplatform.v1beta1.ExtensionOrBuilder>( extensions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); extensions_ = null; } return extensionsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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 * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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 * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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 * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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 * [ListExtensionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExtensionsRequest.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.ListExtensionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListExtensionsResponse) private static final com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse(); } public static com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListExtensionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListExtensionsResponse>() { @java.lang.Override public ListExtensionsResponse 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<ListExtensionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListExtensionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListExtensionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/jackrabbit-oak
38,435
oak-benchmarks/src/main/java/org/apache/jackrabbit/oak/benchmark/BenchmarkRunner.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.benchmark; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Counting; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import org.apache.jackrabbit.guava.common.util.concurrent.MoreExecutors; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.oak.benchmark.authentication.external.AutoMembershipTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.ExternalLoginTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.ListIdentitiesTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.CachedMembershipLoginTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.PrincipalNameResolutionTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.SyncAllExternalUsersTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.SyncAllUsersTest; import org.apache.jackrabbit.oak.benchmark.authentication.external.SyncExternalUsersTest; import org.apache.jackrabbit.oak.benchmark.authorization.AceCreationTest; import org.apache.jackrabbit.oak.benchmark.authorization.CanReadNonExisting; import org.apache.jackrabbit.oak.benchmark.authorization.GetPrivilegeCollectionIncludeNamesTest; import org.apache.jackrabbit.oak.benchmark.authorization.MvGlobsAndSubtreesTest; import org.apache.jackrabbit.oak.benchmark.authorization.SaveHasItemGetItemTest; import org.apache.jackrabbit.oak.benchmark.authorization.HasPermissionHasItemGetItemTest; import org.apache.jackrabbit.oak.benchmark.authorization.HasPrivilegesHasItemGetItemTest; import org.apache.jackrabbit.oak.benchmark.authorization.RefreshHasItemGetItemTest; import org.apache.jackrabbit.oak.benchmark.authorization.RefreshHasPrivPermHasItemGetItemTest; import org.apache.jackrabbit.oak.benchmark.authorization.permission.EagerCacheSizeTest; import org.apache.jackrabbit.oak.benchmark.authorization.principalbased.HasItemGetItemIsModifiedTest; import org.apache.jackrabbit.oak.benchmark.authorization.principalbased.PermissionEvaluationTest; import org.apache.jackrabbit.oak.benchmark.authorization.principalbased.PrinicipalBasedReadTest; import org.apache.jackrabbit.oak.benchmark.wikipedia.WikipediaImport; import org.apache.jackrabbit.oak.fixture.JackrabbitRepositoryFixture; import org.apache.jackrabbit.oak.fixture.OakFixture; import org.apache.jackrabbit.oak.fixture.OakRepositoryFixture; import org.apache.jackrabbit.oak.fixture.RepositoryFixture; import org.apache.jackrabbit.oak.plugins.metric.MetricStatisticsProvider; import org.apache.jackrabbit.oak.stats.StatisticsProvider; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; public class BenchmarkRunner { private static final int MB = 1024 * 1024; protected static List<Benchmark> allBenchmarks = new ArrayList<>(); protected static StatisticsProvider statsProvider = null; private static OptionParser parser = new OptionParser(); protected static BenchmarkOptions benchmarkOptions = null; protected static OptionSet options; private static boolean initFlag = false; public static void main(String[] args) throws Exception { initOptionSet(args); if (options.has(benchmarkOptions.getHelp())) { parser.printHelpOn(System.out); System.exit(0); } String uri = benchmarkOptions.getMongouri().value(options); if (uri == null) { String db = benchmarkOptions.getDbName().value(options); if (db == null) { db = OakFixture.getUniqueDatabaseName(OakFixture.OAK_MONGO); } uri = "mongodb://" + benchmarkOptions.getHost().value(options) + ":" + benchmarkOptions.getPort().value(options) + "/" + db; } statsProvider = options.has(benchmarkOptions.getMetrics()) ? getStatsProvider() : StatisticsProvider.NOOP; int cacheSize = benchmarkOptions.getCache().value(options); RepositoryFixture[] allFixtures = new RepositoryFixture[]{ new JackrabbitRepositoryFixture(benchmarkOptions.getBase().value(options), cacheSize), OakRepositoryFixture.getMemoryNS(cacheSize * MB), OakRepositoryFixture.getMongo(uri, benchmarkOptions.getDropDBAfterTest().value(options), cacheSize * MB, benchmarkOptions.isThrottlingEnabled().value(options)), OakRepositoryFixture.getMongoWithDS(uri, benchmarkOptions.getDropDBAfterTest().value(options), cacheSize * MB, benchmarkOptions.getBase().value(options), benchmarkOptions.getFdsCache().value(options), benchmarkOptions.isThrottlingEnabled().value(options)), OakRepositoryFixture.getMongoNS(uri, benchmarkOptions.getDropDBAfterTest().value(options), cacheSize * MB, benchmarkOptions.isThrottlingEnabled().value(options)), OakRepositoryFixture.getSegmentTar(benchmarkOptions.getBase().value(options), 256, cacheSize, benchmarkOptions.getMmap().value(options), benchmarkOptions.getBinariesInlineThreshold().value(options)), OakRepositoryFixture.getSegmentTarWithDataStore(benchmarkOptions.getBase().value(options), 256, cacheSize, benchmarkOptions.getMmap().value(options), benchmarkOptions.getBinariesInlineThreshold().value(options), benchmarkOptions.getFdsCache().value(options)), OakRepositoryFixture.getSegmentTarWithColdStandby(benchmarkOptions.getBase().value(options), 256, cacheSize, benchmarkOptions.getMmap().value(options), benchmarkOptions.getBinariesInlineThreshold().value(options), benchmarkOptions.getColdUseDataStore().value(options), benchmarkOptions.getFdsCache().value(options), benchmarkOptions.getColdSyncInterval().value(options), benchmarkOptions.getColdShareDataStore().value(options), benchmarkOptions.getColdSecure().value(options), benchmarkOptions.getColdOneShotRun().value(options)), OakRepositoryFixture.getSegmentTarWithAzureSegmentStore(benchmarkOptions.getBase().value(options), benchmarkOptions.getAzureConnectionString().value(options), benchmarkOptions.getAzureContainerName().value(options), benchmarkOptions.getAzureRootPath().value(options), 256, cacheSize, benchmarkOptions.getBinariesInlineThreshold().value(options), true, benchmarkOptions.getFdsCache().value(options)), OakRepositoryFixture.getRDB(benchmarkOptions.getRdbjdbcuri().value(options), benchmarkOptions.getRdbjdbcuser().value(options), benchmarkOptions.getRdbjdbcpasswd().value(options), benchmarkOptions.getRdbjdbctableprefix().value(options), benchmarkOptions.getDropDBAfterTest().value(options), cacheSize * MB, benchmarkOptions.getVgcMaxAge().value(options)), OakRepositoryFixture.getRDBWithDS(benchmarkOptions.getRdbjdbcuri().value(options), benchmarkOptions.getRdbjdbcuser().value(options), benchmarkOptions.getRdbjdbcpasswd().value(options), benchmarkOptions.getRdbjdbctableprefix().value(options), benchmarkOptions.getDropDBAfterTest().value(options), cacheSize * MB, benchmarkOptions.getBase().value(options), benchmarkOptions.getFdsCache().value(options), benchmarkOptions.getVgcMaxAge().value(options)), OakRepositoryFixture.getCompositeStore(benchmarkOptions.getBase().value(options), 256, cacheSize, benchmarkOptions.getMmap().value(options), benchmarkOptions.getBinariesInlineThreshold().value(options)), OakRepositoryFixture.getCompositeMemoryStore(), OakRepositoryFixture.getCompositeMongoStore(uri, cacheSize * MB, benchmarkOptions.getDropDBAfterTest().value(options), benchmarkOptions.isThrottlingEnabled().value(options)) }; addToBenchMarkList(Arrays.asList( new OrderedIndexQueryOrderedIndexTest(), new OrderedIndexQueryStandardIndexTest(), new OrderedIndexQueryNoIndexTest(), new OrderedIndexInsertOrderedPropertyTest(), new OrderedIndexInsertStandardPropertyTest(), new OrderedIndexInsertNoIndexTest(), new LoginTest( benchmarkOptions.getRunAsUser().value(options), benchmarkOptions.getRunWithToken().value(options), benchmarkOptions.getNoIterations().value(options)), new LoginLogoutTest( benchmarkOptions.getRunAsUser().value(options), benchmarkOptions.getRunWithToken().value(options), benchmarkOptions.getNoIterations().value(options)), new LoginGetRootLogoutTest( benchmarkOptions.getRunAsUser().value(options), benchmarkOptions.getRunWithToken().value(options), benchmarkOptions.getNoIterations().value(options)), new LoginWithTokensTest(benchmarkOptions.getNumberOfUsers().value(options)), new LoginSystemTest(), new LoginImpersonateTest(), new LoginWithMembershipTest( benchmarkOptions.getRunWithToken().value(options), benchmarkOptions.getNoIterations().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNestedGroups().value(options), benchmarkOptions.getExpiration().value(options)), new LoginWithMembersTest( benchmarkOptions.getRunWithToken().value(options), benchmarkOptions.getNoIterations().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options)), new NamespaceTest(), new NamespaceRegistryTest(), new ReadPropertyTest(), GetNodeTest.withAdmin(), GetNodeTest.withAnonymous(), GetParentNodeTest.withNodeAPIAndParentVisible(benchmarkOptions.getRunAsAdmin().value(options)), GetParentNodeTest.withSessionAPIAndParentVisible(benchmarkOptions.getRunAsAdmin().value(options)), GetParentNodeTest.withNodeAPIAndParentNotVisible(benchmarkOptions.getRunAsAdmin().value(options)), GetParentNodeTest.withSessionAPIAndParentNotVisible(benchmarkOptions.getRunAsAdmin().value(options)), new GetMixinNodeTypesTest(), new GetDeepNodeTest(), new SetPropertyTest(), new SetMultiPropertyTest(), new SmallFileReadTest(), new SmallFileWriteTest(), new ConcurrentReadTest(), new ConcurrentReadWriteTest(), new ConcurrentWriteReadTest(), new ConcurrentWriteTest(), new SimpleSearchTest(), new UUIDLookupTest(), new SQL2SearchTest(), new DescendantSearchTest(), new SQL2DescendantSearchTest(), new FlatTreeUpdateTest(), new CreateManyChildNodesTest(), new CompareManyChildNodesTest(), new CreateManyNodesTest(), new UpdateManyChildNodesTest(), new TransientManyChildNodesTest(), new WikipediaImport( benchmarkOptions.getWikipedia().value(options), benchmarkOptions.getFlatStructure().value(options), benchmarkOptions.getReport().value(options)), new CreateNodesBenchmark(), new ManyNodes(options.has(benchmarkOptions.getVerbose())), new ObservationTest(), new RevisionGCTest(), new ContinuousRevisionGCTest(), new XmlImportTest(), new FlatTreeWithAceForSamePrincipalTest(), new ReadDeepTreeTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new CompositeAuthorizationTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options)), // NOTE: this is currently the no of configurations new CugTest(benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getRandomUser().value(options), benchmarkOptions.getSupportedPaths().values(options), benchmarkOptions.getReverseOrder().value(options)), new CugOakTest(benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getRandomUser().value(options), benchmarkOptions.getSupportedPaths().values(options), benchmarkOptions.getReverseOrder().value(options)), new PrinicipalBasedReadTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getEntriesForEachPrincipal().value(options), benchmarkOptions.getReverseOrder().value(options), benchmarkOptions.getCompositionType().value(options), benchmarkOptions.getUseAggregationFilter().value(options), benchmarkOptions.getReport().value(options)), new PermissionEvaluationTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getEntriesForEachPrincipal().value(options), benchmarkOptions.getReverseOrder().value(options), benchmarkOptions.getCompositionType().value(options), benchmarkOptions.getUseAggregationFilter().value(options), benchmarkOptions.getReport().value(options)), new HasItemGetItemIsModifiedTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getEntriesForEachPrincipal().value(options), benchmarkOptions.getReverseOrder().value(options), benchmarkOptions.getCompositionType().value(options), benchmarkOptions.getUseAggregationFilter().value(options), benchmarkOptions.getReport().value(options)), new EagerCacheSizeTest(benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getRepeatedRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfUsers().value(options), cacheSize, benchmarkOptions.getReport().value(options)), new HasPrivilegesHasItemGetItemTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options)), new HasPermissionHasItemGetItemTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options)), new RefreshHasItemGetItemTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options)), new RefreshHasPrivPermHasItemGetItemTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options)), new SaveHasItemGetItemTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options)), new GetPrivilegeCollectionIncludeNamesTest(benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options), benchmarkOptions.getEvalutionType().value(options)), new MvGlobsAndSubtreesTest(benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getReport().value(options), benchmarkOptions.getEvalutionType().value(options)), new IsCheckedOutAddMixinSetPropertyTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentReadDeepTreeTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentReadSinglePolicyTreeTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentReadAccessControlledTreeTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentReadAccessControlledTreeTest2( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentReadRandomNodeAndItsPropertiesTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentHasPermissionTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ConcurrentHasPermissionTest2( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options)), new ManyUserReadTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options), benchmarkOptions.getRandomUser().value(options)), new ReadWithMembershipTest( benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNumberOfInitialAce().value(options)), new ConcurrentTraversalTest( benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options), benchmarkOptions.getReport().value(options), benchmarkOptions.getRandomUser().value(options)), new ConcurrentWriteACLTest(benchmarkOptions.getItemsToRead().value(options)), new ConcurrentEveryoneACLTest(benchmarkOptions.getRunAsAdmin().value(options), benchmarkOptions.getItemsToRead().value(options)), new AceCreationTest(benchmarkOptions.getBatchSize().value(options), benchmarkOptions.getNumberOfInitialAce().value(options), benchmarkOptions.getTransientWrites().value(options)), ReadManyTest.linear("LinearReadEmpty", 1, ReadManyTest.EMPTY), ReadManyTest.linear("LinearReadFiles", 1, ReadManyTest.FILES), ReadManyTest.linear("LinearReadNodes", 1, ReadManyTest.NODES), ReadManyTest.uniform("UniformReadEmpty", 1, ReadManyTest.EMPTY), ReadManyTest.uniform("UniformReadFiles", 1, ReadManyTest.FILES), ReadManyTest.uniform("UniformReadNodes", 1, ReadManyTest.NODES), new ConcurrentCreateNodesTest(), new SequentialCreateNodesTest(), new CreateManyIndexedNodesTest(), new GetPoliciesTest(), new ConcurrentFileWriteTest(), new GetAuthorizableByIdTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getFlatStructure().value(options)), new GetAuthorizableByPrincipalTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getFlatStructure().value(options)), new GetPrincipalTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getFlatStructure().value(options)), new GetGroupPrincipalsTest( benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNestedGroups().value(options)), // benchmarks adding multiple or single members new AddMembersTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getBatchSize().value(options), benchmarkOptions.getImportBehavior().value(options)), new AddMemberTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getBatchSize().value(options)), new AddUniqueMembersTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getBatchSize().value(options)), // benchmarks removing multiple or single members new RemoveMembersTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getBatchSize().value(options)), new RemoveMemberTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getBatchSize().value(options)), // benchmark testing isMember/isDeclared member; each user only being member of 1 group new IsMemberTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNestedGroups().value(options)), new IsDeclaredMemberTest( benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNestedGroups().value(options)), // 4 benchmarks with the same setup test various membership operations. new MemberDeclaredMemberOf( benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNestedGroups().value(options), benchmarkOptions.getNumberOfUsers().value(options)), new MemberMemberOf( benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNestedGroups().value(options), benchmarkOptions.getNumberOfUsers().value(options)), new MemberIsDeclaredMember( benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNestedGroups().value(options), benchmarkOptions.getNumberOfUsers().value(options)), new MemberIsMember( benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getNestedGroups().value(options), benchmarkOptions.getNumberOfUsers().value(options)), new FindAuthorizableWithScopeTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getQueryMaxCount().value(options), benchmarkOptions.getSetScope().value(options), benchmarkOptions.getDeclaredMembership().value(options), benchmarkOptions.getRunAsAdmin().value(options)), new ReplicaCrashResilienceTest(), // benchmarks for oak-auth-external new ExternalLoginTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options), benchmarkOptions.getDynamicMembership().value(options), benchmarkOptions.getAutoMembership().values(options), benchmarkOptions.getReport().value(options), statsProvider, benchmarkOptions.getCacheExpiration().value(options)), new CachedMembershipLoginTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options), benchmarkOptions.getDynamicMembership().value(options), benchmarkOptions.getAutoMembership().values(options), benchmarkOptions.getReport().value(options), statsProvider, benchmarkOptions.getCacheExpiration().value(options), benchmarkOptions.getNumberOfLocalGroups().value(options)), new SyncAllExternalUsersTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options), benchmarkOptions.getDynamicMembership().value(options), benchmarkOptions.getAutoMembership().values(options)), new SyncAllUsersTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options), benchmarkOptions.getDynamicMembership().value(options), benchmarkOptions.getAutoMembership().values(options)), new SyncExternalUsersTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options), benchmarkOptions.getDynamicMembership().value(options), benchmarkOptions.getAutoMembership().values(options), benchmarkOptions.getBatchSize().value(options)), new PrincipalNameResolutionTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getExpiration().value(options), benchmarkOptions.getRoundtripDelay().value(options)), new ListIdentitiesTest(benchmarkOptions.getNumberOfUsers().value(options)), new AutoMembershipTest(benchmarkOptions.getNumberOfUsers().value(options), benchmarkOptions.getNumberOfGroups().value(options), benchmarkOptions.getDynamicMembership().value(options), benchmarkOptions.getAutoMembership().values(options)), new BundlingNodeTest(), new PersistentCacheTest(statsProvider), new StringWriteTest(), new BasicWriteTest(), new CanReadNonExisting(), new IsNodeTypeTest(benchmarkOptions.getRunAsAdmin().value(options)), new SetPropertyTransientTest(), new GetURITest(), new ISO8601FormatterTest(), new ReadBinaryPropertiesTest(), new AccessAfterMoveTest() ) ); Set<String> argset = new HashSet<>(benchmarkOptions.getNonOption().values(options)); List<RepositoryFixture> fixtures = new ArrayList<>(); for (RepositoryFixture fixture : allFixtures) { if (argset.remove(fixture.toString())) { fixtures.add(fixture); configure(fixture, statsProvider); } } if (fixtures.isEmpty()) { System.err.println("Warning: no repository fixtures specified, supported fixtures are: " + asSortedString(Arrays.asList(allFixtures))); } List<Benchmark> benchmarks = new ArrayList<>(); for (Benchmark benchmark : allBenchmarks) { if (argset.remove(benchmark.toString())) { benchmarks.add(benchmark); } } if (benchmarks.isEmpty()) { System.err.println("Warning: no benchmarks specified, supported benchmarks are: " + asSortedString(Arrays.asList(allBenchmarks))); } if (argset.isEmpty()) { PrintStream out = null; if (options.has(benchmarkOptions.getCsvFile())) { out = new PrintStream(FileUtils.openOutputStream(benchmarkOptions.getCsvFile().value(options), true)); } for (Benchmark benchmark : benchmarks) { if (benchmark instanceof CSVResultGenerator) { ((CSVResultGenerator) benchmark).setPrintStream(out); } benchmark.run(fixtures, options.valuesOf(benchmarkOptions.getConcurrency())); } if (out != null) { out.close(); } reportMetrics(statsProvider); } else { System.err.println("Unknown arguments: " + argset); } } private static void reportMetrics(StatisticsProvider statsProvider) { if (statsProvider instanceof MetricStatisticsProvider) { MetricRegistry metricRegistry = ((MetricStatisticsProvider) statsProvider).getRegistry(); ConsoleReporter.forRegistry(metricRegistry) .outputTo(System.out) .filter(new MetricFilter() { @Override public boolean matches(String name, Metric metric) { if (metric instanceof Counting) { //Only report non zero metrics return ((Counting) metric).getCount() > 0; } return true; } }) .build() .report(); } } protected static void initOptionSet(String[] args) throws IOException { if (!initFlag) { benchmarkOptions = new BenchmarkOptions(parser); options = parser.parse(args); initFlag = true; } } protected static void addToBenchMarkList(List<Benchmark> benchmarks) { allBenchmarks.addAll(benchmarks); } private static void configure(RepositoryFixture fixture, StatisticsProvider statsProvider) { if (fixture instanceof OakRepositoryFixture) { ((OakRepositoryFixture) fixture).setStatisticsProvider(statsProvider); } } private static String asSortedString(List<?> in) { List<String> tmp = new ArrayList<String>(); for (Object o : in) { tmp.add(o.toString()); } Collections.sort(tmp); return tmp.toString(); } protected static StatisticsProvider getStatsProvider() { if (statsProvider == null) { ScheduledExecutorService executorService = MoreExecutors.getExitingScheduledExecutorService( (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1)); return new MetricStatisticsProvider(null, executorService); } else { return statsProvider; } } }
googleapis/google-cloud-java
37,788
java-secretmanager/proto-google-cloud-secretmanager-v1/src/main/java/com/google/cloud/secretmanager/v1/ListSecretsRequest.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/secretmanager/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.secretmanager.v1; /** * * * <pre> * Request message for * [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. * </pre> * * Protobuf type {@code google.cloud.secretmanager.v1.ListSecretsRequest} */ public final class ListSecretsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.secretmanager.v1.ListSecretsRequest) ListSecretsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListSecretsRequest.newBuilder() to construct. private ListSecretsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSecretsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSecretsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.secretmanager.v1.ServiceProto .internal_static_google_cloud_secretmanager_v1_ListSecretsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.secretmanager.v1.ServiceProto .internal_static_google_cloud_secretmanager_v1_ListSecretsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.secretmanager.v1.ListSecretsRequest.class, com.google.cloud.secretmanager.v1.ListSecretsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. The maximum number of results to be returned in a single page. If * set to 0, the server decides the number of results to return. If the * number is greater than 25000, it is capped at 25000. * </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. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </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. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.secretmanager.v1.ListSecretsRequest)) { return super.equals(obj); } com.google.cloud.secretmanager.v1.ListSecretsRequest other = (com.google.cloud.secretmanager.v1.ListSecretsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.secretmanager.v1.ListSecretsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest 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.secretmanager.v1.ListSecretsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest 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.secretmanager.v1.ListSecretsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest 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.secretmanager.v1.ListSecretsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest 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.secretmanager.v1.ListSecretsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest 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.secretmanager.v1.ListSecretsRequest 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 * [SecretManagerService.ListSecrets][google.cloud.secretmanager.v1.SecretManagerService.ListSecrets]. * </pre> * * Protobuf type {@code google.cloud.secretmanager.v1.ListSecretsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.secretmanager.v1.ListSecretsRequest) com.google.cloud.secretmanager.v1.ListSecretsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.secretmanager.v1.ServiceProto .internal_static_google_cloud_secretmanager_v1_ListSecretsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.secretmanager.v1.ServiceProto .internal_static_google_cloud_secretmanager_v1_ListSecretsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.secretmanager.v1.ListSecretsRequest.class, com.google.cloud.secretmanager.v1.ListSecretsRequest.Builder.class); } // Construct using com.google.cloud.secretmanager.v1.ListSecretsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.secretmanager.v1.ServiceProto .internal_static_google_cloud_secretmanager_v1_ListSecretsRequest_descriptor; } @java.lang.Override public com.google.cloud.secretmanager.v1.ListSecretsRequest getDefaultInstanceForType() { return com.google.cloud.secretmanager.v1.ListSecretsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.secretmanager.v1.ListSecretsRequest build() { com.google.cloud.secretmanager.v1.ListSecretsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.secretmanager.v1.ListSecretsRequest buildPartial() { com.google.cloud.secretmanager.v1.ListSecretsRequest result = new com.google.cloud.secretmanager.v1.ListSecretsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.secretmanager.v1.ListSecretsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.secretmanager.v1.ListSecretsRequest) { return mergeFrom((com.google.cloud.secretmanager.v1.ListSecretsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.secretmanager.v1.ListSecretsRequest other) { if (other == com.google.cloud.secretmanager.v1.ListSecretsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project associated with the * [Secrets][google.cloud.secretmanager.v1.Secret], in the format `projects/&#42;` * or `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. The maximum number of results to be returned in a single page. If * set to 0, the server decides the number of results to return. If the * number is greater than 25000, it is capped at 25000. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. The maximum number of results to be returned in a single page. If * set to 0, the server decides the number of results to return. If the * number is greater than 25000, it is capped at 25000. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The maximum number of results to be returned in a single page. If * set to 0, the server decides the number of results to return. If the * number is greater than 25000, it is capped at 25000. * </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. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. Pagination token, returned earlier via * [ListSecretsResponse.next_page_token][google.cloud.secretmanager.v1.ListSecretsResponse.next_page_token]. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </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. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </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. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </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. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </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. Filter string, adhering to the rules in * [List-operation * filtering](https://cloud.google.com/secret-manager/docs/filtering). List * only secrets matching the filter. If filter is empty, all secrets are * listed. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.secretmanager.v1.ListSecretsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.secretmanager.v1.ListSecretsRequest) private static final com.google.cloud.secretmanager.v1.ListSecretsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.secretmanager.v1.ListSecretsRequest(); } public static com.google.cloud.secretmanager.v1.ListSecretsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSecretsRequest> PARSER = new com.google.protobuf.AbstractParser<ListSecretsRequest>() { @java.lang.Override public ListSecretsRequest 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<ListSecretsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSecretsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.secretmanager.v1.ListSecretsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/gdata-java-client
37,949
java/src/com/google/gdata/util/common/logging/FormattingLogger.java
/* Copyright (c) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gdata.util.common.logging; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * A wrapped logger chock-full of convenience methods. * * The introduction of varargs in Java 5 has provided two ways to further * simplify logging information.<p/> * * First, the level-based convenience methods such as * {@code Logger.foo(String msg)} can contain an additional * {@code Object... args} parameter that formats your message according to the * logger's {@link java.util.logging.Formatter}.<p/> * * Second, for those times when you don't want the * {@link java.util.logging.Formatter} to manage formatting your message, you * can use the {@code FormattingLogger.xxxfmt(String fmt, Object... params)} * methods. These methods leverage the Java 5 * {@link String#format(String format, Object... args)} method. However, * {@code logger.infofmt("%s %s", foo, bar)} is slightly more efficient than * {@code logger.info(String.format("%s %s", foo, bar))} since the text is * only formatted when the message is sufficiently important. It's also a little * more readable.<p/> * * Keep in mind that this class mixes two ways to format text: one that expects * text to be formatted by the logger's {@link java.util.logging.Formatter} * and one that depends upon the new * {@link java.lang.String#format(java.lang.String, java.lang.Object[])} style. * If, in this class, method name ends with {@code fmt}, it's formatting using * the latter. If the class method does not end with {@code fmt}, it's using * the traditional formatting style. * * NOTE(future extenders): any time a new {@link #logfmt} variant is added * to this class a matching {@link #logpfmt} variant must also be added, and * vice versa. This enables {@code * com.google.monitoring.runtime.instrumentation.LogFasterer} to do its job. * * by calls to the private method doLog, which sets the resource bundle. * FormattingLogger does not support that yet; this functionality may change. * * */ public final class FormattingLogger { // For use with LogRecord.inferCaller private static final String LOGGER_CLASS_NAME = FormattingLogger.class.getName(); /** * An extension of {@link LogRecord} used to support a custom version of * its private {@code inferCaller(String)} method. * * */ public static class Record extends LogRecord { private static final long serialVersionUID = 1L; private boolean needToInferCaller; private String sourceMethodName; private String sourceClassName; /** * Arguments passed to *fmt variants that we want to keep track of for * users of this object. */ private final Object[] formatterArgs; private final String formatterFormat; @Override public String getSourceMethodName() { if (needToInferCaller) { inferCaller(LOGGER_CLASS_NAME); } return sourceMethodName; } @Override public String getSourceClassName() { if (needToInferCaller) { inferCaller(LOGGER_CLASS_NAME); } return sourceClassName; } public Object[] getFormatterArgs() { return formatterArgs; } public String getFormatterFormat() { return formatterFormat; } @Override public void setSourceClassName(String sourceClassName) { this.sourceClassName = sourceClassName; super.setSourceClassName(sourceClassName); } @Override public void setSourceMethodName(String sourceMethodName) { this.sourceMethodName = sourceMethodName; super.setSourceMethodName(sourceMethodName); } /** * @param level * @param msg */ Record(Level level, String msg) { super(level, msg); needToInferCaller = true; formatterFormat = null; formatterArgs = null; } /** * Constructs a Record object given a {@link java.util.Formatter} format * string and arguments * */ Record(Level level, String fmt, Object[] args) { super(level, String.format(fmt, args)); needToInferCaller = true; formatterFormat = fmt; formatterArgs = args; } /** * Constructs a Record object when the class + method context are known. * @param level the severity of the log statement * @param msg the content of the log statement * @param sourceClassName the class generating the log statement * @param sourceMethodName the method generating the log statement */ Record(Level level, String msg, String sourceClassName, String sourceMethodName) { super(level, msg); setSourceClassName(sourceClassName); setSourceMethodName(sourceMethodName); formatterFormat = null; formatterArgs = null; } /** * Constructs a Record object when the class + method context are known and * {@link java.util.Formatter} messages are used. */ Record(Level level, String fmt, Object[] args, String sourceClassName, String sourceMethodName) { super(level, String.format(fmt, args)); setSourceClassName(sourceClassName); setSourceMethodName(sourceMethodName); formatterFormat = fmt; formatterArgs = args; } /** * Like LogRecord.inferCaller, we're making a 'best effort'. */ protected void inferCaller(String loggerClassName) { needToInferCaller = false; // true when searching for loggerClassName, false when not. boolean isSearchingForLogger = true; for (StackTraceElement elem : new Throwable().getStackTrace()) { String className = elem.getClassName(); boolean matches = className.equals(loggerClassName); // Found FormattingLogger in the stack. if (matches && isSearchingForLogger) { isSearchingForLogger = false; continue; } // Found first call past FormattingLogger. if (!matches && !isSearchingForLogger) { setSourceClassName(className); setSourceMethodName(elem.getMethodName()); return; } } } } private final Logger logger; /** * Returns an instance of {@code FormattingLogger}. */ public static FormattingLogger getLogger(String name) { return new FormattingLogger(Logger.getLogger(name)); } /** * Returns an instance of {@code FormattingLogger} using the * {@link Class#getCanonicalName()} as a source for the underlying logger's * name. */ public static FormattingLogger getLogger(Class<?> cls) { return getLogger(cls.getCanonicalName()); } /** * Creates a new FormattingLogger. * * This is convenience ctor that creates a named backing {@code Logger} with * the name of the passed-in class. * * @param cls The class whose name will be used to name the backing logger. */ public FormattingLogger(Class<?> cls) { this(Logger.getLogger(cls.getCanonicalName())); } /** * Creates a new FormattingLogger. * * This is a convenience ctor that creates an anonymous backing * {@code Logger}. */ public FormattingLogger() { this(Logger.getAnonymousLogger()); } /** * Creates a new FormattingLogger by wrapping a {@code Logger}. * * @param logger The {@code Logger} to wrap. */ public FormattingLogger(Logger logger) { if (logger == null) { throw new NullPointerException("logger is null"); } this.logger = logger; } /** * Gets the {@code Logger} wrapped by this FormattingLogger. * @return the {@code Logger} wrapped by this FormattingLogger. */ public Logger getFormattingLogger() { return logger; } /** * Similar to {@link Logger#log(Level, String, Object[])}, allows you to delay * formatting with {@link java.text.MessageFormat}. */ public void log(Level level, String msg, Object... params) { if (!isLoggable(level)) { return; } Record record = new Record(level, msg); record.setParameters(params); nameAndLog(record); } /** * Similar to {@link Logger#log(Level, String, Throwable)}, sets the value * of {@link LogRecord#getThrown()}. */ public void log(Level level, String msg, Throwable thrown) { if (!isLoggable(level)) { return; } Record record = new Record(level, msg); record.setThrown(thrown); nameAndLog(record); } /** * Similar to {@link Logger#log(Level, String, Throwable)}, but takes * variable arguments and allows you to delay formatting with * {@link java.text.MessageFormat}. * Calls {@link LogRecord#setThrown(Throwable)} if thrown is non-null. */ public void log(Level level, Throwable thrown, String msg, Object... params) { if (!isLoggable(level)) { return; } Record record = new Record(level, msg); if (thrown != null) { record.setThrown(thrown); } if (params != null && params.length != 0) { record.setParameters(params); } nameAndLog(record); } private void nameAndLog(Record record) { record.setLoggerName(logger.getName()); log(record); } /** * Log a {@link java.util.logging.LogRecord}. The log message, level and * other parameters are contained in the {@code LogRecord}, but the source * class and method will be set if necessary. */ public void log(LogRecord lr) { if (!(lr instanceof Record)) { // set the source class and method name by creating a bogus // record, and getting the class and method names from it. // This may look like a hack, but it's pretty much no worse than anything // else, we'll need to create a new Object, no matter what. Hey, we need // the stack trace, so this is peanuts compared to that. Record rec = new Record(Level.INFO, null); lr.setSourceClassName(rec.getSourceClassName()); lr.setSourceMethodName(rec.getSourceMethodName()); } logger.log(lr); } /** * Logs an event with a known context, similar to * {@link java.util.logging.Logger#logp(java.util.logging.Level, String, String, String)}. * However, this delays formatting of the message. * @param level one of the message level identifiers, e.g. SEVERE * @param sourceClassName the class generating this log event * @param sourceMethodName the method generating this log event * @param msg the basic message string * @param params the parameters for the message string */ public void logp(Level level, String sourceClassName, String sourceMethodName, String msg, Object... params) { if (!isLoggable(level)) { return; } Record record = new Record(level, msg, sourceClassName, sourceMethodName); if (params != null && params.length != 0) { record.setParameters(params); } nameAndLog(record); } /** * Logs an event with a known context, similar to * {@link java.util.logging.Logger#logp(java.util.logging.Level, String, * String, String, Throwable)}. * However, this delays formatting of the message. * @param level one of the message level identifiers, e.g. SEVERE * @param sourceClassName the class generating this log event * @param sourceMethodName the method generating this log event * @param msg the message string * @param thrown the throwable which triggered this log event */ public void logp(Level level, String sourceClassName, String sourceMethodName, String msg, Throwable thrown) { if (!isLoggable(level)) { return; } Record record = new Record(level, msg, sourceClassName, sourceMethodName); record.setThrown(thrown); nameAndLog(record); } /** * Logs an event with a known context, similar to * {@link java.util.logging.Logger#logp(java.util.logging.Level, String, * String, String, Throwable)}. * However, this delays formatting of the message. * @param level one of the message level identifiers, e.g. SEVERE * @param sourceClassName the class generating this log event * @param sourceMethodName the method generating this log event * @param thrown the throwable which triggered this log event * @param msg the basic message string * @param params the parameters for the message string */ public void logp(Level level, String sourceClassName, String sourceMethodName, Throwable thrown, String msg, Object... params) { if (!isLoggable(level)) { return; } Record record = new Record(level, msg, sourceClassName, sourceMethodName); if (thrown != null) { record.setThrown(thrown); } if (params != null && params.length != 0) { record.setParameters(params); } nameAndLog(record); } /** Pass-through to {@link Logger#isLoggable(Level)} */ public boolean isLoggable(Level level) { return logger.isLoggable(level); } /** Pass-through to {@link Logger#getLevel()} */ public Level getLevel() { return logger.getLevel(); } /** Pass-through to {@link Logger#setLevel(Level)} */ public void setLevel(Level level) { logger.setLevel(level); } /** * Log a message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g. SEVERE * @param fmt The string message (or a key in the message catalog) * @param args array of parameters to the message */ public void logfmt(Level level, String fmt, Object... args) { if (logger.isLoggable(level)) { Record record = new Record(level, fmt, args); nameAndLog(record); } } /** * Log a message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param level One of the message level identifiers, e.g. SEVERE * @param fmt The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the format message */ public void logfmt(Level level, String fmt, Throwable thrown) { if (logger.isLoggable(level)) { Record record = new Record(level, fmt, new Object[]{thrown}); record.setThrown(thrown); nameAndLog(record); } } /** * Log a message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param level one of the message level identifiers, e.g. SEVERE * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void logfmt(Level level, Throwable thrown, String fmt, Object... args) { if (logger.isLoggable(level)) { Record record = new Record(level, fmt, args); record.setThrown(thrown); nameAndLog(record); } } /** * Logs an event with a known context, using explicit formatting rules. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * @param level one of the message level identifiers, e.g. SEVERE * @param sourceClassName the class generating this log event * @param sourceMethodName the method generating this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the format message */ public void logpfmt(Level level, String sourceClassName, String sourceMethodName, String fmt, Object... args) { if (!isLoggable(level)) { return; } Record record = new Record(level, fmt, args, sourceClassName, sourceMethodName); nameAndLog(record); } /** * Logs an event with a known context, using explicit formatting rules. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * @param level one of the message level identifiers, e.g. SEVERE * @param sourceClassName the class generating this log event * @param sourceMethodName the method generating this log event * @param fmt the string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the format message */ public void logpfmt(Level level, String sourceClassName, String sourceMethodName, String fmt, Throwable thrown) { if (!isLoggable(level)) { return; } Record record = new Record( level, fmt, new Object[]{thrown}, sourceClassName, sourceMethodName); record.setThrown(thrown); nameAndLog(record); } /** * Logs an event with a known context, using explicit formatting rules. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param level one of the message level identifiers, e.g. SEVERE * @param sourceClassName the class generating this log event * @param sourceMethodName the method generating this log event * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void logpfmt(Level level, String sourceClassName, String sourceMethodName, Throwable thrown, String fmt, Object... args) { if (logger.isLoggable(level)) { logp(level, sourceClassName, sourceMethodName, thrown, String.format(fmt, args), (Object[]) null); } } /** * Log a SEVERE message. * <p> * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void severe(String msg, Throwable thrown) { log(Level.SEVERE, thrown, msg, thrown); } /** * Log a WARNING message. * <p> * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void warning(String msg, Throwable thrown) { log(Level.WARNING, thrown, msg, thrown); } /** * Log an INFO message. * <p> * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void info(String msg, Throwable thrown) { log(Level.INFO, thrown, msg, thrown); } /** * Log a CONFIG message. * <p> * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void config(String msg, Throwable thrown) { log(Level.CONFIG, thrown, msg, thrown); } /** * Log a FINE message. * <p> * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void fine(String msg, Throwable thrown) { log(Level.FINE, thrown, msg, thrown); } /** * Log a FINER message. * <p> * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void finer(String msg, Throwable thrown) { log(Level.FINER, thrown, msg, thrown); } /** * Log a FINEST message. * <p> * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param thrown the throwable which triggered this log event, * and parameter to the message */ public void finest(String msg, Throwable thrown) { log(Level.FINEST, thrown, msg, thrown); } /** * Log a SEVERE message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void severefmt(String fmt, Throwable thrown) { logfmt(Level.SEVERE, thrown, fmt, thrown); } /** * Log a WARNING message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void warningfmt(String fmt, Throwable thrown) { logfmt(Level.WARNING, thrown, fmt, thrown); } /** * Log an INFO message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void infofmt(String fmt, Throwable thrown) { logfmt(Level.INFO, thrown, fmt, thrown); } /** * Log a CONFIG message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(java.util.Locale, String, Object[]) */ public void configfmt(String fmt, Throwable thrown) { logfmt(Level.CONFIG, thrown, fmt, thrown); } /** * Log a FINE message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void finefmt(String fmt, Throwable thrown) { logfmt(Level.FINE, thrown, fmt, thrown); } /** * Log a FINER message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void finerfmt(String fmt, Throwable thrown) { logfmt(Level.FINER, thrown, fmt, thrown); } /** * Log a FINEST message. * <p> * If the logger currently accepts messages of the supplied level, * then the {@code fmt} and {@code thrown} are converted to a string * using {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param thrown the throwable which triggered this log event, * and parameter to the formatter message * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void finestfmt(String fmt, Throwable thrown) { logfmt(Level.FINEST, thrown, fmt, thrown); } /** * Log a SEVERE message, with an array of object arguments. * <p> * If the logger is currently enabled for the SEVERE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void severe(String msg, Object... params) { log(Level.SEVERE, msg, params); } /** * Log a WARNING message. * <p> * If the logger is currently enabled for the WARNING message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void warning(String msg, Object... params) { log(Level.WARNING, msg, params); } /** * Log an INFO message. * <p> * If the logger is currently enabled for the INFO message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void info(String msg, Object... params) { log(Level.INFO, msg, params); } /** * Log a CONFIG message. * <p> * If the logger is currently enabled for the CONFIG message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void config(String msg, Object... params) { log(Level.CONFIG, msg, params); } /** * Log a FINE message. * <p> * If the logger is currently enabled for the FINE message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void fine(String msg, Object... params) { log(Level.FINE, msg, params); } /** * Log a FINER message. * <p> * If the logger is currently enabled for the FINER message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void finer(String msg, Object... params) { log(Level.FINER, msg, params); } /** * Log a FINEST message. * <p> * If the logger is currently enabled for the FINEST message * level then the given message is forwarded to all the * registered output Handler objects. * * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ public void finest(String msg, Object... params) { log(Level.FINEST, msg, params); } /** * Log a SEVERE message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void severefmt(String fmt, Object... args) { logfmt(Level.SEVERE, fmt, args); } /** * Log a WARNING message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void warningfmt(String fmt, Object... args) { logfmt(Level.WARNING, fmt, args); } /** * Log an INFO message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void infofmt(String fmt, Object... args) { logfmt(Level.INFO, fmt, args); } /** * Log a CONFIG message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(java.util.Locale, String, Object[]) */ public void configfmt(String fmt, Object... args) { logfmt(Level.CONFIG, fmt, args); } /** * Log a FINE message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void finefmt(String fmt, Object... args) { logfmt(Level.FINE, fmt, args); } /** * Log a FINER message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void finerfmt(String fmt, Object... args) { logfmt(Level.FINER, fmt, args); } /** * Log a FINEST message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and is forwarded to all the registered output Handler objects. * * @param fmt A format string * @param args array of parameters to the formatter * @see java.util.logging.Formatter * @see String#format(String, Object[]) */ public void finestfmt(String fmt, Object... args) { logfmt(Level.FINEST, fmt, args); } /** * Log a SEVERE message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void severefmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.SEVERE, thrown, fmt, args); } /** * Log a WARNING message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void warningfmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.WARNING, thrown, fmt, args); } /** * Log a INFO message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void infofmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.INFO, thrown, fmt, args); } /** * Log a CONFIG message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void configfmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.CONFIG, thrown, fmt, args); } /** * Log a FINE message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void finefmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.FINE, thrown, fmt, args); } /** * Log a FINER message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void finerfmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.FINER, thrown, fmt, args); } /** * Log a FINEST message. * <p> * If the logger currently accepts messages of the supplied level, * then the fmt and args are converted to a string using * {@link String#format(String, Object[])} * and forwarded to all the registered output Handler objects. * * @param thrown the throwable which triggered this log event * @param fmt the string message (or a key in the message catalog) * @param args array of parameters to the message */ public void finestfmt(Throwable thrown, String fmt, Object... args) { logfmt(Level.FINEST, thrown, fmt, args); } }
googleapis/google-cloud-java
37,811
java-migrationcenter/proto-google-cloud-migrationcenter-v1/src/main/java/com/google/cloud/migrationcenter/v1/Insight.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/migrationcenter/v1/migrationcenter.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.migrationcenter.v1; /** * * * <pre> * An insight about an asset. * </pre> * * Protobuf type {@code google.cloud.migrationcenter.v1.Insight} */ public final class Insight extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.migrationcenter.v1.Insight) InsightOrBuilder { private static final long serialVersionUID = 0L; // Use Insight.newBuilder() to construct. private Insight(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Insight() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Insight(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.migrationcenter.v1.MigrationCenterProto .internal_static_google_cloud_migrationcenter_v1_Insight_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.migrationcenter.v1.MigrationCenterProto .internal_static_google_cloud_migrationcenter_v1_Insight_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.migrationcenter.v1.Insight.class, com.google.cloud.migrationcenter.v1.Insight.Builder.class); } private int insightCase_ = 0; @SuppressWarnings("serial") private java.lang.Object insight_; public enum InsightCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { MIGRATION_INSIGHT(1), GENERIC_INSIGHT(2), INSIGHT_NOT_SET(0); private final int value; private InsightCase(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 InsightCase valueOf(int value) { return forNumber(value); } public static InsightCase forNumber(int value) { switch (value) { case 1: return MIGRATION_INSIGHT; case 2: return GENERIC_INSIGHT; case 0: return INSIGHT_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public InsightCase getInsightCase() { return InsightCase.forNumber(insightCase_); } public static final int MIGRATION_INSIGHT_FIELD_NUMBER = 1; /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the migrationInsight field is set. */ @java.lang.Override public boolean hasMigrationInsight() { return insightCase_ == 1; } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The migrationInsight. */ @java.lang.Override public com.google.cloud.migrationcenter.v1.MigrationInsight getMigrationInsight() { if (insightCase_ == 1) { return (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_; } return com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance(); } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.migrationcenter.v1.MigrationInsightOrBuilder getMigrationInsightOrBuilder() { if (insightCase_ == 1) { return (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_; } return com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance(); } public static final int GENERIC_INSIGHT_FIELD_NUMBER = 2; /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the genericInsight field is set. */ @java.lang.Override public boolean hasGenericInsight() { return insightCase_ == 2; } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The genericInsight. */ @java.lang.Override public com.google.cloud.migrationcenter.v1.GenericInsight getGenericInsight() { if (insightCase_ == 2) { return (com.google.cloud.migrationcenter.v1.GenericInsight) insight_; } return com.google.cloud.migrationcenter.v1.GenericInsight.getDefaultInstance(); } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.migrationcenter.v1.GenericInsightOrBuilder getGenericInsightOrBuilder() { if (insightCase_ == 2) { return (com.google.cloud.migrationcenter.v1.GenericInsight) insight_; } return com.google.cloud.migrationcenter.v1.GenericInsight.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 (insightCase_ == 1) { output.writeMessage(1, (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_); } if (insightCase_ == 2) { output.writeMessage(2, (com.google.cloud.migrationcenter.v1.GenericInsight) insight_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (insightCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_); } if (insightCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.cloud.migrationcenter.v1.GenericInsight) insight_); } 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.migrationcenter.v1.Insight)) { return super.equals(obj); } com.google.cloud.migrationcenter.v1.Insight other = (com.google.cloud.migrationcenter.v1.Insight) obj; if (!getInsightCase().equals(other.getInsightCase())) return false; switch (insightCase_) { case 1: if (!getMigrationInsight().equals(other.getMigrationInsight())) return false; break; case 2: if (!getGenericInsight().equals(other.getGenericInsight())) 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 (insightCase_) { case 1: hash = (37 * hash) + MIGRATION_INSIGHT_FIELD_NUMBER; hash = (53 * hash) + getMigrationInsight().hashCode(); break; case 2: hash = (37 * hash) + GENERIC_INSIGHT_FIELD_NUMBER; hash = (53 * hash) + getGenericInsight().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.migrationcenter.v1.Insight parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.migrationcenter.v1.Insight 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.migrationcenter.v1.Insight parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.migrationcenter.v1.Insight 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.migrationcenter.v1.Insight parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.migrationcenter.v1.Insight parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.migrationcenter.v1.Insight parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.migrationcenter.v1.Insight 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.migrationcenter.v1.Insight parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.migrationcenter.v1.Insight 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.migrationcenter.v1.Insight parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.migrationcenter.v1.Insight 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.migrationcenter.v1.Insight prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * An insight about an asset. * </pre> * * Protobuf type {@code google.cloud.migrationcenter.v1.Insight} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.migrationcenter.v1.Insight) com.google.cloud.migrationcenter.v1.InsightOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.migrationcenter.v1.MigrationCenterProto .internal_static_google_cloud_migrationcenter_v1_Insight_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.migrationcenter.v1.MigrationCenterProto .internal_static_google_cloud_migrationcenter_v1_Insight_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.migrationcenter.v1.Insight.class, com.google.cloud.migrationcenter.v1.Insight.Builder.class); } // Construct using com.google.cloud.migrationcenter.v1.Insight.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (migrationInsightBuilder_ != null) { migrationInsightBuilder_.clear(); } if (genericInsightBuilder_ != null) { genericInsightBuilder_.clear(); } insightCase_ = 0; insight_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.migrationcenter.v1.MigrationCenterProto .internal_static_google_cloud_migrationcenter_v1_Insight_descriptor; } @java.lang.Override public com.google.cloud.migrationcenter.v1.Insight getDefaultInstanceForType() { return com.google.cloud.migrationcenter.v1.Insight.getDefaultInstance(); } @java.lang.Override public com.google.cloud.migrationcenter.v1.Insight build() { com.google.cloud.migrationcenter.v1.Insight result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.migrationcenter.v1.Insight buildPartial() { com.google.cloud.migrationcenter.v1.Insight result = new com.google.cloud.migrationcenter.v1.Insight(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.migrationcenter.v1.Insight result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.cloud.migrationcenter.v1.Insight result) { result.insightCase_ = insightCase_; result.insight_ = this.insight_; if (insightCase_ == 1 && migrationInsightBuilder_ != null) { result.insight_ = migrationInsightBuilder_.build(); } if (insightCase_ == 2 && genericInsightBuilder_ != null) { result.insight_ = genericInsightBuilder_.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.migrationcenter.v1.Insight) { return mergeFrom((com.google.cloud.migrationcenter.v1.Insight) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.migrationcenter.v1.Insight other) { if (other == com.google.cloud.migrationcenter.v1.Insight.getDefaultInstance()) return this; switch (other.getInsightCase()) { case MIGRATION_INSIGHT: { mergeMigrationInsight(other.getMigrationInsight()); break; } case GENERIC_INSIGHT: { mergeGenericInsight(other.getGenericInsight()); break; } case INSIGHT_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( getMigrationInsightFieldBuilder().getBuilder(), extensionRegistry); insightCase_ = 1; break; } // case 10 case 18: { input.readMessage(getGenericInsightFieldBuilder().getBuilder(), extensionRegistry); insightCase_ = 2; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int insightCase_ = 0; private java.lang.Object insight_; public InsightCase getInsightCase() { return InsightCase.forNumber(insightCase_); } public Builder clearInsight() { insightCase_ = 0; insight_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.migrationcenter.v1.MigrationInsight, com.google.cloud.migrationcenter.v1.MigrationInsight.Builder, com.google.cloud.migrationcenter.v1.MigrationInsightOrBuilder> migrationInsightBuilder_; /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the migrationInsight field is set. */ @java.lang.Override public boolean hasMigrationInsight() { return insightCase_ == 1; } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The migrationInsight. */ @java.lang.Override public com.google.cloud.migrationcenter.v1.MigrationInsight getMigrationInsight() { if (migrationInsightBuilder_ == null) { if (insightCase_ == 1) { return (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_; } return com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance(); } else { if (insightCase_ == 1) { return migrationInsightBuilder_.getMessage(); } return com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance(); } } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setMigrationInsight(com.google.cloud.migrationcenter.v1.MigrationInsight value) { if (migrationInsightBuilder_ == null) { if (value == null) { throw new NullPointerException(); } insight_ = value; onChanged(); } else { migrationInsightBuilder_.setMessage(value); } insightCase_ = 1; return this; } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setMigrationInsight( com.google.cloud.migrationcenter.v1.MigrationInsight.Builder builderForValue) { if (migrationInsightBuilder_ == null) { insight_ = builderForValue.build(); onChanged(); } else { migrationInsightBuilder_.setMessage(builderForValue.build()); } insightCase_ = 1; return this; } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeMigrationInsight( com.google.cloud.migrationcenter.v1.MigrationInsight value) { if (migrationInsightBuilder_ == null) { if (insightCase_ == 1 && insight_ != com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance()) { insight_ = com.google.cloud.migrationcenter.v1.MigrationInsight.newBuilder( (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_) .mergeFrom(value) .buildPartial(); } else { insight_ = value; } onChanged(); } else { if (insightCase_ == 1) { migrationInsightBuilder_.mergeFrom(value); } else { migrationInsightBuilder_.setMessage(value); } } insightCase_ = 1; return this; } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearMigrationInsight() { if (migrationInsightBuilder_ == null) { if (insightCase_ == 1) { insightCase_ = 0; insight_ = null; onChanged(); } } else { if (insightCase_ == 1) { insightCase_ = 0; insight_ = null; } migrationInsightBuilder_.clear(); } return this; } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.migrationcenter.v1.MigrationInsight.Builder getMigrationInsightBuilder() { return getMigrationInsightFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.migrationcenter.v1.MigrationInsightOrBuilder getMigrationInsightOrBuilder() { if ((insightCase_ == 1) && (migrationInsightBuilder_ != null)) { return migrationInsightBuilder_.getMessageOrBuilder(); } else { if (insightCase_ == 1) { return (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_; } return com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance(); } } /** * * * <pre> * Output only. An insight about potential migrations for an asset. * </pre> * * <code> * .google.cloud.migrationcenter.v1.MigrationInsight migration_insight = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.migrationcenter.v1.MigrationInsight, com.google.cloud.migrationcenter.v1.MigrationInsight.Builder, com.google.cloud.migrationcenter.v1.MigrationInsightOrBuilder> getMigrationInsightFieldBuilder() { if (migrationInsightBuilder_ == null) { if (!(insightCase_ == 1)) { insight_ = com.google.cloud.migrationcenter.v1.MigrationInsight.getDefaultInstance(); } migrationInsightBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.migrationcenter.v1.MigrationInsight, com.google.cloud.migrationcenter.v1.MigrationInsight.Builder, com.google.cloud.migrationcenter.v1.MigrationInsightOrBuilder>( (com.google.cloud.migrationcenter.v1.MigrationInsight) insight_, getParentForChildren(), isClean()); insight_ = null; } insightCase_ = 1; onChanged(); return migrationInsightBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.migrationcenter.v1.GenericInsight, com.google.cloud.migrationcenter.v1.GenericInsight.Builder, com.google.cloud.migrationcenter.v1.GenericInsightOrBuilder> genericInsightBuilder_; /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the genericInsight field is set. */ @java.lang.Override public boolean hasGenericInsight() { return insightCase_ == 2; } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The genericInsight. */ @java.lang.Override public com.google.cloud.migrationcenter.v1.GenericInsight getGenericInsight() { if (genericInsightBuilder_ == null) { if (insightCase_ == 2) { return (com.google.cloud.migrationcenter.v1.GenericInsight) insight_; } return com.google.cloud.migrationcenter.v1.GenericInsight.getDefaultInstance(); } else { if (insightCase_ == 2) { return genericInsightBuilder_.getMessage(); } return com.google.cloud.migrationcenter.v1.GenericInsight.getDefaultInstance(); } } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setGenericInsight(com.google.cloud.migrationcenter.v1.GenericInsight value) { if (genericInsightBuilder_ == null) { if (value == null) { throw new NullPointerException(); } insight_ = value; onChanged(); } else { genericInsightBuilder_.setMessage(value); } insightCase_ = 2; return this; } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setGenericInsight( com.google.cloud.migrationcenter.v1.GenericInsight.Builder builderForValue) { if (genericInsightBuilder_ == null) { insight_ = builderForValue.build(); onChanged(); } else { genericInsightBuilder_.setMessage(builderForValue.build()); } insightCase_ = 2; return this; } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeGenericInsight(com.google.cloud.migrationcenter.v1.GenericInsight value) { if (genericInsightBuilder_ == null) { if (insightCase_ == 2 && insight_ != com.google.cloud.migrationcenter.v1.GenericInsight.getDefaultInstance()) { insight_ = com.google.cloud.migrationcenter.v1.GenericInsight.newBuilder( (com.google.cloud.migrationcenter.v1.GenericInsight) insight_) .mergeFrom(value) .buildPartial(); } else { insight_ = value; } onChanged(); } else { if (insightCase_ == 2) { genericInsightBuilder_.mergeFrom(value); } else { genericInsightBuilder_.setMessage(value); } } insightCase_ = 2; return this; } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearGenericInsight() { if (genericInsightBuilder_ == null) { if (insightCase_ == 2) { insightCase_ = 0; insight_ = null; onChanged(); } } else { if (insightCase_ == 2) { insightCase_ = 0; insight_ = null; } genericInsightBuilder_.clear(); } return this; } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.migrationcenter.v1.GenericInsight.Builder getGenericInsightBuilder() { return getGenericInsightFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.migrationcenter.v1.GenericInsightOrBuilder getGenericInsightOrBuilder() { if ((insightCase_ == 2) && (genericInsightBuilder_ != null)) { return genericInsightBuilder_.getMessageOrBuilder(); } else { if (insightCase_ == 2) { return (com.google.cloud.migrationcenter.v1.GenericInsight) insight_; } return com.google.cloud.migrationcenter.v1.GenericInsight.getDefaultInstance(); } } /** * * * <pre> * Output only. A generic insight about an asset * </pre> * * <code> * .google.cloud.migrationcenter.v1.GenericInsight generic_insight = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.migrationcenter.v1.GenericInsight, com.google.cloud.migrationcenter.v1.GenericInsight.Builder, com.google.cloud.migrationcenter.v1.GenericInsightOrBuilder> getGenericInsightFieldBuilder() { if (genericInsightBuilder_ == null) { if (!(insightCase_ == 2)) { insight_ = com.google.cloud.migrationcenter.v1.GenericInsight.getDefaultInstance(); } genericInsightBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.migrationcenter.v1.GenericInsight, com.google.cloud.migrationcenter.v1.GenericInsight.Builder, com.google.cloud.migrationcenter.v1.GenericInsightOrBuilder>( (com.google.cloud.migrationcenter.v1.GenericInsight) insight_, getParentForChildren(), isClean()); insight_ = null; } insightCase_ = 2; onChanged(); return genericInsightBuilder_; } @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.migrationcenter.v1.Insight) } // @@protoc_insertion_point(class_scope:google.cloud.migrationcenter.v1.Insight) private static final com.google.cloud.migrationcenter.v1.Insight DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.migrationcenter.v1.Insight(); } public static com.google.cloud.migrationcenter.v1.Insight getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Insight> PARSER = new com.google.protobuf.AbstractParser<Insight>() { @java.lang.Override public Insight 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<Insight> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Insight> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.migrationcenter.v1.Insight getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hop
37,891
plugins/transforms/kafka/src/main/java/org/apache/hop/pipeline/transforms/kafka/consumer/KafkaConsumerInputDialog.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.pipeline.transforms.kafka.consumer; import static java.util.Optional.ofNullable; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.hop.core.Const; import org.apache.hop.core.Props; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.gui.Point; import org.apache.hop.core.row.value.ValueMetaFactory; import org.apache.hop.core.util.Utils; import org.apache.hop.core.variables.IVariables; import org.apache.hop.execution.ExecutionInfoLocation; import org.apache.hop.execution.profiling.ExecutionDataProfile; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.TransformWithMappingMeta; import org.apache.hop.pipeline.transform.TransformMeta; import org.apache.hop.pipeline.transforms.injector.InjectorField; import org.apache.hop.pipeline.transforms.injector.InjectorMeta; import org.apache.hop.pipeline.transforms.kafka.shared.KafkaDialogHelper; import org.apache.hop.pipeline.transforms.kafka.shared.KafkaFactory; import org.apache.hop.ui.core.PropsUi; import org.apache.hop.ui.core.dialog.BaseDialog; 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.gui.WindowProperty; import org.apache.hop.ui.core.widget.ColumnInfo; import org.apache.hop.ui.core.widget.ComboVar; import org.apache.hop.ui.core.widget.MetaSelectionLine; 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.file.pipeline.HopPipelineFileType; import org.apache.hop.ui.hopgui.perspective.dataorch.HopDataOrchestrationPerspective; import org.apache.hop.ui.pipeline.transform.BaseTransformDialog; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyListener; 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.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; public class KafkaConsumerInputDialog extends BaseTransformDialog { private static final Class<?> PKG = KafkaConsumerInputDialog.class; private static final Map<String, String> DEFAULT_OPTION_VALUES = ImmutableMap.of(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); private final KafkaFactory kafkaFactory = KafkaFactory.defaultFactory(); protected KafkaConsumerInputMeta meta; protected Label wlFilename; protected TextVar wFilename; protected Button wbFilename; protected Button wbCreatePipeline; protected MetaSelectionLine<ExecutionInfoLocation> wLocation; protected MetaSelectionLine<ExecutionDataProfile> wProfile; protected Label wlSubTransform; protected ComboVar wSubTransform; protected ModifyListener lsMod; protected Label wlBatchSize; protected TextVar wBatchSize; protected Label wlBatchDuration; protected TextVar wBatchDuration; protected CTabFolder wTabFolder; protected CTabItem wSetupTab; protected CTabItem wBatchTab; protected CTabItem wResultsTab; protected Composite wSetupComp; protected Composite wBatchComp; protected Composite wResultsComp; private final HopGui hopGui; private TextVar wConsumerGroup; private Button wbAutoCommit; private Button wbManualCommit; private TableView fieldsTable; private TableView topicsTable; private TableView optionsTable; private TextVar wBootstrapServers; private final int middle = props.getMiddlePct(); private final int margin = PropsUi.getMargin(); public KafkaConsumerInputDialog( Shell parent, IVariables variables, KafkaConsumerInputMeta transformMeta, PipelineMeta pipelineMeta) { super(parent, variables, transformMeta, pipelineMeta); this.meta = transformMeta; hopGui = HopGui.getInstance(); } @Override public String open() { Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.MIN | SWT.MAX | SWT.RESIZE); PropsUi.setLook(shell); setShellImage(shell, meta); shell.setMinimumSize(527, 622); lsMod = e -> meta.setChanged(); changed = meta.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = PropsUi.getMargin(); formLayout.marginHeight = PropsUi.getMargin(); shell.setLayout(formLayout); shell.setText(getDialogTitle()); // Some buttons at the bottom... // wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); wCancel.addListener(SWT.Selection, e -> cancel()); wOk = new Button(shell, SWT.PUSH); wOk.setText(BaseMessages.getString(PKG, "System.Button.OK")); wOk.addListener(SWT.Selection, e -> ok()); positionBottomButtons(shell, new Button[] {wOk, wCancel}, margin, null); wlTransformName = new Label(shell, SWT.RIGHT); wlTransformName.setText( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.TransformName.Label")); PropsUi.setLook(wlTransformName); fdlTransformName = new FormData(); fdlTransformName.left = new FormAttachment(0, 0); fdlTransformName.top = new FormAttachment(0, margin); fdlTransformName.right = new FormAttachment(middle, -margin); wlTransformName.setLayoutData(fdlTransformName); wTransformName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wTransformName.setText(transformName); PropsUi.setLook(wTransformName); wTransformName.addModifyListener(lsMod); fdTransformName = new FormData(); fdTransformName.left = new FormAttachment(wlTransformName, margin); fdTransformName.right = new FormAttachment(100, 0); fdTransformName.top = new FormAttachment(wlTransformName, 0, SWT.CENTER); wTransformName.setLayoutData(fdTransformName); // The filename // wlFilename = new Label(shell, SWT.RIGHT); PropsUi.setLook(wlFilename); wlFilename.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Pipeline")); FormData fdlFilename = new FormData(); fdlFilename.left = new FormAttachment(0, 0); fdlFilename.top = new FormAttachment(wTransformName, margin * 2); fdlFilename.right = new FormAttachment(middle, -margin); wlFilename.setLayoutData(fdlFilename); wbCreatePipeline = new Button(shell, SWT.PUSH); PropsUi.setLook(wbCreatePipeline); wbCreatePipeline.setText( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Pipeline.CreatePipeline")); FormData fdCreatePipeline = new FormData(); fdCreatePipeline.right = new FormAttachment(100, 0); fdCreatePipeline.top = new FormAttachment(wlFilename, 0, SWT.CENTER); wbCreatePipeline.setLayoutData(fdCreatePipeline); wbCreatePipeline.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { createNewKafkaPipeline(); } }); wbFilename = new Button(shell, SWT.PUSH); PropsUi.setLook(wbFilename); wbFilename.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Pipeline.Browse")); FormData fdbFilename = new FormData(); fdbFilename.right = new FormAttachment(wbCreatePipeline, -margin); fdbFilename.top = new FormAttachment(wlFilename, 0, SWT.CENTER); wbFilename.setLayoutData(fdbFilename); wbFilename.addListener( SWT.Selection, e -> { HopPipelineFileType pipelineFileType = new HopPipelineFileType(); BaseDialog.presentFileDialog( shell, wFilename, variables, pipelineFileType.getFilterExtensions(), pipelineFileType.getFilterNames(), true); }); wFilename = new TextVar(variables, shell, SWT.SINGLE | SWT.BORDER | SWT.LEFT); PropsUi.setLook(wFilename); FormData fdFilename = new FormData(); fdFilename.left = new FormAttachment(wlFilename, margin); fdFilename.right = new FormAttachment(wbFilename, -PropsUi.getMargin()); fdFilename.top = new FormAttachment(wlFilename, 0, SWT.CENTER); wFilename.setLayoutData(fdFilename); wLocation = new MetaSelectionLine<>( variables, metadataProvider, ExecutionInfoLocation.class, shell, SWT.NONE, BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Location.Label"), BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Location.Tooltip")); FormData fdLocation = new FormData(); fdLocation.left = new FormAttachment(0, 0); fdLocation.top = new FormAttachment(wFilename, margin); fdLocation.right = new FormAttachment(100, 0); wLocation.setLayoutData(fdLocation); wProfile = new MetaSelectionLine<>( variables, metadataProvider, ExecutionDataProfile.class, shell, SWT.NONE, BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Profile.Label"), BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Profile.Tooltip")); FormData fdProfile = new FormData(); fdProfile.left = new FormAttachment(0, 0); fdProfile.top = new FormAttachment(wLocation, margin); fdProfile.right = new FormAttachment(100, 0); wProfile.setLayoutData(fdProfile); try { wLocation.fillItems(); wProfile.fillItems(); } catch (Exception e) { new ErrorDialog(shell, "Error", "Error getting lists of locations and profiles", e); } // Start of tabbed display // wTabFolder = new CTabFolder(shell, SWT.BORDER); PropsUi.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); wTabFolder.setUnselectedCloseVisible(true); FormData fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(wProfile, 15); fdTabFolder.bottom = new FormAttachment(wOk, -15); fdTabFolder.right = new FormAttachment(100, 0); wTabFolder.setLayoutData(fdTabFolder); buildSetupTab(); buildBatchTab(); buildResultsTab(); createAdditionalTabs(); getData(); wTabFolder.setSelection(0); wTransformName.selectAll(); wTransformName.setFocus(); BaseDialog.defaultShellHandling(shell, c -> ok(), c -> cancel()); return transformName; } private void ok() { transformName = wTransformName.getText(); if (Utils.isEmpty(wFilename.getText())) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.FilenameMissing.Header")); mb.setMessage( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.FilenameMissing.Message")); mb.open(); return; } if (isSelfReferencing()) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.SelfReference.Header")); mb.setMessage(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.SelfReference.Message")); mb.open(); return; } updateMeta(meta); dispose(); } @Override public void dispose() { props.setScreen(new WindowProperty(shell)); shell.dispose(); } private void updateMeta(KafkaConsumerInputMeta m) { m.setFilename(wFilename.getText()); m.setExecutionInformationLocation(wLocation.getText()); m.setExecutionDataProfile(wProfile.getText()); m.setBatchSize(wBatchSize.getText()); m.setBatchDuration(wBatchDuration.getText()); m.setSubTransform(wSubTransform.getText()); setTopicsFromTable(); m.setConsumerGroup(wConsumerGroup.getText()); m.setDirectBootstrapServers(wBootstrapServers.getText()); m.setAutoCommit(wbAutoCommit.getSelection()); setFieldsFromTable(); setOptionsFromTable(); } protected String getDialogTitle() { return BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Shell.Title"); } protected void createAdditionalTabs() { buildFieldsTab(); buildOptionsTab(); buildOffsetManagement(); } private void buildOffsetManagement() { Group wOffsetGroup = new Group(wBatchComp, SWT.SHADOW_ETCHED_IN); wOffsetGroup.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.OffsetManagement")); FormLayout flOffsetGroup = new FormLayout(); flOffsetGroup.marginHeight = 15; flOffsetGroup.marginWidth = 15; wOffsetGroup.setLayout(flOffsetGroup); FormData fdOffsetGroup = new FormData(); fdOffsetGroup.top = new FormAttachment(wBatchSize, 15); fdOffsetGroup.left = new FormAttachment(0, 0); fdOffsetGroup.right = new FormAttachment(100, 0); wOffsetGroup.setLayoutData(fdOffsetGroup); PropsUi.setLook(wOffsetGroup); wbAutoCommit = new Button(wOffsetGroup, SWT.RADIO); wbAutoCommit.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.AutoOffset")); FormData fdbAutoCommit = new FormData(); fdbAutoCommit.top = new FormAttachment(0, 0); fdbAutoCommit.left = new FormAttachment(middle, 0); wbAutoCommit.setLayoutData(fdbAutoCommit); PropsUi.setLook(wbAutoCommit); wbManualCommit = new Button(wOffsetGroup, SWT.RADIO); wbManualCommit.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.ManualOffset")); FormData fdbManualCommit = new FormData(); fdbManualCommit.left = new FormAttachment(middle, 0); fdbManualCommit.top = new FormAttachment(wbAutoCommit, margin); wbManualCommit.setLayoutData(fdbManualCommit); PropsUi.setLook(wbManualCommit); } protected void buildSetup(Composite wSetupComp) { PropsUi.setLook(wSetupComp); FormLayout setupLayout = new FormLayout(); setupLayout.marginHeight = 15; setupLayout.marginWidth = 15; wSetupComp.setLayout(setupLayout); Label wlBootstrapServers = new Label(wSetupComp, SWT.RIGHT); PropsUi.setLook(wlBootstrapServers); wlBootstrapServers.setText( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.BootstrapServers")); FormData fdlBootstrapServers = new FormData(); fdlBootstrapServers.left = new FormAttachment(0, 0); fdlBootstrapServers.top = new FormAttachment(0, 0); fdlBootstrapServers.right = new FormAttachment(middle, -margin); wlBootstrapServers.setLayoutData(fdlBootstrapServers); wBootstrapServers = new TextVar(variables, wSetupComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wBootstrapServers); wBootstrapServers.addModifyListener(lsMod); FormData fdBootstrapServers = new FormData(); fdBootstrapServers.left = new FormAttachment(wlBootstrapServers, margin); fdBootstrapServers.top = new FormAttachment(wlBootstrapServers, 0, SWT.CENTER); fdBootstrapServers.right = new FormAttachment(100, 0); wBootstrapServers.setLayoutData(fdBootstrapServers); Label wlTopic = new Label(wSetupComp, SWT.LEFT); PropsUi.setLook(wlTopic); wlTopic.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Topics")); FormData fdlTopic = new FormData(); fdlTopic.left = new FormAttachment(0, 0); fdlTopic.top = new FormAttachment(wBootstrapServers, 3 * PropsUi.getMargin()); fdlTopic.right = new FormAttachment(props.getMiddlePct(), 0); wlTopic.setLayoutData(fdlTopic); wConsumerGroup = new TextVar(variables, wSetupComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wConsumerGroup); wConsumerGroup.addModifyListener(lsMod); FormData fdConsumerGroup = new FormData(); fdConsumerGroup.right = new FormAttachment(100, 0); fdConsumerGroup.bottom = new FormAttachment(100, 0); wConsumerGroup.setLayoutData(fdConsumerGroup); Label wlConsumerGroup = new Label(wSetupComp, SWT.RIGHT); PropsUi.setLook(wlConsumerGroup); wlConsumerGroup.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.ConsumerGroup")); FormData fdlConsumerGroup = new FormData(); fdlConsumerGroup.left = new FormAttachment(0, 0); fdlConsumerGroup.top = new FormAttachment(wConsumerGroup, 0, SWT.CENTER); fdlConsumerGroup.right = new FormAttachment(middle, -margin); wlConsumerGroup.setLayoutData(fdlConsumerGroup); fdConsumerGroup.left = new FormAttachment(wlConsumerGroup, margin); buildTopicsTable(wSetupComp, wlTopic, wlConsumerGroup); FormData fdSetupComp = new FormData(); fdSetupComp.left = new FormAttachment(0, 0); fdSetupComp.top = new FormAttachment(0, 0); fdSetupComp.right = new FormAttachment(100, 0); fdSetupComp.bottom = new FormAttachment(100, 0); wSetupComp.setLayoutData(fdSetupComp); wSetupComp.layout(); wSetupTab.setControl(wSetupComp); } private void buildFieldsTab() { CTabItem wFieldsTab = new CTabItem(wTabFolder, SWT.NONE, 2); wFieldsTab.setFont(GuiResource.getInstance().getFontDefault()); wFieldsTab.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.FieldsTab")); Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wFieldsComp); FormLayout fieldsLayout = new FormLayout(); fieldsLayout.marginHeight = 15; fieldsLayout.marginWidth = 15; wFieldsComp.setLayout(fieldsLayout); FormData fieldsFormData = new FormData(); fieldsFormData.left = new FormAttachment(0, 0); fieldsFormData.top = new FormAttachment(wFieldsComp, 0); fieldsFormData.right = new FormAttachment(100, 0); fieldsFormData.bottom = new FormAttachment(100, 0); wFieldsComp.setLayoutData(fieldsFormData); buildFieldTable(wFieldsComp, wFieldsComp); wFieldsComp.layout(); wFieldsTab.setControl(wFieldsComp); } private void buildOptionsTab() { CTabItem wOptionsTab = new CTabItem(wTabFolder, SWT.NONE); wOptionsTab.setFont(GuiResource.getInstance().getFontDefault()); wOptionsTab.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.OptionsTab")); Composite wOptionsComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wOptionsComp); FormLayout fieldsLayout = new FormLayout(); fieldsLayout.marginHeight = 15; fieldsLayout.marginWidth = 15; wOptionsComp.setLayout(fieldsLayout); FormData optionsFormData = new FormData(); optionsFormData.left = new FormAttachment(0, 0); optionsFormData.top = new FormAttachment(wOptionsComp, 0); optionsFormData.right = new FormAttachment(100, 0); optionsFormData.bottom = new FormAttachment(100, 0); wOptionsComp.setLayoutData(optionsFormData); buildOptionsTable(wOptionsComp); wOptionsComp.layout(); wOptionsTab.setControl(wOptionsComp); } private void buildFieldTable(Composite parentWidget, Control relativePosition) { ColumnInfo[] columns = getFieldColumns(); int fieldCount = KafkaConsumerField.Name.values().length; fieldsTable = new TableView( variables, parentWidget, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, columns, fieldCount, true, lsMod, props, false); fieldsTable.setSortable(false); populateFieldData(); FormData fdData = new FormData(); fdData.left = new FormAttachment(0, 0); fdData.top = new FormAttachment(relativePosition, 5); fdData.right = new FormAttachment(100, 0); fieldsTable.setLayoutData(fdData); // don't let any rows get deleted or added (this does not affect the read-only state of the // cells) fieldsTable.setReadonly(true); } private void buildOptionsTable(Composite parentWidget) { ColumnInfo[] columns = getOptionsColumns(); if (meta.getConfig().isEmpty()) { // inital call List<String> list = KafkaDialogHelper.getConsumerAdvancedConfigOptionNames(); Map<String, String> advancedConfig = new LinkedHashMap<>(); for (String item : list) { advancedConfig.put(item, DEFAULT_OPTION_VALUES.getOrDefault(item, "")); } meta.setConfig(advancedConfig); } int fieldCount = meta.getConfig().size(); optionsTable = new TableView( variables, parentWidget, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, columns, fieldCount, false, lsMod, props, false); optionsTable.setSortable(false); populateOptionsData(); FormData fdData = new FormData(); fdData.left = new FormAttachment(0, 0); fdData.top = new FormAttachment(0, 0); fdData.right = new FormAttachment(100, 0); fdData.bottom = new FormAttachment(100, 0); optionsTable.setLayoutData(fdData); } private void buildSetupTab() { wSetupTab = new CTabItem(wTabFolder, SWT.NONE); wSetupTab.setFont(GuiResource.getInstance().getFontDefault()); wSetupTab.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.SetupTab")); wSetupComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wSetupComp); FormLayout setupLayout = new FormLayout(); setupLayout.marginHeight = 15; setupLayout.marginWidth = 15; wSetupComp.setLayout(setupLayout); buildSetup(wSetupComp); FormData fdSetupComp = new FormData(); fdSetupComp.left = new FormAttachment(0, 0); fdSetupComp.top = new FormAttachment(0, 0); fdSetupComp.right = new FormAttachment(100, 0); fdSetupComp.bottom = new FormAttachment(100, 0); wSetupComp.setLayoutData(fdSetupComp); wSetupComp.layout(); wSetupTab.setControl(wSetupComp); } private void buildBatchTab() { wBatchTab = new CTabItem(wTabFolder, SWT.NONE); wBatchTab.setFont(GuiResource.getInstance().getFontDefault()); wBatchTab.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.BatchTab")); wBatchComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wBatchComp); FormLayout batchLayout = new FormLayout(); batchLayout.marginHeight = 15; batchLayout.marginWidth = 15; wBatchComp.setLayout(batchLayout); FormData fdBatchComp = new FormData(); fdBatchComp.left = new FormAttachment(0, 0); fdBatchComp.top = new FormAttachment(0, 0); fdBatchComp.right = new FormAttachment(100, 0); fdBatchComp.bottom = new FormAttachment(100, 0); wBatchComp.setLayoutData(fdBatchComp); wlBatchDuration = new Label(wBatchComp, SWT.RIGHT); PropsUi.setLook(wlBatchDuration); wlBatchDuration.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.BatchDuration")); FormData fdlBatchDuration = new FormData(); fdlBatchDuration.left = new FormAttachment(0, 0); fdlBatchDuration.top = new FormAttachment(0, 0); fdlBatchDuration.right = new FormAttachment(middle, -margin); wlBatchDuration.setLayoutData(fdlBatchDuration); wBatchDuration = new TextVar(variables, wBatchComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wBatchDuration); wBatchDuration.addModifyListener(lsMod); FormData fdBatchDuration = new FormData(); fdBatchDuration.left = new FormAttachment(wlBatchDuration, margin); fdBatchDuration.right = new FormAttachment(100, 0); fdBatchDuration.top = new FormAttachment(wlBatchDuration, 0, SWT.CENTER); wBatchDuration.setLayoutData(fdBatchDuration); wlBatchSize = new Label(wBatchComp, SWT.RIGHT); PropsUi.setLook(wlBatchSize); wlBatchSize.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.BatchSize")); FormData fdlBatchSize = new FormData(); fdlBatchSize.left = new FormAttachment(0, 0); fdlBatchSize.top = new FormAttachment(wBatchDuration, margin); fdlBatchSize.right = new FormAttachment(middle, -margin); wlBatchSize.setLayoutData(fdlBatchSize); wBatchSize = new TextVar(variables, wBatchComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wBatchSize); wBatchSize.addModifyListener(lsMod); FormData fdBatchSize = new FormData(); fdBatchSize.left = new FormAttachment(wlBatchSize, margin); fdBatchSize.right = new FormAttachment(100, 0); fdBatchSize.top = new FormAttachment(wlBatchSize, 0, SWT.CENTER); wBatchSize.setLayoutData(fdBatchSize); wBatchComp.layout(); wBatchTab.setControl(wBatchComp); } private void buildResultsTab() { wResultsTab = new CTabItem(wTabFolder, SWT.NONE); wResultsTab.setFont(GuiResource.getInstance().getFontDefault()); wResultsTab.setText(BaseMessages.getString(PKG, "KafkaConsumerInputDialog.ResultsTab")); wResultsComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wResultsComp); FormLayout resultsLayout = new FormLayout(); resultsLayout.marginHeight = 15; resultsLayout.marginWidth = 15; wResultsComp.setLayout(resultsLayout); FormData fdResultsComp = new FormData(); fdResultsComp.left = new FormAttachment(0, 0); fdResultsComp.top = new FormAttachment(0, 0); fdResultsComp.right = new FormAttachment(100, 0); fdResultsComp.bottom = new FormAttachment(100, 0); wResultsComp.setLayoutData(fdResultsComp); wlSubTransform = new Label(wResultsComp, SWT.RIGHT); PropsUi.setLook(wlSubTransform); FormData fdlSubTrans = new FormData(); fdlSubTrans.left = new FormAttachment(0, 0); fdlSubTrans.top = new FormAttachment(0, 0); fdlSubTrans.right = new FormAttachment(middle, -margin); wlSubTransform.setLayoutData(fdlSubTrans); wlSubTransform.setText( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Pipeline.SubPipelineTransform")); wSubTransform = new ComboVar(variables, wResultsComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wSubTransform); FormData fdSubTransform = new FormData(); fdSubTransform.left = new FormAttachment(wlSubTransform, margin); fdSubTransform.right = new FormAttachment(100, 0); fdSubTransform.top = new FormAttachment(wlSubTransform, 0, SWT.CENTER); wSubTransform.setLayoutData(fdSubTransform); wSubTransform.getCComboWidget().addListener(SWT.FocusIn, this::populateSubTransforms); wResultsComp.layout(); wResultsTab.setControl(wResultsComp); } private ColumnInfo[] getFieldColumns() { KafkaConsumerField.Type[] values = KafkaConsumerField.Type.values(); String[] supportedTypes = Arrays.stream(values).map(KafkaConsumerField.Type::toString).toArray(String[]::new); ColumnInfo referenceName = new ColumnInfo( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Column.Ref"), ColumnInfo.COLUMN_TYPE_TEXT, false, true); ColumnInfo name = new ColumnInfo( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Column.Name"), ColumnInfo.COLUMN_TYPE_TEXT, false, false); ColumnInfo type = new ColumnInfo( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Column.Type"), ColumnInfo.COLUMN_TYPE_CCOMBO, supportedTypes, false); // don't let the user edit the type for anything other than key & msg fields type.setDisabledListener( rowNumber -> { String ref = fieldsTable.getTable().getItem(rowNumber).getText(1); KafkaConsumerField.Name refName = KafkaConsumerField.Name.valueOf(ref.toUpperCase()); return !(refName == KafkaConsumerField.Name.KEY || refName == KafkaConsumerField.Name.MESSAGE); }); return new ColumnInfo[] {referenceName, name, type}; } private ColumnInfo[] getOptionsColumns() { ColumnInfo optionName = new ColumnInfo( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.NameField"), ColumnInfo.COLUMN_TYPE_TEXT, false, false); ColumnInfo value = new ColumnInfo( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.Column.Value"), ColumnInfo.COLUMN_TYPE_TEXT, false, false); value.setUsingVariables(true); return new ColumnInfo[] {optionName, value}; } private void populateFieldData() { List<KafkaConsumerField> fieldDefinitions = meta.getFieldDefinitions(); int rowIndex = 0; for (KafkaConsumerField field : fieldDefinitions) { TableItem key = fieldsTable.getTable().getItem(rowIndex++); key.setText(1, Const.NVL(field.getKafkaName().toString(), "")); key.setText(2, Const.NVL(field.getOutputName(), "")); key.setText(3, Const.NVL(field.getOutputType().toString(), "")); } } private void populateOptionsData() { int rowIndex = 0; for (Map.Entry<String, String> entry : meta.getConfig().entrySet()) { TableItem key = optionsTable.getTable().getItem(rowIndex++); key.setText(1, entry.getKey()); key.setText(2, entry.getValue()); } } private void populateTopicsData() { List<String> topics = meta.getTopics(); int rowIndex = 0; for (String topic : topics) { TableItem key = topicsTable.getTable().getItem(rowIndex++); if (topic != null) { key.setText(1, topic); } } } private void buildTopicsTable( Composite parentWidget, Control controlAbove, Control controlBelow) { ColumnInfo[] columns = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString(PKG, "KafkaConsumerInputDialog.NameField"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[1], false) }; columns[0].setUsingVariables(true); int topicsCount = meta.getTopics().size(); Listener lsFocusInTopic = e -> { CCombo comboWidget = (CCombo) e.widget; ComboVar topicsCombo = (ComboVar) comboWidget.getParent(); KafkaDialogHelper kdh = new KafkaDialogHelper( variables, topicsCombo, wBootstrapServers, kafkaFactory, optionsTable, meta.getParentTransformMeta()); kdh.clusterNameChanged(e); }; topicsTable = new TableView( variables, parentWidget, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, columns, topicsCount, false, lsMod, props, true, lsFocusInTopic); topicsTable.setSortable(false); populateTopicsData(); FormData fdData = new FormData(); fdData.left = new FormAttachment(0, 0); fdData.top = new FormAttachment(controlAbove, 5); fdData.right = new FormAttachment(100, 0); fdData.bottom = new FormAttachment(controlBelow, -10, SWT.TOP); topicsTable.setLayoutData(fdData); topicsTable.optimizeTableView(); } protected void getData() { wFilename.setText(Const.NVL(meta.getFilename(), "")); wLocation.setText(Const.NVL(meta.getExecutionInformationLocation(), "")); wProfile.setText(Const.NVL(meta.getExecutionDataProfile(), "")); wBootstrapServers.setText(Const.NVL(meta.getDirectBootstrapServers(), "")); populateTopicsData(); wSubTransform.setText(Const.NVL(meta.getSubTransform(), "")); wConsumerGroup.setText(Const.NVL(meta.getConsumerGroup(), "")); wBatchSize.setText(Const.NVL(meta.getBatchSize(), "")); wBatchDuration.setText(Const.NVL(meta.getBatchDuration(), "")); wbAutoCommit.setSelection(meta.isAutoCommit()); wbManualCommit.setSelection(!meta.isAutoCommit()); populateFieldData(); fieldsTable.optimizeTableView(); topicsTable.optimizeTableView(); optionsTable.optimizeTableView(); } private void cancel() { meta.setChanged(false); dispose(); } private void setFieldsFromTable() { int itemCount = fieldsTable.getItemCount(); for (int rowIndex = 0; rowIndex < itemCount; rowIndex++) { TableItem row = fieldsTable.getTable().getItem(rowIndex); String kafkaName = row.getText(1); String outputName = row.getText(2); String outputType = row.getText(3); try { KafkaConsumerField.Name ref = KafkaConsumerField.Name.valueOf(kafkaName.toUpperCase()); KafkaConsumerField field = new KafkaConsumerField(ref, outputName, KafkaConsumerField.Type.valueOf(outputType)); meta.setField(field); } catch (IllegalArgumentException e) { if (isDebug()) { logDebug(e.getMessage(), e); } } } } private void setTopicsFromTable() { int itemCount = topicsTable.getItemCount(); ArrayList<String> tableTopics = new ArrayList<>(); for (int rowIndex = 0; rowIndex < itemCount; rowIndex++) { TableItem row = topicsTable.getTable().getItem(rowIndex); String topic = row.getText(1); if (!"".equals(topic) && tableTopics.indexOf(topic) == -1) { tableTopics.add(topic); } } meta.setTopics(tableTopics); } private void setOptionsFromTable() { meta.setConfig(KafkaDialogHelper.getConfig(optionsTable)); } protected String[] getFieldNames() { return Arrays.stream(fieldsTable.getTable().getItems()) .map(row -> row.getText(2)) .toArray(String[]::new); } protected int[] getFieldTypes() { return Arrays.stream(fieldsTable.getTable().getItems()) .mapToInt(row -> ValueMetaFactory.getIdForValueMeta(row.getText(3))) .toArray(); } protected void createNewKafkaPipeline() { PipelineMeta kafkaPipelineMeta = createSubPipelineMeta(); HopDataOrchestrationPerspective doPerspective = HopGui.getDataOrchestrationPerspective(); if (doPerspective == null) { return; } try { // Add a new tab with a new pipeline in the background // doPerspective.addPipeline(hopGui, kafkaPipelineMeta, new HopPipelineFileType()); // Ask the user to save the new pipeline // String filename = hopGui.fileDelegate.fileSaveAs(); if (StringUtils.isNotEmpty(filename)) { // It's hidden in another tab so to make sure, do it asynchronous // HopGui.getInstance().getDisplay().asyncExec(() -> wFilename.setText(filename)); } } catch (Exception e) { new ErrorDialog(shell, "Error", "Error adding new Kafka pipeline", e); } } protected PipelineMeta createSubPipelineMeta() { InjectorMeta injectorMeta = new InjectorMeta(); String[] fieldNames = getFieldNames(); int[] fieldTypes = getFieldTypes(); for (int i = 0; i < fieldNames.length; i++) { InjectorField field = new InjectorField( fieldNames[i], ValueMetaFactory.getValueMetaName(fieldTypes[i]), "", ""); injectorMeta.getInjectorFields().add(field); } TransformMeta recsFromStream = new TransformMeta("RecordsFromStream", "Get messages from Kafka", injectorMeta); recsFromStream.setLocation(new Point(100, 100)); PipelineMeta pipelineMeta = new PipelineMeta(); pipelineMeta.addTransform(recsFromStream); pipelineMeta.setFilename(""); return pipelineMeta; } private PipelineMeta loadKafkaPipelineMeta() throws HopException { KafkaConsumerInputMeta copyMeta = meta.clone(); updateMeta(copyMeta); return TransformWithMappingMeta.loadMappingMeta(copyMeta, getMetadataProvider(), variables); } protected void populateSubTransforms(Event event) { try { String current = wSubTransform.getText(); wSubTransform.removeAll(); ofNullable(loadKafkaPipelineMeta()) .ifPresent( pipelineMeta -> pipelineMeta.getTransforms().stream() .map(TransformMeta::getName) .sorted() .forEach(wSubTransform::add)); // I don't know why but just calling setText does not work when the text is not one of the // items in the list. // Instead the first item in the list is selected. asyncExec solves it. If you have a better // solution, by all // means go ahead and implement // HopGui.getInstance().getDisplay().asyncExec(() -> wSubTransform.setText(current)); } catch (HopException e) { log.logError("Error getting transform names from Kafka pipeline", e); } } private boolean isSelfReferencing() { return variables .resolve(wFilename.getText()) .equals(variables.resolve(pipelineMeta.getFilename())); } }
googleapis/google-cloud-java
37,664
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListEventsRequest.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/streams_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.visionai.v1; /** * * * <pre> * Message for requesting list of Events. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListEventsRequest} */ public final class ListEventsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListEventsRequest) ListEventsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListEventsRequest.newBuilder() to construct. private ListEventsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEventsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; orderBy_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEventsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListEventsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListEventsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListEventsRequest.class, com.google.cloud.visionai.v1.ListEventsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ORDER_BY_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object orderBy_ = ""; /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The orderBy. */ @java.lang.Override public java.lang.String getOrderBy() { java.lang.Object ref = orderBy_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); orderBy_ = s; return s; } } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The bytes for orderBy. */ @java.lang.Override public com.google.protobuf.ByteString getOrderByBytes() { java.lang.Object ref = orderBy_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); orderBy_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.visionai.v1.ListEventsRequest)) { return super.equals(obj); } com.google.cloud.visionai.v1.ListEventsRequest other = (com.google.cloud.visionai.v1.ListEventsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getOrderBy().equals(other.getOrderBy())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (37 * hash) + ORDER_BY_FIELD_NUMBER; hash = (53 * hash) + getOrderBy().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.visionai.v1.ListEventsRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListEventsRequest 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.ListEventsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListEventsRequest 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.ListEventsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListEventsRequest 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.ListEventsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListEventsRequest 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.ListEventsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListEventsRequest 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.ListEventsRequest 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.ListEventsRequest 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.ListEventsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message for requesting list of Events. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListEventsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListEventsRequest) com.google.cloud.visionai.v1.ListEventsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListEventsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListEventsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListEventsRequest.class, com.google.cloud.visionai.v1.ListEventsRequest.Builder.class); } // Construct using com.google.cloud.visionai.v1.ListEventsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; orderBy_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListEventsRequest_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.ListEventsRequest getDefaultInstanceForType() { return com.google.cloud.visionai.v1.ListEventsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.ListEventsRequest build() { com.google.cloud.visionai.v1.ListEventsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.ListEventsRequest buildPartial() { com.google.cloud.visionai.v1.ListEventsRequest result = new com.google.cloud.visionai.v1.ListEventsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.visionai.v1.ListEventsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.orderBy_ = orderBy_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.visionai.v1.ListEventsRequest) { return mergeFrom((com.google.cloud.visionai.v1.ListEventsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.ListEventsRequest other) { if (other == com.google.cloud.visionai.v1.ListEventsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } if (!other.getOrderBy().isEmpty()) { orderBy_ = other.orderBy_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 42: { orderBy_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Parent value for ListEventsRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private java.lang.Object orderBy_ = ""; /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The orderBy. */ public java.lang.String getOrderBy() { java.lang.Object ref = orderBy_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); orderBy_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The bytes for orderBy. */ public com.google.protobuf.ByteString getOrderByBytes() { java.lang.Object ref = orderBy_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); orderBy_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @param value The orderBy to set. * @return This builder for chaining. */ public Builder setOrderBy(java.lang.String value) { if (value == null) { throw new NullPointerException(); } orderBy_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return This builder for chaining. */ public Builder clearOrderBy() { orderBy_ = getDefaultInstance().getOrderBy(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @param value The bytes for orderBy to set. * @return This builder for chaining. */ public Builder setOrderByBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); orderBy_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListEventsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListEventsRequest) private static final com.google.cloud.visionai.v1.ListEventsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListEventsRequest(); } public static com.google.cloud.visionai.v1.ListEventsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEventsRequest> PARSER = new com.google.protobuf.AbstractParser<ListEventsRequest>() { @java.lang.Override public ListEventsRequest 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<ListEventsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEventsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.ListEventsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,664
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListSeriesRequest.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/streams_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.visionai.v1; /** * * * <pre> * Message for requesting list of Series. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListSeriesRequest} */ public final class ListSeriesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListSeriesRequest) ListSeriesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListSeriesRequest.newBuilder() to construct. private ListSeriesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSeriesRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; orderBy_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSeriesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListSeriesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListSeriesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListSeriesRequest.class, com.google.cloud.visionai.v1.ListSeriesRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ORDER_BY_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object orderBy_ = ""; /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The orderBy. */ @java.lang.Override public java.lang.String getOrderBy() { java.lang.Object ref = orderBy_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); orderBy_ = s; return s; } } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The bytes for orderBy. */ @java.lang.Override public com.google.protobuf.ByteString getOrderByBytes() { java.lang.Object ref = orderBy_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); orderBy_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.visionai.v1.ListSeriesRequest)) { return super.equals(obj); } com.google.cloud.visionai.v1.ListSeriesRequest other = (com.google.cloud.visionai.v1.ListSeriesRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getOrderBy().equals(other.getOrderBy())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (37 * hash) + ORDER_BY_FIELD_NUMBER; hash = (53 * hash) + getOrderBy().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.visionai.v1.ListSeriesRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListSeriesRequest 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.ListSeriesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListSeriesRequest 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.ListSeriesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListSeriesRequest 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.ListSeriesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListSeriesRequest 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.ListSeriesRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListSeriesRequest 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.ListSeriesRequest 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.ListSeriesRequest 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.ListSeriesRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message for requesting list of Series. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListSeriesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListSeriesRequest) com.google.cloud.visionai.v1.ListSeriesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListSeriesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListSeriesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListSeriesRequest.class, com.google.cloud.visionai.v1.ListSeriesRequest.Builder.class); } // Construct using com.google.cloud.visionai.v1.ListSeriesRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; orderBy_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.visionai.v1.StreamsServiceProto .internal_static_google_cloud_visionai_v1_ListSeriesRequest_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.ListSeriesRequest getDefaultInstanceForType() { return com.google.cloud.visionai.v1.ListSeriesRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.ListSeriesRequest build() { com.google.cloud.visionai.v1.ListSeriesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.ListSeriesRequest buildPartial() { com.google.cloud.visionai.v1.ListSeriesRequest result = new com.google.cloud.visionai.v1.ListSeriesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.visionai.v1.ListSeriesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.orderBy_ = orderBy_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.visionai.v1.ListSeriesRequest) { return mergeFrom((com.google.cloud.visionai.v1.ListSeriesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.ListSeriesRequest other) { if (other == com.google.cloud.visionai.v1.ListSeriesRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } if (!other.getOrderBy().isEmpty()) { orderBy_ = other.orderBy_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 42: { orderBy_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Parent value for ListSeriesRequest. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Filtering results. * </pre> * * <code>string filter = 4;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private java.lang.Object orderBy_ = ""; /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The orderBy. */ public java.lang.String getOrderBy() { java.lang.Object ref = orderBy_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); orderBy_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return The bytes for orderBy. */ public com.google.protobuf.ByteString getOrderByBytes() { java.lang.Object ref = orderBy_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); orderBy_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @param value The orderBy to set. * @return This builder for chaining. */ public Builder setOrderBy(java.lang.String value) { if (value == null) { throw new NullPointerException(); } orderBy_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @return This builder for chaining. */ public Builder clearOrderBy() { orderBy_ = getDefaultInstance().getOrderBy(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** * * * <pre> * Hint for how to order the results. * </pre> * * <code>string order_by = 5;</code> * * @param value The bytes for orderBy to set. * @return This builder for chaining. */ public Builder setOrderByBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); orderBy_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListSeriesRequest) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListSeriesRequest) private static final com.google.cloud.visionai.v1.ListSeriesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListSeriesRequest(); } public static com.google.cloud.visionai.v1.ListSeriesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSeriesRequest> PARSER = new com.google.protobuf.AbstractParser<ListSeriesRequest>() { @java.lang.Override public ListSeriesRequest 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<ListSeriesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSeriesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.ListSeriesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,998
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/BackendServiceHAPolicyLeader.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.BackendServiceHAPolicyLeader} */ public final class BackendServiceHAPolicyLeader extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.BackendServiceHAPolicyLeader) BackendServiceHAPolicyLeaderOrBuilder { private static final long serialVersionUID = 0L; // Use BackendServiceHAPolicyLeader.newBuilder() to construct. private BackendServiceHAPolicyLeader(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BackendServiceHAPolicyLeader() { backendGroup_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BackendServiceHAPolicyLeader(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceHAPolicyLeader_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceHAPolicyLeader_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.class, com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.Builder.class); } private int bitField0_; public static final int BACKEND_GROUP_FIELD_NUMBER = 457777428; @SuppressWarnings("serial") private volatile java.lang.Object backendGroup_ = ""; /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return Whether the backendGroup field is set. */ @java.lang.Override public boolean hasBackendGroup() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return The backendGroup. */ @java.lang.Override public java.lang.String getBackendGroup() { java.lang.Object ref = backendGroup_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); backendGroup_ = s; return s; } } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return The bytes for backendGroup. */ @java.lang.Override public com.google.protobuf.ByteString getBackendGroupBytes() { java.lang.Object ref = backendGroup_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); backendGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NETWORK_ENDPOINT_FIELD_NUMBER = 56789126; private com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint networkEndpoint_; /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> * * @return Whether the networkEndpoint field is set. */ @java.lang.Override public boolean hasNetworkEndpoint() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> * * @return The networkEndpoint. */ @java.lang.Override public com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint getNetworkEndpoint() { return networkEndpoint_ == null ? com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint .getDefaultInstance() : networkEndpoint_; } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpointOrBuilder getNetworkEndpointOrBuilder() { return networkEndpoint_ == null ? com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint .getDefaultInstance() : networkEndpoint_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(56789126, getNetworkEndpoint()); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 457777428, backendGroup_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(56789126, getNetworkEndpoint()); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(457777428, backendGroup_); } 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.BackendServiceHAPolicyLeader)) { return super.equals(obj); } com.google.cloud.compute.v1.BackendServiceHAPolicyLeader other = (com.google.cloud.compute.v1.BackendServiceHAPolicyLeader) obj; if (hasBackendGroup() != other.hasBackendGroup()) return false; if (hasBackendGroup()) { if (!getBackendGroup().equals(other.getBackendGroup())) return false; } if (hasNetworkEndpoint() != other.hasNetworkEndpoint()) return false; if (hasNetworkEndpoint()) { if (!getNetworkEndpoint().equals(other.getNetworkEndpoint())) 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 (hasBackendGroup()) { hash = (37 * hash) + BACKEND_GROUP_FIELD_NUMBER; hash = (53 * hash) + getBackendGroup().hashCode(); } if (hasNetworkEndpoint()) { hash = (37 * hash) + NETWORK_ENDPOINT_FIELD_NUMBER; hash = (53 * hash) + getNetworkEndpoint().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader 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.BackendServiceHAPolicyLeader} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.BackendServiceHAPolicyLeader) com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceHAPolicyLeader_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceHAPolicyLeader_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.class, com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.Builder.class); } // Construct using com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getNetworkEndpointFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; backendGroup_ = ""; networkEndpoint_ = null; if (networkEndpointBuilder_ != null) { networkEndpointBuilder_.dispose(); networkEndpointBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_BackendServiceHAPolicyLeader_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceHAPolicyLeader getDefaultInstanceForType() { return com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceHAPolicyLeader build() { com.google.cloud.compute.v1.BackendServiceHAPolicyLeader result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceHAPolicyLeader buildPartial() { com.google.cloud.compute.v1.BackendServiceHAPolicyLeader result = new com.google.cloud.compute.v1.BackendServiceHAPolicyLeader(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.BackendServiceHAPolicyLeader result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.backendGroup_ = backendGroup_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.networkEndpoint_ = networkEndpointBuilder_ == null ? networkEndpoint_ : networkEndpointBuilder_.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.compute.v1.BackendServiceHAPolicyLeader) { return mergeFrom((com.google.cloud.compute.v1.BackendServiceHAPolicyLeader) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.BackendServiceHAPolicyLeader other) { if (other == com.google.cloud.compute.v1.BackendServiceHAPolicyLeader.getDefaultInstance()) return this; if (other.hasBackendGroup()) { backendGroup_ = other.backendGroup_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasNetworkEndpoint()) { mergeNetworkEndpoint(other.getNetworkEndpoint()); } 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 454313010: { input.readMessage(getNetworkEndpointFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 454313010 case -632747870: { backendGroup_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case -632747870 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 backendGroup_ = ""; /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return Whether the backendGroup field is set. */ public boolean hasBackendGroup() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return The backendGroup. */ public java.lang.String getBackendGroup() { java.lang.Object ref = backendGroup_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); backendGroup_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return The bytes for backendGroup. */ public com.google.protobuf.ByteString getBackendGroupBytes() { java.lang.Object ref = backendGroup_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); backendGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @param value The backendGroup to set. * @return This builder for chaining. */ public Builder setBackendGroup(java.lang.String value) { if (value == null) { throw new NullPointerException(); } backendGroup_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @return This builder for chaining. */ public Builder clearBackendGroup() { backendGroup_ = getDefaultInstance().getBackendGroup(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * A fully-qualified URL (starting with https://www.googleapis.com/) of the zonal Network Endpoint Group (NEG) with `GCE_VM_IP` endpoints that the leader is attached to. The leader's backendGroup must already be specified as a backend of this backend service. Removing a backend that is designated as the leader's backendGroup is not permitted. * </pre> * * <code>optional string backend_group = 457777428;</code> * * @param value The bytes for backendGroup to set. * @return This builder for chaining. */ public Builder setBackendGroupBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); backendGroup_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint networkEndpoint_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint, com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint.Builder, com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpointOrBuilder> networkEndpointBuilder_; /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> * * @return Whether the networkEndpoint field is set. */ public boolean hasNetworkEndpoint() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> * * @return The networkEndpoint. */ public com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint getNetworkEndpoint() { if (networkEndpointBuilder_ == null) { return networkEndpoint_ == null ? com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint .getDefaultInstance() : networkEndpoint_; } else { return networkEndpointBuilder_.getMessage(); } } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ public Builder setNetworkEndpoint( com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint value) { if (networkEndpointBuilder_ == null) { if (value == null) { throw new NullPointerException(); } networkEndpoint_ = value; } else { networkEndpointBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ public Builder setNetworkEndpoint( com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint.Builder builderForValue) { if (networkEndpointBuilder_ == null) { networkEndpoint_ = builderForValue.build(); } else { networkEndpointBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ public Builder mergeNetworkEndpoint( com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint value) { if (networkEndpointBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && networkEndpoint_ != null && networkEndpoint_ != com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint .getDefaultInstance()) { getNetworkEndpointBuilder().mergeFrom(value); } else { networkEndpoint_ = value; } } else { networkEndpointBuilder_.mergeFrom(value); } if (networkEndpoint_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ public Builder clearNetworkEndpoint() { bitField0_ = (bitField0_ & ~0x00000002); networkEndpoint_ = null; if (networkEndpointBuilder_ != null) { networkEndpointBuilder_.dispose(); networkEndpointBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ public com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint.Builder getNetworkEndpointBuilder() { bitField0_ |= 0x00000002; onChanged(); return getNetworkEndpointFieldBuilder().getBuilder(); } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ public com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpointOrBuilder getNetworkEndpointOrBuilder() { if (networkEndpointBuilder_ != null) { return networkEndpointBuilder_.getMessageOrBuilder(); } else { return networkEndpoint_ == null ? com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint .getDefaultInstance() : networkEndpoint_; } } /** * * * <pre> * The network endpoint within the leader.backendGroup that is designated as the leader. This network endpoint cannot be detached from the NEG specified in the haPolicy.leader.backendGroup until the leader is updated with another network endpoint, or the leader is removed from the haPolicy. * </pre> * * <code> * optional .google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint network_endpoint = 56789126; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint, com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint.Builder, com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpointOrBuilder> getNetworkEndpointFieldBuilder() { if (networkEndpointBuilder_ == null) { networkEndpointBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint, com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpoint.Builder, com.google.cloud.compute.v1.BackendServiceHAPolicyLeaderNetworkEndpointOrBuilder>( getNetworkEndpoint(), getParentForChildren(), isClean()); networkEndpoint_ = null; } return networkEndpointBuilder_; } @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.BackendServiceHAPolicyLeader) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.BackendServiceHAPolicyLeader) private static final com.google.cloud.compute.v1.BackendServiceHAPolicyLeader DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.BackendServiceHAPolicyLeader(); } public static com.google.cloud.compute.v1.BackendServiceHAPolicyLeader getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BackendServiceHAPolicyLeader> PARSER = new com.google.protobuf.AbstractParser<BackendServiceHAPolicyLeader>() { @java.lang.Override public BackendServiceHAPolicyLeader 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<BackendServiceHAPolicyLeader> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BackendServiceHAPolicyLeader> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.BackendServiceHAPolicyLeader getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/grails-core
38,010
grails-spring/src/main/groovy/grails/spring/BeanBuilder.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 grails.spring; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import groovy.lang.Binding; import groovy.lang.Closure; import groovy.lang.GString; import groovy.lang.GroovyObject; import groovy.lang.GroovyObjectSupport; import groovy.lang.GroovyShell; import groovy.lang.MetaClass; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.runtime.InvokerHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.beans.factory.parsing.EmptyReaderEventListener; import org.springframework.beans.factory.parsing.FailFastProblemReporter; import org.springframework.beans.factory.parsing.Location; import org.springframework.beans.factory.parsing.NullSourceExtractor; import org.springframework.beans.factory.parsing.Problem; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver; import org.springframework.beans.factory.xml.NamespaceHandler; import org.springframework.beans.factory.xml.NamespaceHandlerResolver; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.util.Assert; import org.grails.spring.BeanConfiguration; import org.grails.spring.DefaultBeanConfiguration; import org.grails.spring.DefaultRuntimeSpringConfiguration; import org.grails.spring.RuntimeSpringConfiguration; /** * <p>Runtime bean configuration wrapper. Like a Groovy builder, but more of a DSL for * Spring configuration. Allows syntax like:</p> * * <pre> * import org.hibernate.SessionFactory * import org.apache.tomcat.jdbc.pool.DataSource * * BeanBuilder builder = new BeanBuilder() * builder.beans { * dataSource(DataSource) { // invokeMethod * driverClassName = "org.h2.Driver" * url = "jdbc:h2:mem:grailsDB" * username = "sa" // setProperty * password = "" * settings = [mynew:"setting"] * } * sessionFactory(SessionFactory) { * dataSource = dataSource // getProperty for retrieving refs * } * myService(MyService) { * nestedBean = { AnotherBean bean-> // setProperty with closure for nested bean * dataSource = dataSource * } * } * } * </pre> * <p> * You can also use the Spring IO API to load resources containing beans defined as a Groovy * script using either the constructors or the loadBeans(Resource[] resources) method * </p> * * @author Graeme Rocher * @since 0.4 * */ public class BeanBuilder extends GroovyObjectSupport { private static final Log LOG = LogFactory.getLog(BeanBuilder.class); private static final String CREATE_APPCTX = "createApplicationContext"; private static final String REGISTER_BEANS = "registerBeans"; private static final String BEANS = "beans"; private static final String REF = "ref"; private RuntimeSpringConfiguration springConfig; private BeanConfiguration currentBeanConfig; private Map<String, DeferredProperty> deferredProperties = new HashMap<>(); private ApplicationContext parentCtx; private Map<String, Object> binding = Collections.emptyMap(); private ClassLoader classLoader = null; private NamespaceHandlerResolver namespaceHandlerResolver; private Map<String, NamespaceHandler> namespaceHandlers = new HashMap<>(); private XmlBeanDefinitionReader xmlBeanDefinitionReader; private Map<String, String> namespaces = new HashMap<>(); private Resource beanBuildResource = new ByteArrayResource(new byte[0]); private XmlReaderContext readerContext; private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); public BeanBuilder() { this(null, null); } public BeanBuilder(ClassLoader classLoader) { this(null, classLoader); } public BeanBuilder(ApplicationContext parent) { this(parent, null); } public BeanBuilder(ApplicationContext parent, ClassLoader classLoader) { this(parent, null, classLoader); } public BeanBuilder(ApplicationContext parentCtx, RuntimeSpringConfiguration springConfig, ClassLoader classLoader) { this.springConfig = springConfig == null ? createRuntimeSpringConfiguration(parentCtx, classLoader) : springConfig; this.parentCtx = parentCtx; this.classLoader = classLoader; initializeSpringConfig(); } public void setResourcePatternResolver(ResourcePatternResolver resourcePatternResolver) { Assert.notNull(resourcePatternResolver, "The argument [resourcePatternResolver] cannot be null"); this.resourcePatternResolver = resourcePatternResolver; } protected void initializeSpringConfig() { xmlBeanDefinitionReader = new XmlBeanDefinitionReader((GenericApplicationContext) springConfig.getUnrefreshedApplicationContext()); initializeBeanBuilderForClassLoader(classLoader); } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader == null ? getClass().getClassLoader() : classLoader; initializeBeanBuilderForClassLoader(classLoader); } protected void initializeBeanBuilderForClassLoader(ClassLoader classLoader) { xmlBeanDefinitionReader.setBeanClassLoader(classLoader); namespaceHandlerResolver = new DefaultNamespaceHandlerResolver(this.classLoader); readerContext = new XmlReaderContext(beanBuildResource, new FailFastProblemReporter(), new EmptyReaderEventListener(), new NullSourceExtractor(), xmlBeanDefinitionReader, namespaceHandlerResolver); } public void setNamespaceHandlerResolver(NamespaceHandlerResolver namespaceHandlerResolver) { this.namespaceHandlerResolver = namespaceHandlerResolver; } protected RuntimeSpringConfiguration createRuntimeSpringConfiguration(ApplicationContext parent, ClassLoader cl) { return new DefaultRuntimeSpringConfiguration(parent, cl); } public Log getLog() { return LOG; } /** * Imports Spring bean definitions from either XML or Groovy sources into the current bean builder instance * * @param resourcePattern The resource pattern */ public void importBeans(String resourcePattern) { try { Resource[] resources = resourcePatternResolver.getResources(resourcePattern); for (Resource resource : resources) { importBeans(resource); } } catch (IOException e) { LOG.error("Error loading beans for resource pattern: " + resourcePattern, e); } } public void importBeans(Resource resource) { if (resource.getFilename().endsWith(".groovy")) { loadBeans(resource); } else if (resource.getFilename().endsWith(".xml")) { SimpleBeanDefinitionRegistry beanRegistry = new SimpleBeanDefinitionRegistry(); XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(beanRegistry); beanReader.loadBeanDefinitions(resource); String[] beanNames = beanRegistry.getBeanDefinitionNames(); for (String beanName : beanNames) { springConfig.addBeanDefinition(beanName, beanRegistry.getBeanDefinition(beanName)); } } } /** * Defines a Spring namespace definition to use. * * @param definition The definition */ public void xmlns(Map<String, String> definition) { Assert.notNull(namespaceHandlerResolver, "You cannot define a Spring namespace without a [namespaceHandlerResolver] set"); if (definition.isEmpty()) { return; } for (Map.Entry<String, String> entry : definition.entrySet()) { String namespace = entry.getKey(); String uri = entry.getValue() == null ? null : entry.getValue(); Assert.notNull(uri, "Namespace definition cannot supply a null URI"); final NamespaceHandler namespaceHandler = namespaceHandlerResolver.resolve(uri); if (namespaceHandler == null) { throw new BeanDefinitionParsingException( new Problem("No namespace handler found for URI: " + uri, new Location(readerContext.getResource()))); } namespaceHandlers.put(namespace, namespaceHandler); namespaces.put(namespace, uri); } } /** * Retrieves the parent ApplicationContext * @return The parent ApplicationContext */ public ApplicationContext getParentCtx() { return parentCtx; } /** * Retrieves the RuntimeSpringConfiguration instance used the the BeanBuilder * @return The RuntimeSpringConfiguration instance */ public RuntimeSpringConfiguration getSpringConfig() { return springConfig; } /** * Retrieves a BeanDefinition for the given name * @param name The bean definition * @return The BeanDefinition instance */ public BeanDefinition getBeanDefinition(String name) { if (!getSpringConfig().containsBean(name)) { return null; } return getSpringConfig().getBeanConfig(name).getBeanDefinition(); } /** * Retrieves all BeanDefinitions for this BeanBuilder * * @return A map of BeanDefinition instances with the bean id as the key */ public Map<String, BeanDefinition> getBeanDefinitions() { Map<String, BeanDefinition> beanDefinitions = new HashMap<>(); for (String beanName : getSpringConfig().getBeanNames()) { beanDefinitions.put(beanName, getSpringConfig().getBeanConfig(beanName).getBeanDefinition()); } return beanDefinitions; } /** * Sets the runtime Spring configuration instance to use. This is not necessary to set * and is configured to default value if not, but is useful for integrating with other * spring configuration mechanisms @see org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator * * @param springConfig The spring config */ public void setSpringConfig(RuntimeSpringConfiguration springConfig) { this.springConfig = springConfig; initializeSpringConfig(); } /** * Defers the adding of a property to a bean definition until later. * This is for a case where you assign a property to a list that may not contain bean references at * that point of asignment, but may later hence it would need to be managed * * @author Graeme Rocher */ private class DeferredProperty { private BeanConfiguration config; private String name; private Object value; DeferredProperty(BeanConfiguration config, String name, Object value) { this.config = config; this.name = name; this.value = value; } public void setInBeanConfig() { config.addProperty(name, value); } } /** * Adds new properties to runtime references. * * @author Graeme Rocher * @since 0.4 */ private class ConfigurableRuntimeBeanReference extends RuntimeBeanReference implements GroovyObject { private MetaClass metaClass; private BeanConfiguration beanConfig; public ConfigurableRuntimeBeanReference(String beanName, BeanConfiguration beanConfig, boolean toParent) { super(beanName, toParent); Assert.notNull(beanConfig, "Argument [beanConfig] cannot be null"); this.beanConfig = beanConfig; metaClass = InvokerHelper.getMetaClass(this); } public MetaClass getMetaClass() { return metaClass; } public Object getProperty(String property) { if (property.equals("beanName")) { return getBeanName(); } if (property.equals("source")) { return getSource(); } if (beanConfig != null) { return new WrappedPropertyValue(property, beanConfig.getPropertyValue(property)); } return metaClass.getProperty(this, property); } /** * Wraps a BeanConfiguration property an ensures that any RuntimeReference additions to it are * deferred for resolution later. */ private class WrappedPropertyValue extends GroovyObjectSupport { private Object propertyValue; private String propertyName; public WrappedPropertyValue(String propertyName, Object propertyValue) { this.propertyValue = propertyValue; this.propertyName = propertyName; } @SuppressWarnings("unused") public void leftShift(Object value) { InvokerHelper.invokeMethod(propertyValue, "leftShift", value); updateDeferredProperties(value); } @SuppressWarnings("unused") public boolean add(Object value) { boolean retval = (Boolean) InvokerHelper.invokeMethod(propertyValue, "add", value); updateDeferredProperties(value); return retval; } @SuppressWarnings("unused") public boolean addAll(@SuppressWarnings("rawtypes") Collection values) { boolean retval = (Boolean) InvokerHelper.invokeMethod(propertyValue, "addAll", values); for (Object value : values) { updateDeferredProperties(value); } return retval; } @Override public Object invokeMethod(String name, Object args) { return InvokerHelper.invokeMethod(propertyValue, name, args); } @Override public Object getProperty(String name) { return InvokerHelper.getProperty(propertyValue, name); } @Override public void setProperty(String name, Object value) { InvokerHelper.setProperty(propertyValue, name, value); } private void updateDeferredProperties(Object value) { if (value instanceof RuntimeBeanReference) { deferredProperties.put(beanConfig.getName(), new DeferredProperty(beanConfig, propertyName, propertyValue)); } } } public Object invokeMethod(String name, Object args) { return metaClass.invokeMethod(this, name, args); } public void setMetaClass(MetaClass metaClass) { this.metaClass = metaClass; } public void setProperty(String property, Object newValue) { if (!addToDeferred(beanConfig, property, newValue)) { beanConfig.setPropertyValue(property, newValue); } } } /** * Takes a resource pattern as (@see org.springframework.core.io.support.PathMatchingResourcePatternResolver) * This allows you load multiple bean resources in this single builder * * eg loadBeans("classpath:*Beans.groovy") * * @param resourcePattern The resource pattern * @throws IOException When the path cannot be matched */ public void loadBeans(String resourcePattern) throws IOException { loadBeans(new PathMatchingResourcePatternResolver().getResources(resourcePattern)); } /** * Loads a single Resource into the bean builder * * @param resource The resource to load */ public void loadBeans(Resource resource) { beanBuildResource = resource; loadBeans(new Resource[]{resource}); } /** * Loads a set of given beans. * @param resources The resources to load * @throws BeanDefinitionParsingException Thrown if there is an error reading one of the passes resources */ public void loadBeans(Resource[] resources) { @SuppressWarnings("rawtypes") Closure beans = new Closure(this) { private static final long serialVersionUID = -2778328821635253740L; @Override public Object call(Object... args) { invokeBeanDefiningClosure((Closure) args[0]); return null; } }; Binding b = new Binding() { @Override public void setVariable(String name, Object value) { if (currentBeanConfig == null) { super.setVariable(name, value); } else { setPropertyOnBeanConfig(name, value); } } }; b.setVariable("beans", beans); for (Resource resource : resources) { try { GroovyShell shell = classLoader == null ? new GroovyShell(b) : new GroovyShell(classLoader, b); shell.evaluate(new InputStreamReader(resource.getInputStream(), "UTF-8")); } catch (Throwable e) { throw new BeanDefinitionParsingException( new Problem("Error evaluating bean definition script: " + e.getMessage(), new Location(resource), null, e)); } } } /** * Register a set of beans with the given bean registry. Most * application contexts are bean registries. */ public void registerBeans(BeanDefinitionRegistry registry) { finalizeDeferredProperties(); if (registry instanceof GenericApplicationContext) { GenericApplicationContext ctx = (GenericApplicationContext) registry; ctx.setClassLoader(classLoader); ctx.getBeanFactory().setBeanClassLoader(classLoader); } springConfig.registerBeansWithRegistry(registry); } /** * Registers bean definitions with another instance of RuntimeSpringConfiguration, overriding any beans in the target. * * @param targetSpringConfig The RuntimeSpringConfiguration object */ public void registerBeans(RuntimeSpringConfiguration targetSpringConfig) { springConfig.registerBeansWithConfig(targetSpringConfig); } /** * Overrides method invocation to create beans for each method name that takes a class argument. */ @Override public Object invokeMethod(String name, Object arg) { Object[] args = (Object[]) arg; if (CREATE_APPCTX.equals(name)) { return createApplicationContext(); } if (REGISTER_BEANS.equals(name) && args.length == 1 && args[0] instanceof GenericApplicationContext) { registerBeans((GenericApplicationContext) args[0]); return null; } if (BEANS.equals(name) && args.length == 1 && args[0] instanceof Closure) { return beans((Closure<?>) args[0]); } if (REF.equals(name)) { String refName; Assert.notNull(args[0], "Argument to ref() is not a valid bean or was not found"); if (args[0] instanceof RuntimeBeanReference) { refName = ((RuntimeBeanReference) args[0]).getBeanName(); } else { refName = args[0].toString(); } boolean parentRef = false; if (args.length > 1) { if (args[1] instanceof Boolean) { parentRef = (Boolean) args[1]; } } return new RuntimeBeanReference(refName, parentRef); } if (namespaceHandlers.containsKey(name) && args.length > 0 && (args[0] instanceof Closure)) { createDynamicElementReader(name, true).invokeMethod("doCall", args); return this; } if (args.length > 0 && args[0] instanceof Closure) { // abstract bean definition return invokeBeanDefiningMethod(name, args); } if (args.length > 0 && args[0] instanceof Class || args.length > 0 && args[0] instanceof RuntimeBeanReference || args.length > 0 && args[0] instanceof Map) { return invokeBeanDefiningMethod(name, args); } if (args.length > 1 && args[args.length - 1] instanceof Closure) { return invokeBeanDefiningMethod(name, args); } ApplicationContext ctx = springConfig.getUnrefreshedApplicationContext(); MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx); if (!mc.respondsTo(ctx, name, args).isEmpty()) { return mc.invokeMethod(ctx, name, args); } return this; } /** * Defines a set of beans for the given block or closure. * * @param c The block or closure * @return This BeanBuilder instance */ public BeanBuilder beans(Closure<?> c) { return invokeBeanDefiningClosure(c); } /** * Creates an ApplicationContext from the current state of the BeanBuilder * @return The ApplicationContext instance */ public ApplicationContext createApplicationContext() { finalizeDeferredProperties(); return springConfig.getApplicationContext(); } protected void finalizeDeferredProperties() { for (DeferredProperty dp : deferredProperties.values()) { if (dp.value instanceof List) { dp.value = manageListIfNecessary(dp.value); } else if (dp.value instanceof Map) { dp.value = manageMapIfNecessary(dp.value); } dp.setInBeanConfig(); } deferredProperties.clear(); } protected boolean addToDeferred(BeanConfiguration beanConfig, String property, Object newValue) { if (newValue instanceof List) { deferredProperties.put(currentBeanConfig.getName() + property, new DeferredProperty(currentBeanConfig, property, newValue)); return true; } if (newValue instanceof Map) { deferredProperties.put(currentBeanConfig.getName() + property, new DeferredProperty(currentBeanConfig, property, newValue)); return true; } return false; } /** * Called when a bean definition node is called. * * @param name The name of the bean to define * @param args The arguments to the bean. The first argument is the class name, the last argument is sometimes a closure. All * the arguments in between are constructor arguments * @return The bean configuration instance */ protected BeanConfiguration invokeBeanDefiningMethod(String name, Object[] args) { boolean hasClosureArgument = args[args.length - 1] instanceof Closure; if (args[0] instanceof Class) { Class<?> beanClass = args[0] instanceof Class ? (Class<?>) args[0] : args[0].getClass(); if (args.length >= 1) { if (hasClosureArgument) { if (args.length - 1 != 1) { currentBeanConfig = springConfig.addSingletonBean(name, beanClass, resolveConstructorArguments(args, 1, args.length - 1)); } else { currentBeanConfig = springConfig.addSingletonBean(name, beanClass); } } else { currentBeanConfig = springConfig.addSingletonBean(name, beanClass, resolveConstructorArguments(args, 1, args.length)); } } } else if (args[0] instanceof RuntimeBeanReference) { currentBeanConfig = springConfig.addSingletonBean(name); currentBeanConfig.setFactoryBean(((RuntimeBeanReference) args[0]).getBeanName()); } else if (args[0] instanceof Map) { // named constructor arguments if (args.length > 1 && args[1] instanceof Class) { List<?> constructorArgs = resolveConstructorArguments(args, 2, hasClosureArgument ? args.length - 1 : args.length); currentBeanConfig = springConfig.addSingletonBean(name, (Class<?>) args[1], constructorArgs); @SuppressWarnings("rawtypes") Map namedArgs = (Map) args[0]; for (Object o : namedArgs.keySet()) { String propName = (String) o; setProperty(propName, namedArgs.get(propName)); } } // factory method syntax else { //First arg is the map containing factoryBean : factoryMethod @SuppressWarnings("rawtypes") Map.Entry factoryBeanEntry = (Map.Entry) ((Map) args[0]).entrySet().iterator().next(); // If we have a closure body, that will be the last argument. // In between are the constructor args int constructorArgsTest = hasClosureArgument ? 2 : 1; // If we have more than this number of args, we have constructor args if (args.length > constructorArgsTest) { //factory-method requires args int endOfConstructArgs = hasClosureArgument ? args.length - 1 : args.length; currentBeanConfig = springConfig.addSingletonBean(name, null, resolveConstructorArguments(args, 1, endOfConstructArgs)); } else { currentBeanConfig = springConfig.addSingletonBean(name); } currentBeanConfig.setFactoryBean(factoryBeanEntry.getKey().toString()); currentBeanConfig.setFactoryMethod(factoryBeanEntry.getValue().toString()); } } else if (args[0] instanceof Closure) { currentBeanConfig = springConfig.addAbstractBean(name); } else { List<?> constructorArgs = resolveConstructorArguments(args, 0, hasClosureArgument ? args.length - 1 : args.length); currentBeanConfig = new DefaultBeanConfiguration(name, null, constructorArgs); springConfig.addBeanConfiguration(name, currentBeanConfig); } if (hasClosureArgument) { Closure<?> callable = (Closure<?>) args[args.length - 1]; callable.setDelegate(this); callable.setResolveStrategy(Closure.DELEGATE_FIRST); callable.call(new Object[]{currentBeanConfig}); } BeanConfiguration beanConfig = currentBeanConfig; currentBeanConfig = null; return beanConfig; } @SuppressWarnings("rawtypes") protected List resolveConstructorArguments(Object[] args, int start, int end) { Object[] constructorArgs = subarray(args, start, end); filterGStringReferences(constructorArgs); for (int i = 0; i < constructorArgs.length; i++) { if (constructorArgs[i] instanceof List) { constructorArgs[i] = manageListIfNecessary(constructorArgs[i]); } else if (constructorArgs[i] instanceof Map) { constructorArgs[i] = manageMapIfNecessary(constructorArgs[i]); } } return Arrays.asList(constructorArgs); } protected Object[] subarray(Object[] args, int i, int j) { Assert.isTrue(j <= args.length, "Upper bound can't be greater than array length"); Object[] b = new Object[j - i]; int n = 0; for (int k = i; k < j; k++, n++) { b[n] = args[k]; } return b; } protected void filterGStringReferences(Object[] constructorArgs) { for (int i = 0; i < constructorArgs.length; i++) { Object constructorArg = constructorArgs[i]; if (constructorArg instanceof GString) { constructorArgs[i] = constructorArg.toString(); } } } /** * When an method's argument is only a closure it is a set of bean definitions. * * @param callable The closure argument * @return This BeanBuilder instance */ protected BeanBuilder invokeBeanDefiningClosure(Closure<?> callable) { callable.setDelegate(this); // callable.setResolveStrategy(Closure.DELEGATE_FIRST); callable.call(); finalizeDeferredProperties(); return this; } /** * Overrides property setting in the scope of the BeanBuilder to set * properties on the current BeanConfiguration. */ @Override public void setProperty(String name, Object value) { if (currentBeanConfig != null) { setPropertyOnBeanConfig(name, value); } } /** * Defines an inner bean definition. * * @param type The bean type * @return The bean definition */ public AbstractBeanDefinition bean(Class<?> type) { return springConfig.createSingletonBean(type).getBeanDefinition(); } /** * Defines an inner bean definition. * * @param type The bean type * @param args The constructors arguments and closure configurer * @return The bean definition */ @SuppressWarnings("rawtypes") public AbstractBeanDefinition bean(Class type, Object... args) { BeanConfiguration current = currentBeanConfig; try { Closure callable = null; Collection constructorArgs = null; if (args != null && args.length > 0) { int index = args.length; Object lastArg = args[index - 1]; if (lastArg instanceof Closure) { callable = (Closure) lastArg; index--; } if (index > -1) { constructorArgs = resolveConstructorArguments(args, 0, index); } } currentBeanConfig = constructorArgs == null ? springConfig.createSingletonBean(type) : springConfig.createSingletonBean(type, constructorArgs); if (callable != null) { callable.call(new Object[]{currentBeanConfig}); } return currentBeanConfig.getBeanDefinition(); } finally { currentBeanConfig = current; } } protected void setPropertyOnBeanConfig(String name, Object value) { if (value instanceof GString) { value = value.toString(); } if (addToDeferred(currentBeanConfig, name, value)) { return; } if (value instanceof Closure) { BeanConfiguration current = currentBeanConfig; try { Closure<?> callable = (Closure<?>) value; Class<?> parameterType = callable.getParameterTypes()[0]; if (parameterType.equals(Object.class)) { currentBeanConfig = springConfig.createSingletonBean(""); callable.call(new Object[]{currentBeanConfig}); } else { currentBeanConfig = springConfig.createSingletonBean(parameterType); callable.call(); } value = currentBeanConfig.getBeanDefinition(); } finally { currentBeanConfig = current; } } currentBeanConfig.addProperty(name, value); } /** * Checks whether there are any runtime refs inside a Map and converts * it to a ManagedMap if necessary. * * @param value The current map * @return A ManagedMap or a normal map */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Object manageMapIfNecessary(Object value) { Map map = (Map) value; boolean containsRuntimeRefs = false; for (Object e : map.values()) { if (e instanceof RuntimeBeanReference) { containsRuntimeRefs = true; break; } } if (containsRuntimeRefs) { Map managedMap = new ManagedMap(); managedMap.putAll(map); return managedMap; } return value; } /** * Checks whether there are any runtime refs inside the list and * converts it to a ManagedList if necessary. * * @param value The object that represents the list * @return Either a new list or a managed one */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Object manageListIfNecessary(Object value) { List list = (List) value; boolean containsRuntimeRefs = false; for (Object e : list) { if (e instanceof RuntimeBeanReference) { containsRuntimeRefs = true; break; } } if (containsRuntimeRefs) { List tmp = new ManagedList(); tmp.addAll((List) value); value = tmp; } return value; } /** * Overrides property retrieval in the scope of the BeanBuilder to either: * * a) Retrieve a variable from the bean builder's binding if it exists * b) Retrieve a RuntimeBeanReference for a specific bean if it exists * c) Otherwise just delegate to super.getProperty which will resolve properties from the BeanBuilder itself */ @Override public Object getProperty(String name) { if (binding.containsKey(name)) { return binding.get(name); } if (namespaceHandlers.containsKey(name)) { return createDynamicElementReader(name, currentBeanConfig != null); } if (springConfig.containsBean(name)) { BeanConfiguration beanConfig = springConfig.getBeanConfig(name); if (beanConfig != null) { return new ConfigurableRuntimeBeanReference(name, springConfig.getBeanConfig(name), false); } return new RuntimeBeanReference(name, false); } // this is to deal with the case where the property setter is the last // statement in a closure (hence the return value) if (currentBeanConfig != null) { if (currentBeanConfig.hasProperty(name)) { return currentBeanConfig.getPropertyValue(name); } DeferredProperty dp = deferredProperties.get(currentBeanConfig.getName() + name); if (dp != null) { return dp.value; } return super.getProperty(name); } return super.getProperty(name); } protected DynamicElementReader createDynamicElementReader(String namespace, final boolean decorator) { NamespaceHandler handler = namespaceHandlers.get(namespace); ParserContext parserContext = new ParserContext(readerContext, new BeanDefinitionParserDelegate(readerContext)); final DynamicElementReader dynamicElementReader = new DynamicElementReader(namespace, namespaces, handler, parserContext) { @Override protected void afterInvocation() { if (!decorator) { currentBeanConfig = null; } } }; dynamicElementReader.setClassLoader(classLoader); if (currentBeanConfig != null) { dynamicElementReader.setBeanConfiguration(currentBeanConfig); } else if (!decorator) { currentBeanConfig = new DefaultBeanConfiguration(namespace); dynamicElementReader.setBeanConfiguration(currentBeanConfig); } dynamicElementReader.setBeanDecorator(decorator); return dynamicElementReader; } /** * Sets the binding (the variables available in the scope of the BeanBuilder). * @param b The Binding instance */ @SuppressWarnings("unchecked") public void setBinding(Binding b) { binding = b.getVariables(); } }
apache/myfaces
37,867
impl/src/main/java/org/apache/myfaces/view/facelets/impl/FaceletCompositionContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.view.facelets.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import jakarta.faces.FactoryFinder; import jakarta.faces.component.UIComponent; import jakarta.faces.component.UIViewRoot; import jakarta.faces.component.UniqueIdVendor; import jakarta.faces.component.visit.VisitContextFactory; import jakarta.faces.context.FacesContext; import jakarta.faces.view.AttachedObjectHandler; import jakarta.faces.view.EditableValueHolderAttachedObjectHandler; import org.apache.myfaces.config.webparameters.MyfacesConfig; import org.apache.myfaces.util.lang.Lazy; import org.apache.myfaces.view.facelets.ELExpressionCacheMode; import org.apache.myfaces.view.facelets.FaceletCompositionContext; import org.apache.myfaces.view.facelets.FaceletFactory; import org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage; import org.apache.myfaces.view.facelets.tag.faces.ComponentSupport; /** * @since 2.0.1 * @author Leonardo Uribe (latest modification by $Author$) * @version $Revision$ $Date$ */ public class FaceletCompositionContextImpl extends FaceletCompositionContext { public static final String JAKARTA_FACES_LOCATION_PREFIX = "jakarta_faces_location_"; private static final String VISIT_CONTEXT_FACTORY = "oam.vf.VisitContextFactory"; private FacesContext _facesContext; private FaceletFactory _factory; private LinkedList<UIComponent> _compositeComponentStack; private LinkedList<UniqueIdVendor> _uniqueIdVendorStack; private LinkedList<Map.Entry<String, EditableValueHolderAttachedObjectHandler>> _enclosingValidatorIdsStack; private Boolean _isRefreshingTransientBuild; private Boolean _isMarkInitialState; private Boolean _isBuildingViewMetadata; private Boolean _refreshTransientBuildOnPSS; private Boolean _usingPSSOnThisView; private List<Map<String, UIComponent>> _componentsMarkedForDeletion; private Map<String, UIComponent> _relocatableResourceForDeletion; private int _deletionLevel; private Map<UIComponent, List<AttachedObjectHandler>> _attachedObjectHandlers; private Map<UIComponent, Map<String, Object>> _methodExpressionsTargeted; private Map<UIComponent, Map<String, Boolean>> _compositeComponentAttributesMarked; private static final String VIEWROOT_FACELET_ID = "oam.VIEW_ROOT"; private Lazy<SectionUniqueIdCounter> _sectionUniqueIdCounter; private Lazy<SectionUniqueIdCounter> _sectionUniqueComponentIdCounter; private List<String> _uniqueIdsList; private Iterator<String> _uniqueIdsIterator; private int _level; private int _isInMetadataSection; private Lazy<SectionUniqueIdCounter> _sectionUniqueMetadataIdCounter; private Lazy<SectionUniqueIdCounter> _sectionUniqueNormalIdCounter; private Lazy<SectionUniqueIdCounter> _sectionUniqueComponentMetadataIdCounter; private Lazy<SectionUniqueIdCounter> _sectionUniqueComponentNormalIdCounter; private List<SectionUniqueIdCounter> _sectionUniqueIdCounterStack; private List<SectionUniqueIdCounter> _sectionUniqueComponentIdCounterStack; private StringBuilder _sharedStringBuilder; private int _ccLevel; private boolean _dynamicComponentHandler; private boolean _oldRefreshingTransientBuild; private boolean _dynamicComponentTopLevel; private int _dynamicComponentSection = 0; private List<Integer> _dynamicOldDeletionLevel; private VisitContextFactory _visitContextFactory = null; private UIViewRoot _viewRoot = null; private MyfacesConfig myfacesConfig; public FaceletCompositionContextImpl(FaceletFactory factory, FacesContext facesContext) { super(); _factory = factory; _facesContext = facesContext; _componentsMarkedForDeletion = new ArrayList<>(); _relocatableResourceForDeletion = new HashMap<>(); _deletionLevel = -1; _sectionUniqueIdCounter = new Lazy(() -> new SectionUniqueIdCounter()); //Cached at facelet view myfacesConfig = MyfacesConfig.getCurrentInstance(facesContext); if (myfacesConfig.getComponentUniqueIdsCacheSize() > 0) { String[] componentIdsCache = (String[]) facesContext.getExternalContext(). getApplicationMap().get(FaceletViewDeclarationLanguage.CACHED_COMPONENT_IDS); if (componentIdsCache != null) { _sectionUniqueComponentIdCounter = new Lazy(() -> new SectionUniqueIdCounter("_", componentIdsCache)); } else { _sectionUniqueComponentIdCounter = new Lazy(() -> new SectionUniqueIdCounter("_")); } } else { _sectionUniqueComponentIdCounter = new Lazy(() -> new SectionUniqueIdCounter("_")); } _sectionUniqueNormalIdCounter = _sectionUniqueIdCounter; _sectionUniqueComponentNormalIdCounter = _sectionUniqueComponentIdCounter; _uniqueIdsList = null; _uniqueIdsIterator = null; _level = 0; _isInMetadataSection = 0; _sharedStringBuilder = null; _ccLevel = 0; _viewRoot = null; } /** * This constructor is intended for places where the id generation strategy needs to be changed * adding a unique base id, like for example on a dynamic component creation. * * @param factory * @param facesContext * @param base */ public FaceletCompositionContextImpl(FaceletFactory factory, FacesContext facesContext, String base) { this(factory, facesContext); _sectionUniqueIdCounter = new Lazy(() -> new SectionUniqueIdCounter(base+ '_')); _sectionUniqueComponentIdCounter = new Lazy(() -> new SectionUniqueIdCounter('_' + base + '_')); _sectionUniqueNormalIdCounter = _sectionUniqueIdCounter; _sectionUniqueComponentNormalIdCounter = _sectionUniqueComponentIdCounter; _dynamicComponentTopLevel = true; _dynamicComponentSection = 1; } @Override public void setUniqueIdsIterator(Iterator<String> uniqueIdsIterator) { _uniqueIdsList = null; _uniqueIdsIterator = uniqueIdsIterator; } @Override public void initUniqueIdRecording() { _uniqueIdsList = new LinkedList<>(); _uniqueIdsIterator = null; } @Override public void addUniqueId(String uniqueId) { if (_uniqueIdsList != null && _level == 0 && !(_isInMetadataSection > 0) && !(_dynamicComponentSection > 0)) { _uniqueIdsList.add(uniqueId); } } @Override public String getUniqueIdFromIterator() { if (_uniqueIdsIterator != null && _uniqueIdsIterator.hasNext() && _level == 0 && !(_isInMetadataSection > 0) && !(_dynamicComponentSection > 0)) { return _uniqueIdsIterator.next(); } return null; } @Override public List<String> getUniqueIdList() { return _uniqueIdsList; } @Override public FaceletFactory getFaceletFactory() { return _factory; } @Override public void release(FacesContext facesContext) { super.release(facesContext); _factory = null; _facesContext = null; _compositeComponentStack = null; _enclosingValidatorIdsStack = null; _uniqueIdVendorStack = null; _componentsMarkedForDeletion = null; _relocatableResourceForDeletion = null; _sectionUniqueIdCounter = null; _sectionUniqueNormalIdCounter = null; _sectionUniqueMetadataIdCounter = null; _sectionUniqueComponentIdCounter = null; _sectionUniqueComponentNormalIdCounter = null; _sectionUniqueComponentMetadataIdCounter = null; _sharedStringBuilder = null; _visitContextFactory = null; _dynamicOldDeletionLevel = null; _viewRoot = null; } @Override public UIComponent getCompositeComponentFromStack() { if (_compositeComponentStack != null && !_compositeComponentStack.isEmpty()) { return _compositeComponentStack.peek(); } return null; } @Override public void pushCompositeComponentToStack(UIComponent parent) { if (_compositeComponentStack == null) { _compositeComponentStack = new LinkedList<>(); } _compositeComponentStack.addFirst(parent); _ccLevel++; } @Override public void popCompositeComponentToStack() { if (_compositeComponentStack != null && !_compositeComponentStack.isEmpty()) { _compositeComponentStack.removeFirst(); } _ccLevel--; } @Override public int getCompositeComponentLevel() { return _ccLevel; } @Override public UniqueIdVendor getUniqueIdVendorFromStack() { if (_uniqueIdVendorStack != null && !_uniqueIdVendorStack.isEmpty()) { return _uniqueIdVendorStack.peek(); } return null; } @Override public void popUniqueIdVendorToStack() { if (_uniqueIdVendorStack != null && !_uniqueIdVendorStack.isEmpty()) { _uniqueIdVendorStack.removeFirst(); } } @Override public void pushUniqueIdVendorToStack(UniqueIdVendor parent) { if (_uniqueIdVendorStack == null) { _uniqueIdVendorStack = new LinkedList<>(); } _uniqueIdVendorStack.addFirst(parent); } /** * Removes top of stack. * @since 2.0 */ @Override public void popEnclosingValidatorIdToStack() { if (_enclosingValidatorIdsStack != null && !_enclosingValidatorIdsStack.isEmpty()) { _enclosingValidatorIdsStack.removeFirst(); } } @Override public void pushEnclosingValidatorIdToStack(String validatorId, EditableValueHolderAttachedObjectHandler attachedObjectHandler) { if (_enclosingValidatorIdsStack == null) { _enclosingValidatorIdsStack = new LinkedList<>(); } _enclosingValidatorIdsStack.addFirst(new SimpleEntry<>(validatorId, attachedObjectHandler)); } public Iterator<Map.Entry<String, EditableValueHolderAttachedObjectHandler>> getEnclosingValidatorIdsAndHandlers() { if (_enclosingValidatorIdsStack != null && !_enclosingValidatorIdsStack.isEmpty()) { return _enclosingValidatorIdsStack.iterator(); } return null; } @Override public boolean containsEnclosingValidatorId(String id) { if (_enclosingValidatorIdsStack != null && !_enclosingValidatorIdsStack.isEmpty()) { for (Map.Entry<String, EditableValueHolderAttachedObjectHandler> entry : _enclosingValidatorIdsStack) { if (entry.getKey().equals(id)) { return true; } } } return false; } @Override public boolean isRefreshingTransientBuild() { if (_isRefreshingTransientBuild == null) { _isRefreshingTransientBuild = FaceletViewDeclarationLanguage.isRefreshingTransientBuild(_facesContext); } return _isRefreshingTransientBuild; } @Override public boolean isMarkInitialState() { if (_isMarkInitialState == null) { _isMarkInitialState = FaceletViewDeclarationLanguage.isMarkInitialState(_facesContext); } return _isMarkInitialState; } @Override public void setMarkInitialState(boolean value) { _isMarkInitialState = value; } @Override public boolean isRefreshTransientBuildOnPSS() { if (_refreshTransientBuildOnPSS == null) { _refreshTransientBuildOnPSS = FaceletViewDeclarationLanguage. isRefreshTransientBuildOnPSS(_facesContext); } return _refreshTransientBuildOnPSS; } @Override public boolean isRefreshTransientBuildOnPSSPreserveState() { return myfacesConfig.isRefreshTransientBuildOnPSSPreserveState(); } @Override public boolean isBuildingViewMetadata() { if (_isBuildingViewMetadata == null) { _isBuildingViewMetadata = FaceletViewDeclarationLanguage.isBuildingViewMetadata(_facesContext); } return _isBuildingViewMetadata; } @Override public boolean isUsingPSSOnThisView() { if (_usingPSSOnThisView == null) { _usingPSSOnThisView = FaceletViewDeclarationLanguage.isUsingPSSOnThisView(_facesContext); } return _usingPSSOnThisView; } @Override public boolean isMarkInitialStateAndIsRefreshTransientBuildOnPSS() { return isMarkInitialState() && isRefreshTransientBuildOnPSS(); } @Override public ELExpressionCacheMode getELExpressionCacheMode() { return myfacesConfig.getELExpressionCacheMode(); } @Override public boolean isWrapTagExceptionsAsContextAware() { return myfacesConfig.isWrapTagExceptionsAsContextAware(); } @Override public void addAttachedObjectHandler(UIComponent compositeComponentParent, AttachedObjectHandler handler) { List<AttachedObjectHandler> list = null; if (_attachedObjectHandlers == null) { _attachedObjectHandlers = new HashMap<>(); } else { list = _attachedObjectHandlers.get(compositeComponentParent); } if (list == null) { list = new ArrayList<>(); _attachedObjectHandlers.put(compositeComponentParent, list); } list.add(handler); } @Override public void removeAttachedObjectHandlers(UIComponent compositeComponentParent) { if (_attachedObjectHandlers == null) { return; } _attachedObjectHandlers.remove(compositeComponentParent); } @Override public List<AttachedObjectHandler> getAttachedObjectHandlers(UIComponent compositeComponentParent) { if (_attachedObjectHandlers == null) { return null; } return _attachedObjectHandlers.get(compositeComponentParent); } @Override public void addMethodExpressionTargeted(UIComponent targetedComponent, String attributeName, Object backingValue) { Map<String, Object> map = null; if (_methodExpressionsTargeted == null) { _methodExpressionsTargeted = new HashMap<>(); } else { map = _methodExpressionsTargeted.get(targetedComponent); } if (map == null) { map = new HashMap<>(8); _methodExpressionsTargeted.put(targetedComponent, map); } map.put(attributeName, backingValue); } @Override public boolean isMethodExpressionAttributeApplied(UIComponent compositeComponentParent, String attributeName) { if (_compositeComponentAttributesMarked == null) { return false; } Map<String, Boolean> map = _compositeComponentAttributesMarked.get(compositeComponentParent); if (map == null) { return false; } Boolean v = map.get(attributeName); return v == null ? false : v; } @Override public void markMethodExpressionAttribute(UIComponent compositeComponentParent, String attributeName) { Map<String, Boolean> map = null; if (_compositeComponentAttributesMarked == null) { _compositeComponentAttributesMarked = new HashMap<>(); } else { map = _compositeComponentAttributesMarked.get(compositeComponentParent); } if (map == null) { map = new HashMap<>(8); _compositeComponentAttributesMarked.put(compositeComponentParent, map); } map.put(attributeName, Boolean.TRUE); } @Override public void clearMethodExpressionAttribute(UIComponent compositeComponentParent, String attributeName) { if (_compositeComponentAttributesMarked == null) { return; } Map<String, Boolean> map = _compositeComponentAttributesMarked.get(compositeComponentParent); if (map == null) { //No map, so just return return; } map.put(attributeName, Boolean.FALSE); } @Override public Object removeMethodExpressionTargeted(UIComponent targetedComponent, String attributeName) { if (_methodExpressionsTargeted == null) { return null; } Map<String, Object> map = _methodExpressionsTargeted.get(targetedComponent); if (map != null) { return map.remove(attributeName); } return null; } /** * Add a level of components marked for deletion. */ private void increaseComponentLevelMarkedForDeletion() { _deletionLevel++; if (_componentsMarkedForDeletion.size() <= _deletionLevel) { _componentsMarkedForDeletion.add(new HashMap<String, UIComponent>()); } } /** * Remove the last component level from the components marked to be deleted. The components are removed * from this list because they are deleted from the tree. This is done in ComponentSupport.finalizeForDeletion. * * @return the array of components that are removed. */ private void decreaseComponentLevelMarkedForDeletion() { //The common case is this co if (!_componentsMarkedForDeletion.get(_deletionLevel).isEmpty()) { _componentsMarkedForDeletion.get(_deletionLevel).clear(); } _deletionLevel--; } /** Mark a component to be deleted from the tree. The component to be deleted is added on the * current level. This is done from ComponentSupport.markForDeletion * * @param id * @param component the component marked for deletion. */ private void markComponentForDeletion(String id , UIComponent component) { _componentsMarkedForDeletion.get(_deletionLevel).put(id, component); } /** * Remove a component from the last level of components marked to be deleted. * * @param id */ private UIComponent removeComponentForDeletion(String id) { UIComponent removedComponent = _componentsMarkedForDeletion.get(_deletionLevel).remove(id); if (removedComponent != null && _deletionLevel > 0) { _componentsMarkedForDeletion.get(_deletionLevel-1).remove(id); } return removedComponent; } @Override public void markForDeletion(UIComponent component) { increaseComponentLevelMarkedForDeletion(); String id = (String) component.getAttributes().get(ComponentSupport.MARK_CREATED); id = (id == null) ? VIEWROOT_FACELET_ID : id; markComponentForDeletion(id, component); if (component.getFacetCount() > 0) { for (UIComponent fc: component.getFacets().values()) { id = (String) fc.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null) { markComponentForDeletion(id, fc); } else if (Boolean.TRUE.equals(fc.getAttributes().get(ComponentSupport.FACET_CREATED_UIPANEL_MARKER))) { //Mark its children, but do not mark itself. int childCount = fc.getChildCount(); if (childCount > 0) { for (int i = 0; i < childCount; i++) { UIComponent child = fc.getChildren().get(i); id = (String) child.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null) { markComponentForDeletion(id, child); } } } } } } int childCount = component.getChildCount(); if (childCount > 0) { for (int i = 0; i < childCount; i++) { UIComponent child = component.getChildren().get(i); id = (String) child.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null) { markComponentForDeletion(id, child); } } } } @Override public void removeComponentForDeletion(UIComponent component) { String id = (String) component.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null) { removeComponentForDeletion(id); } else if (id == null && Boolean.TRUE.equals(component.getAttributes().get(ComponentSupport.FACET_CREATED_UIPANEL_MARKER))) { int childCount = component.getChildCount(); if (childCount > 0) { for (int i = 0, size = childCount; i < size; i++) { UIComponent child = component.getChildren().get(i); id = (String) child.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null) { removeComponentForDeletion(id); } } } } } @Override public void finalizeForDeletion(UIComponent component) { String id = (String) component.getAttributes().get(ComponentSupport.MARK_CREATED); id = (id == null) ? VIEWROOT_FACELET_ID : id; // remove any existing marks of deletion removeComponentForDeletion(id); // finally remove any children marked as deleted int childCount = component.getChildCount(); if (childCount > 0) { for (int i = 0; i < childCount; i ++) { UIComponent child = component.getChildren().get(i); id = (String) child.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null && removeComponentForDeletion(id) != null) { component.getChildren().remove(i); i--; childCount--; } } } // remove any facets marked as deleted if (component.getFacetCount() > 0) { Map<String, UIComponent> facets = component.getFacets(); for (Iterator<UIComponent> itr = facets.values().iterator(); itr.hasNext();) { UIComponent fc = itr.next(); id = (String) fc.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null && removeComponentForDeletion(id) != null) { itr.remove(); } else if (id == null && Boolean.TRUE.equals(fc.getAttributes().get(ComponentSupport.FACET_CREATED_UIPANEL_MARKER))) { if (fc.getChildCount() > 0) { for (int i = 0, size = fc.getChildCount(); i < size; i++) { UIComponent child = fc.getChildren().get(i); id = (String) child.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null && removeComponentForDeletion(id) != null) { fc.getChildren().remove(i); i--; size--; } } } if (fc.getChildCount() == 0) { itr.remove(); } } } } decreaseComponentLevelMarkedForDeletion(); } @Override public void markRelocatableResourceForDeletion(UIComponent component) { // The idea is keep track of the component resources that can be relocated // to later check which resources were not refreshed and delete them. String id = (String) component.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null) { _relocatableResourceForDeletion.put(id, component); } } @Override public void finalizeRelocatableResourcesForDeletion(UIViewRoot root) { String id = null; //Check facets if (root.getFacetCount() > 0) { Map<String, UIComponent> facets = root.getFacets(); for (Iterator<UIComponent> itr = facets.values().iterator(); itr.hasNext();) { UIComponent fc = itr.next(); // It is necessary to check only the facets that are used as holder for // component resources. To do that, the best way is check the ones that // has id starting with "jakarta_faces_location_" if (fc.getId() != null && fc.getId().startsWith(JAKARTA_FACES_LOCATION_PREFIX)) { // Check all children with MARK_CREATED and if one is found, check if it was // refreshed by the algorithm. int childCount = fc.getChildCount(); if (childCount > 0) { for (int i = 0; i < childCount; i ++) { UIComponent child = fc.getChildren().get(i); id = (String) child.getAttributes().get(ComponentSupport.MARK_CREATED); if (id != null && finalizeRelocatableResourcesForDeletion(id) == null) { fc.getChildren().remove(i); i--; childCount--; } } } } } } } private UIComponent finalizeRelocatableResourcesForDeletion(String id) { return _relocatableResourceForDeletion.remove(id); } @Override public String startComponentUniqueIdSection() { _level++; _sectionUniqueComponentIdCounter.get().startUniqueIdSection(); return _sectionUniqueIdCounter.get().startUniqueIdSection(); } @Override public String startComponentUniqueIdSection(String base) { _level++; _sectionUniqueComponentIdCounter.get().startUniqueIdSection(base); return _sectionUniqueIdCounter.get().startUniqueIdSection(base); } @Override public void incrementUniqueId() { _sectionUniqueIdCounter.get().incrementUniqueId(); } @Override public String generateUniqueId() { return _sectionUniqueIdCounter.get().generateUniqueId(); } @Override public void generateUniqueId(StringBuilder builderToAdd) { _sectionUniqueIdCounter.get().generateUniqueId(builderToAdd); } @Override public String generateUniqueComponentId() { return _sectionUniqueComponentIdCounter.get().generateUniqueId(); } @Override public void incrementUniqueComponentId() { _sectionUniqueComponentIdCounter.get().incrementUniqueId(); } @Override public void endComponentUniqueIdSection() { _level--; _sectionUniqueIdCounter.get().endUniqueIdSection(); _sectionUniqueComponentIdCounter.get().endUniqueIdSection(); } @Override public void endComponentUniqueIdSection(String base) { _level--; _sectionUniqueIdCounter.get().endUniqueIdSection(base); _sectionUniqueComponentIdCounter.get().endUniqueIdSection(base); } @Override public void startMetadataSection() { if (_isInMetadataSection == 0) { if (_sectionUniqueMetadataIdCounter == null) { _sectionUniqueMetadataIdCounter = new Lazy(() -> new SectionUniqueIdCounter("__md_")); } if (_sectionUniqueComponentMetadataIdCounter == null) { _sectionUniqueComponentMetadataIdCounter = new Lazy(() -> new SectionUniqueIdCounter("__md_")); } //Replace the counter with metadata counter _sectionUniqueIdCounter = _sectionUniqueMetadataIdCounter; _sectionUniqueComponentIdCounter = _sectionUniqueComponentMetadataIdCounter; } _isInMetadataSection++; } @Override public void endMetadataSection() { _isInMetadataSection--; if (_isInMetadataSection == 0) { //Use normal id counter again _sectionUniqueIdCounter = _sectionUniqueNormalIdCounter; _sectionUniqueComponentIdCounter = _sectionUniqueComponentNormalIdCounter; } } @Override public boolean isInMetadataSection() { return _isInMetadataSection > 0; } @Override public boolean isRefreshingSection() { return isRefreshingTransientBuild() || (!isBuildingViewMetadata() && isInMetadataSection()); } @Override public StringBuilder getSharedStringBuilder() { if (_sharedStringBuilder == null) { _sharedStringBuilder = new StringBuilder(); } else { _sharedStringBuilder.setLength(0); } return _sharedStringBuilder; } @Override public boolean isDynamicCompositeComponentHandler() { return this._dynamicComponentHandler; } @Override public void setDynamicCompositeComponentHandler(boolean value) { this._dynamicComponentHandler = value; } @Override public void pushDynamicComponentSection(String base) { if (_sectionUniqueIdCounterStack == null) { _sectionUniqueIdCounterStack = new ArrayList<SectionUniqueIdCounter>(); } if (_sectionUniqueComponentIdCounterStack == null) { _sectionUniqueComponentIdCounterStack = new ArrayList<SectionUniqueIdCounter>(); } // Activate refresh transient build over dynamic component section. if (_sectionUniqueComponentIdCounterStack.isEmpty()) { _oldRefreshingTransientBuild = _isRefreshingTransientBuild; } _isRefreshingTransientBuild = true; _sectionUniqueIdCounterStack.add(_sectionUniqueIdCounter.get()); _sectionUniqueComponentIdCounterStack.add(_sectionUniqueComponentIdCounter.get()); _sectionUniqueIdCounter = new Lazy(() -> new SectionUniqueIdCounter(base + '_')); _sectionUniqueComponentIdCounter = new Lazy(() -> new SectionUniqueIdCounter('_' + base + '_')); _sectionUniqueNormalIdCounter = _sectionUniqueIdCounter; _sectionUniqueComponentNormalIdCounter = _sectionUniqueComponentIdCounter; _dynamicComponentTopLevel = true; _dynamicComponentSection++; if (_dynamicOldDeletionLevel == null) { _dynamicOldDeletionLevel = new ArrayList<Integer>(4); } _dynamicOldDeletionLevel.add(_deletionLevel); // Increase one level in the mark/delete algorithm to avoid any interference in the previous code. increaseComponentLevelMarkedForDeletion(); } @Override public void popDynamicComponentSection() { decreaseComponentLevelMarkedForDeletion(); int oldDeletionLevel = _dynamicOldDeletionLevel.remove(_dynamicOldDeletionLevel.size()-1); if (_deletionLevel != oldDeletionLevel) { // This happens because in a dynamic component section, the dynamic top component level does not take // part in the algorithm. The easiest solution so far is just decrease one level to let it as it was // before enter the algorithm. decreaseComponentLevelMarkedForDeletion(); } _sectionUniqueIdCounter.reset( _sectionUniqueIdCounterStack.remove(_sectionUniqueIdCounterStack.size() - 1)); _sectionUniqueComponentIdCounter.reset( _sectionUniqueComponentIdCounterStack.remove(_sectionUniqueComponentIdCounterStack.size() - 1)); //Restore refresh section if (_sectionUniqueComponentIdCounterStack.isEmpty()) { _isRefreshingTransientBuild = _oldRefreshingTransientBuild; } _sectionUniqueNormalIdCounter = _sectionUniqueIdCounter; _sectionUniqueComponentNormalIdCounter = _sectionUniqueComponentIdCounter; _dynamicComponentTopLevel = false; _dynamicComponentSection--; } @Override public boolean isDynamicComponentTopLevel() { return _dynamicComponentTopLevel; } @Override public void setDynamicComponentTopLevel(boolean value) { _dynamicComponentTopLevel = value; } @Override public boolean isDynamicComponentSection() { return _dynamicComponentSection > 0; } @Override public void setViewRoot(UIViewRoot root) { this._viewRoot = root; } @Override public UIViewRoot getViewRoot(FacesContext facesContext) { if (_viewRoot == null) { return facesContext.getViewRoot(); } return _viewRoot; } @Override public VisitContextFactory getVisitContextFactory() { if (_visitContextFactory == null) { // Store it in application map improve performance because it avoids FactoryFinder.getFactory(...) call // which has synchronized blocks. _visitContextFactory = (VisitContextFactory) _facesContext.getExternalContext().getApplicationMap() .computeIfAbsent( VISIT_CONTEXT_FACTORY, k -> FactoryFinder.getFactory(FactoryFinder.VISIT_CONTEXT_FACTORY)); } return _visitContextFactory; } private static class SimpleEntry<K, V> implements Map.Entry<K, V> { private final K _key; private final V _value; public SimpleEntry(K key, V value) { _key = key; _value = value; } @Override public K getKey() { return _key; } @Override public V getValue() { return _value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_key == null) ? 0 : _key.hashCode()); result = prime * result + ((_value == null) ? 0 : _value.hashCode()); return result; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SimpleEntry other = (SimpleEntry) obj; if (_key == null) { if (other._key != null) { return false; } } else if (!_key.equals(other._key)) { return false; } if (_value == null) { if (other._value != null) { return false; } } else if (!_value.equals(other._value)) { return false; } return true; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } } }
googleapis/google-cloud-java
37,787
java-securesourcemanager/proto-google-cloud-securesourcemanager-v1/src/main/java/com/google/cloud/securesourcemanager/v1/ListPullRequestFileDiffsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/securesourcemanager/v1/secure_source_manager.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.securesourcemanager.v1; /** * * * <pre> * ListPullRequestFileDiffsResponse is the response containing file diffs * returned from ListPullRequestFileDiffs. * </pre> * * Protobuf type {@code google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse} */ public final class ListPullRequestFileDiffsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse) ListPullRequestFileDiffsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPullRequestFileDiffsResponse.newBuilder() to construct. private ListPullRequestFileDiffsResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPullRequestFileDiffsResponse() { fileDiffs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListPullRequestFileDiffsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_ListPullRequestFileDiffsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_ListPullRequestFileDiffsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse.class, com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse.Builder.class); } public static final int FILE_DIFFS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.securesourcemanager.v1.FileDiff> fileDiffs_; /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.securesourcemanager.v1.FileDiff> getFileDiffsList() { return fileDiffs_; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder> getFileDiffsOrBuilderList() { return fileDiffs_; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ @java.lang.Override public int getFileDiffsCount() { return fileDiffs_.size(); } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ @java.lang.Override public com.google.cloud.securesourcemanager.v1.FileDiff getFileDiffs(int index) { return fileDiffs_.get(index); } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ @java.lang.Override public com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder getFileDiffsOrBuilder( int index) { return fileDiffs_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < fileDiffs_.size(); i++) { output.writeMessage(1, fileDiffs_.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 < fileDiffs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, fileDiffs_.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.securesourcemanager.v1.ListPullRequestFileDiffsResponse)) { return super.equals(obj); } com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse other = (com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse) obj; if (!getFileDiffsList().equals(other.getFileDiffsList())) 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 (getFileDiffsCount() > 0) { hash = (37 * hash) + FILE_DIFFS_FIELD_NUMBER; hash = (53 * hash) + getFileDiffsList().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.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse 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> * ListPullRequestFileDiffsResponse is the response containing file diffs * returned from ListPullRequestFileDiffs. * </pre> * * Protobuf type {@code google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse) com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_ListPullRequestFileDiffsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_ListPullRequestFileDiffsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse.class, com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse.Builder .class); } // Construct using // com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (fileDiffsBuilder_ == null) { fileDiffs_ = java.util.Collections.emptyList(); } else { fileDiffs_ = null; fileDiffsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto .internal_static_google_cloud_securesourcemanager_v1_ListPullRequestFileDiffsResponse_descriptor; } @java.lang.Override public com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse getDefaultInstanceForType() { return com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse build() { com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse buildPartial() { com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse result = new com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse result) { if (fileDiffsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { fileDiffs_ = java.util.Collections.unmodifiableList(fileDiffs_); bitField0_ = (bitField0_ & ~0x00000001); } result.fileDiffs_ = fileDiffs_; } else { result.fileDiffs_ = fileDiffsBuilder_.build(); } } private void buildPartial0( com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse 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.securesourcemanager.v1.ListPullRequestFileDiffsResponse) { return mergeFrom( (com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse other) { if (other == com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse .getDefaultInstance()) return this; if (fileDiffsBuilder_ == null) { if (!other.fileDiffs_.isEmpty()) { if (fileDiffs_.isEmpty()) { fileDiffs_ = other.fileDiffs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureFileDiffsIsMutable(); fileDiffs_.addAll(other.fileDiffs_); } onChanged(); } } else { if (!other.fileDiffs_.isEmpty()) { if (fileDiffsBuilder_.isEmpty()) { fileDiffsBuilder_.dispose(); fileDiffsBuilder_ = null; fileDiffs_ = other.fileDiffs_; bitField0_ = (bitField0_ & ~0x00000001); fileDiffsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getFileDiffsFieldBuilder() : null; } else { fileDiffsBuilder_.addAllMessages(other.fileDiffs_); } } } 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.securesourcemanager.v1.FileDiff m = input.readMessage( com.google.cloud.securesourcemanager.v1.FileDiff.parser(), extensionRegistry); if (fileDiffsBuilder_ == null) { ensureFileDiffsIsMutable(); fileDiffs_.add(m); } else { fileDiffsBuilder_.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.securesourcemanager.v1.FileDiff> fileDiffs_ = java.util.Collections.emptyList(); private void ensureFileDiffsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { fileDiffs_ = new java.util.ArrayList<com.google.cloud.securesourcemanager.v1.FileDiff>(fileDiffs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.securesourcemanager.v1.FileDiff, com.google.cloud.securesourcemanager.v1.FileDiff.Builder, com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder> fileDiffsBuilder_; /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public java.util.List<com.google.cloud.securesourcemanager.v1.FileDiff> getFileDiffsList() { if (fileDiffsBuilder_ == null) { return java.util.Collections.unmodifiableList(fileDiffs_); } else { return fileDiffsBuilder_.getMessageList(); } } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public int getFileDiffsCount() { if (fileDiffsBuilder_ == null) { return fileDiffs_.size(); } else { return fileDiffsBuilder_.getCount(); } } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public com.google.cloud.securesourcemanager.v1.FileDiff getFileDiffs(int index) { if (fileDiffsBuilder_ == null) { return fileDiffs_.get(index); } else { return fileDiffsBuilder_.getMessage(index); } } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder setFileDiffs(int index, com.google.cloud.securesourcemanager.v1.FileDiff value) { if (fileDiffsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFileDiffsIsMutable(); fileDiffs_.set(index, value); onChanged(); } else { fileDiffsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder setFileDiffs( int index, com.google.cloud.securesourcemanager.v1.FileDiff.Builder builderForValue) { if (fileDiffsBuilder_ == null) { ensureFileDiffsIsMutable(); fileDiffs_.set(index, builderForValue.build()); onChanged(); } else { fileDiffsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder addFileDiffs(com.google.cloud.securesourcemanager.v1.FileDiff value) { if (fileDiffsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFileDiffsIsMutable(); fileDiffs_.add(value); onChanged(); } else { fileDiffsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder addFileDiffs(int index, com.google.cloud.securesourcemanager.v1.FileDiff value) { if (fileDiffsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFileDiffsIsMutable(); fileDiffs_.add(index, value); onChanged(); } else { fileDiffsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder addFileDiffs( com.google.cloud.securesourcemanager.v1.FileDiff.Builder builderForValue) { if (fileDiffsBuilder_ == null) { ensureFileDiffsIsMutable(); fileDiffs_.add(builderForValue.build()); onChanged(); } else { fileDiffsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder addFileDiffs( int index, com.google.cloud.securesourcemanager.v1.FileDiff.Builder builderForValue) { if (fileDiffsBuilder_ == null) { ensureFileDiffsIsMutable(); fileDiffs_.add(index, builderForValue.build()); onChanged(); } else { fileDiffsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder addAllFileDiffs( java.lang.Iterable<? extends com.google.cloud.securesourcemanager.v1.FileDiff> values) { if (fileDiffsBuilder_ == null) { ensureFileDiffsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, fileDiffs_); onChanged(); } else { fileDiffsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder clearFileDiffs() { if (fileDiffsBuilder_ == null) { fileDiffs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { fileDiffsBuilder_.clear(); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public Builder removeFileDiffs(int index) { if (fileDiffsBuilder_ == null) { ensureFileDiffsIsMutable(); fileDiffs_.remove(index); onChanged(); } else { fileDiffsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public com.google.cloud.securesourcemanager.v1.FileDiff.Builder getFileDiffsBuilder(int index) { return getFileDiffsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder getFileDiffsOrBuilder( int index) { if (fileDiffsBuilder_ == null) { return fileDiffs_.get(index); } else { return fileDiffsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public java.util.List<? extends com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder> getFileDiffsOrBuilderList() { if (fileDiffsBuilder_ != null) { return fileDiffsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(fileDiffs_); } } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public com.google.cloud.securesourcemanager.v1.FileDiff.Builder addFileDiffsBuilder() { return getFileDiffsFieldBuilder() .addBuilder(com.google.cloud.securesourcemanager.v1.FileDiff.getDefaultInstance()); } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public com.google.cloud.securesourcemanager.v1.FileDiff.Builder addFileDiffsBuilder(int index) { return getFileDiffsFieldBuilder() .addBuilder(index, com.google.cloud.securesourcemanager.v1.FileDiff.getDefaultInstance()); } /** * * * <pre> * The list of pull request file diffs. * </pre> * * <code>repeated .google.cloud.securesourcemanager.v1.FileDiff file_diffs = 1;</code> */ public java.util.List<com.google.cloud.securesourcemanager.v1.FileDiff.Builder> getFileDiffsBuilderList() { return getFileDiffsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.securesourcemanager.v1.FileDiff, com.google.cloud.securesourcemanager.v1.FileDiff.Builder, com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder> getFileDiffsFieldBuilder() { if (fileDiffsBuilder_ == null) { fileDiffsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.securesourcemanager.v1.FileDiff, com.google.cloud.securesourcemanager.v1.FileDiff.Builder, com.google.cloud.securesourcemanager.v1.FileDiffOrBuilder>( fileDiffs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); fileDiffs_ = null; } return fileDiffsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse) private static final com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse(); } public static com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPullRequestFileDiffsResponse> PARSER = new com.google.protobuf.AbstractParser<ListPullRequestFileDiffsResponse>() { @java.lang.Override public ListPullRequestFileDiffsResponse 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<ListPullRequestFileDiffsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPullRequestFileDiffsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.securesourcemanager.v1.ListPullRequestFileDiffsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/fineract
38,170
fineract-provider/src/main/java/org/apache/fineract/portfolio/loanproduct/api/LoanProductsApiResource.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.portfolio.loanproduct.api; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.UriInfo; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import lombok.RequiredArgsConstructor; import org.apache.fineract.accounting.common.AccountingConstants.LoanProductAccountingParams; import org.apache.fineract.accounting.common.AccountingDropdownReadPlatformService; import org.apache.fineract.accounting.glaccount.data.GLAccountData; import org.apache.fineract.accounting.producttoaccountmapping.data.ChargeOffReasonToGLAccountMapper; import org.apache.fineract.accounting.producttoaccountmapping.data.ChargeToGLAccountMapper; import org.apache.fineract.accounting.producttoaccountmapping.data.ClassificationToGLAccountData; import org.apache.fineract.accounting.producttoaccountmapping.data.PaymentTypeToGLAccountMapper; import org.apache.fineract.accounting.producttoaccountmapping.data.WriteOffReasonsToExpenseAccountMapper; import org.apache.fineract.accounting.producttoaccountmapping.service.ProductToGLAccountMappingReadPlatformService; import org.apache.fineract.commands.domain.CommandWrapper; import org.apache.fineract.commands.service.CommandWrapperBuilder; import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService; import org.apache.fineract.infrastructure.codes.data.CodeValueData; import org.apache.fineract.infrastructure.codes.service.CodeValueReadPlatformService; import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService; import org.apache.fineract.infrastructure.core.api.ApiFacingEnum; import org.apache.fineract.infrastructure.core.api.ApiParameterHelper; import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.core.data.EnumOptionData; import org.apache.fineract.infrastructure.core.data.StringEnumOptionData; import org.apache.fineract.infrastructure.core.domain.ExternalId; import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.apache.fineract.infrastructure.core.service.ExternalIdFactory; import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; import org.apache.fineract.organisation.monetary.data.CurrencyData; import org.apache.fineract.organisation.monetary.service.CurrencyReadPlatformService; import org.apache.fineract.portfolio.charge.data.ChargeData; import org.apache.fineract.portfolio.charge.service.ChargeReadPlatformService; import org.apache.fineract.portfolio.common.domain.DaysInYearCustomStrategyType; import org.apache.fineract.portfolio.common.service.DropdownReadPlatformService; import org.apache.fineract.portfolio.delinquency.data.DelinquencyBucketData; import org.apache.fineract.portfolio.delinquency.service.DelinquencyReadPlatformService; import org.apache.fineract.portfolio.floatingrates.data.FloatingRateData; import org.apache.fineract.portfolio.floatingrates.service.FloatingRatesReadPlatformService; import org.apache.fineract.portfolio.fund.data.FundData; import org.apache.fineract.portfolio.fund.service.FundReadPlatformService; import org.apache.fineract.portfolio.loanaccount.api.LoanApiConstants; import org.apache.fineract.portfolio.loanaccount.api.LoanTransactionApiConstants; import org.apache.fineract.portfolio.loanaccount.domain.LoanBuyDownFeeCalculationType; import org.apache.fineract.portfolio.loanaccount.domain.LoanBuyDownFeeIncomeType; import org.apache.fineract.portfolio.loanaccount.domain.LoanBuyDownFeeStrategy; import org.apache.fineract.portfolio.loanaccount.domain.LoanCapitalizedIncomeCalculationType; import org.apache.fineract.portfolio.loanaccount.domain.LoanCapitalizedIncomeStrategy; import org.apache.fineract.portfolio.loanaccount.domain.LoanCapitalizedIncomeType; import org.apache.fineract.portfolio.loanaccount.domain.LoanChargeOffBehaviour; import org.apache.fineract.portfolio.loanaccount.loanschedule.domain.LoanScheduleProcessingType; import org.apache.fineract.portfolio.loanaccount.loanschedule.domain.LoanScheduleType; import org.apache.fineract.portfolio.loanproduct.LoanProductConstants; import org.apache.fineract.portfolio.loanproduct.data.LoanProductData; import org.apache.fineract.portfolio.loanproduct.data.TransactionProcessingStrategyData; import org.apache.fineract.portfolio.loanproduct.domain.AllocationType; import org.apache.fineract.portfolio.loanproduct.domain.CreditAllocationTransactionType; import org.apache.fineract.portfolio.loanproduct.domain.FutureInstallmentAllocationRule; import org.apache.fineract.portfolio.loanproduct.domain.LoanSupportedInterestRefundTypes; import org.apache.fineract.portfolio.loanproduct.domain.PaymentAllocationTransactionType; import org.apache.fineract.portfolio.loanproduct.domain.PaymentAllocationType; import org.apache.fineract.portfolio.loanproduct.exception.LoanProductNotFoundException; import org.apache.fineract.portfolio.loanproduct.productmix.data.ProductMixData; import org.apache.fineract.portfolio.loanproduct.productmix.service.ProductMixReadPlatformService; import org.apache.fineract.portfolio.loanproduct.service.LoanDropdownReadPlatformService; import org.apache.fineract.portfolio.loanproduct.service.LoanProductReadPlatformService; import org.apache.fineract.portfolio.paymenttype.data.PaymentTypeData; import org.apache.fineract.portfolio.paymenttype.service.PaymentTypeReadPlatformService; import org.apache.fineract.portfolio.rate.data.RateData; import org.apache.fineract.portfolio.rate.service.RateReadService; import org.springframework.stereotype.Component; @Path("/v1/loanproducts") @Component @Tag(name = "Loan Products", description = "A Loan product is a template that is used when creating a loan. Much of the template definition can be overridden during loan creation.") @RequiredArgsConstructor public class LoanProductsApiResource { private static final Set<String> LOAN_PRODUCT_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "name", "shortName", "description", "fundId", "fundName", "includeInBorrowerCycle", "currency", "principal", "minPrincipal", "maxPrincipal", "numberOfRepayments", "minNumberOfRepayments", "maxNumberOfRepayments", "repaymentEvery", "repaymentFrequencyType", "graceOnPrincipalPayment", "recurringMoratoriumOnPrincipalPeriods", "graceOnInterestPayment", "graceOnInterestCharged", "interestRatePerPeriod", "minInterestRatePerPeriod", "maxInterestRatePerPeriod", "interestRateFrequencyType", "annualInterestRate", "amortizationType", "interestType", "interestCalculationPeriodType", LoanProductConstants.ALLOW_PARTIAL_PERIOD_INTEREST_CALCUALTION_PARAM_NAME, "inArrearsTolerance", "transactionProcessingStrategyCode", "transactionProcessingStrategyName", "charges", "accountingRule", "externalId", "accountingMappings", "paymentChannelToFundSourceMappings", "fundOptions", "paymentTypeOptions", "currencyOptions", "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", "transactionProcessingStrategyOptions", "chargeOptions", "accountingOptions", "accountingRuleOptions", "accountingMappingOptions", "floatingRateOptions", "isLinkedToFloatingInterestRates", "floatingRatesId", "interestRateDifferential", "minDifferentialLendingRate", "defaultDifferentialLendingRate", "maxDifferentialLendingRate", "isFloatingInterestRateCalculationAllowed", LoanProductConstants.CAN_USE_FOR_TOPUP, LoanProductConstants.IS_EQUAL_AMORTIZATION_PARAM, LoanProductConstants.RATES_PARAM_NAME, LoanApiConstants.fixedPrincipalPercentagePerInstallmentParamName, LoanProductConstants.DUE_DAYS_FOR_REPAYMENT_EVENT, LoanProductConstants.OVER_DUE_DAYS_FOR_REPAYMENT_EVENT, LoanProductConstants.ENABLE_DOWN_PAYMENT, LoanProductConstants.DISBURSED_AMOUNT_PERCENTAGE_DOWN_PAYMENT, LoanProductConstants.ENABLE_AUTO_REPAYMENT_DOWN_PAYMENT, LoanProductConstants.REPAYMENT_START_DATE_TYPE, LoanProductConstants.DAYS_IN_YEAR_CUSTOM_STRATEGY_TYPE_PARAMETER_NAME, LoanProductConstants.ENABLE_INCOME_CAPITALIZATION_PARAM_NAME, LoanProductConstants.CAPITALIZED_INCOME_CALCULATION_TYPE_PARAM_NAME, LoanProductConstants.CAPITALIZED_INCOME_STRATEGY_PARAM_NAME, LoanProductConstants.CAPITALIZED_INCOME_TYPE_PARAM_NAME, LoanProductConstants.ENABLE_BUY_DOWN_FEE_PARAM_NAME, LoanProductConstants.BUY_DOWN_FEE_CALCULATION_TYPE_PARAM_NAME, LoanProductConstants.BUY_DOWN_FEE_STRATEGY_PARAM_NAME, LoanProductConstants.BUY_DOWN_FEE_INCOME_TYPE_PARAM_NAME)); private static final Set<String> PRODUCT_MIX_DATA_PARAMETERS = new HashSet<>( Arrays.asList("productId", "productName", "restrictedProducts", "allowedProducts", "productOptions")); private static final String RESOURCE_NAME_FOR_PERMISSIONS = "LOANPRODUCT"; public static final String PRODUCTMIX = "PRODUCTMIX"; public static final String PRODUCT_MIXES = "productMixes"; private final PlatformSecurityContext context; private final LoanProductReadPlatformService loanProductReadPlatformService; private final ChargeReadPlatformService chargeReadPlatformService; private final CurrencyReadPlatformService currencyReadPlatformService; private final FundReadPlatformService fundReadPlatformService; private final DefaultToApiJsonSerializer<LoanProductData> toApiJsonSerializer; private final ApiRequestParameterHelper apiRequestParameterHelper; private final LoanDropdownReadPlatformService dropdownReadPlatformService; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final ProductToGLAccountMappingReadPlatformService accountMappingReadPlatformService; private final AccountingDropdownReadPlatformService accountingDropdownReadPlatformService; private final DefaultToApiJsonSerializer<ProductMixData> productMixDataApiJsonSerializer; private final ProductMixReadPlatformService productMixReadPlatformService; private final DropdownReadPlatformService commonDropdownReadPlatformService; private final PaymentTypeReadPlatformService paymentTypeReadPlatformService; private final FloatingRatesReadPlatformService floatingRateReadPlatformService; private final RateReadService rateReadService; private final ConfigurationDomainService configurationDomainService; private final DelinquencyReadPlatformService delinquencyReadPlatformService; private final CodeValueReadPlatformService codeValueReadPlatformService; @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Create a Loan Product", description = "Depending of the Accounting Rule (accountingRule) selected, additional fields with details of the appropriate Ledger Account identifiers would need to be passed in.\n" + "\n" + "Refer MifosX Accounting Specs Draft for more details regarding the significance of the selected accounting rule\n\n" + "Mandatory Fields: name, shortName, currencyCode, digitsAfterDecimal, inMultiplesOf, principal, numberOfRepayments, repaymentEvery, repaymentFrequencyType, interestRatePerPeriod, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, transactionProcessingStrategyCode, accountingRule, isInterestRecalculationEnabled, daysInYearType, daysInMonthType\n\n" + "Optional Fields: inArrearsTolerance, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, graceOnArrearsAgeing, charges, paymentChannelToFundSourceMappings, feeToIncomeAccountMappings, penaltyToIncomeAccountMappings, chargeOffReasonToExpenseAccountMappings, includeInBorrowerCycle, useBorrowerCycle,principalVariationsForBorrowerCycle, numberOfRepaymentVariationsForBorrowerCycle, interestRateVariationsForBorrowerCycle, multiDisburseLoan,maxTrancheCount, outstandingLoanBalance,overdueDaysForNPA,holdGuaranteeFunds, principalThresholdForLastInstalment, accountMovesOutOfNPAOnlyOnArrearsCompletion, canDefineInstallmentAmount, installmentAmountInMultiplesOf, allowAttributeOverrides, allowPartialPeriodInterestCalcualtion,dueDaysForRepaymentEvent,overDueDaysForRepaymentEvent,enableDownPayment,disbursedAmountPercentageDownPayment,enableAutoRepaymentForDownPayment,repaymentStartDateType,enableBuyDownFee\n\n" + "Additional Mandatory Fields for Cash(2) based accounting: fundSourceAccountId, loanPortfolioAccountId, interestOnLoanAccountId, incomeFromFeeAccountId, incomeFromPenaltyAccountId, writeOffAccountId, transfersInSuspenseAccountId, overpaymentLiabilityAccountId\n\n" + "Additional Mandatory Fields for periodic (3) and upfront (4)accrual accounting: fundSourceAccountId, loanPortfolioAccountId, interestOnLoanAccountId, incomeFromFeeAccountId, incomeFromPenaltyAccountId, writeOffAccountId, receivableInterestAccountId, receivableFeeAccountId, receivablePenaltyAccountId, transfersInSuspenseAccountId, overpaymentLiabilityAccountId\n\n" + "Additional Mandatory Fields if interest recalculation is enabled(true): interestRecalculationCompoundingMethod, rescheduleStrategyMethod, recalculationRestFrequencyType\n\n" + "Additional Optional Fields if interest recalculation is enabled(true): isArrearsBasedOnOriginalSchedule, preClosureInterestCalculationStrategy\n\n" + "Additional Optional Fields if interest recalculation is enabled(true) and recalculationRestFrequencyType is not same as repayment period: recalculationRestFrequencyInterval, recalculationRestFrequencyDate\n\n" + "Additional Optional Fields if interest recalculation is enabled(true) and interestRecalculationCompoundingMethod is enabled: recalculationCompoundingFrequencyType\n\n" + "Additional Optional Fields if interest recalculation is enabled(true) and interestRecalculationCompoundingMethod is enabled and recalculationCompoundingFrequencyType is not same as repayment period: recalculationCompoundingFrequencyInterval, recalculationCompoundingFrequencyDate\n\n" + "Additional Mandatory Fields if Hold Guarantee funds is enabled(true): mandatoryGuarantee\n\n" + "Additional Optional Fields if Hold Guarantee funds is enabled(true): minimumGuaranteeFromOwnFunds,minimumGuaranteeFromGuarantor") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.PostLoanProductsRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.PostLoanProductsResponse.class))) }) public String createLoanProduct(@Parameter(hidden = true) final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createLoanProduct().withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "List Loan Products", description = "Lists Loan Products\n\n" + "Example Requests:\n" + "\n" + "loanproducts\n" + "\n" + "\n" + "loanproducts?fields=name,description,interestRateFrequencyType,amortizationType") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = LoanProductsApiResourceSwagger.GetLoanProductsResponse.class)))) }) public String retrieveAllLoanProducts(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS); final Set<String> associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (!associationParameters.isEmpty() && associationParameters.contains(PRODUCT_MIXES)) { this.context.authenticatedUser().validateHasReadPermission(PRODUCTMIX); final Collection<ProductMixData> productMixes = this.productMixReadPlatformService.retrieveAllProductMixes(); return this.productMixDataApiJsonSerializer.serialize(settings, productMixes, PRODUCT_MIX_DATA_PARAMETERS); } final Collection<LoanProductData> products = this.loanProductReadPlatformService.retrieveAllLoanProducts(); return this.toApiJsonSerializer.serialize(settings, products, LOAN_PRODUCT_DATA_PARAMETERS); } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Retrieve Loan Product Details Template", description = "This is a convenience resource. It can be useful when building maintenance user interface screens for client applications. The template data returned consists of any or all of:\n" + "\n" + "Field Defaults\n" + "Allowed description Lists\n" + "Example Request:\n" + "\n" + "loanproducts/template") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.GetLoanProductsTemplateResponse.class))) }) public String retrieveTemplate(@Context final UriInfo uriInfo, @QueryParam("isProductMixTemplate") @Parameter(description = "isProductMixTemplate") final boolean isProductMixTemplate) { this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (isProductMixTemplate) { this.context.authenticatedUser().validateHasReadPermission(PRODUCTMIX); final Collection<LoanProductData> productOptions = this.loanProductReadPlatformService.retrieveAvailableLoanProductsForMix(); final ProductMixData productMixData = ProductMixData.template(productOptions); return this.productMixDataApiJsonSerializer.serialize(settings, productMixData, PRODUCT_MIX_DATA_PARAMETERS); } LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveNewLoanProductDetails(); loanProduct = handleTemplate(loanProduct); return this.toApiJsonSerializer.serialize(settings, loanProduct, LOAN_PRODUCT_DATA_PARAMETERS); } @GET @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Retrieve a Loan Product", description = "Retrieves a Loan Product\n\n" + "Example Requests:\n" + "\n" + "loanproducts/1\n" + "\n" + "\n" + "loanproducts/1?template=true\n" + "\n" + "\n" + "loanproducts/1?fields=name,description,numberOfRepayments") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.GetLoanProductsProductIdResponse.class))) }) public String retrieveLoanProductDetails(@PathParam("productId") @Parameter(description = "productId") final Long productId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS); return getLoanProductDetails(productId, uriInfo); } @PUT @Path("{productId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Update a Loan Product", description = "Updates a Loan Product") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.PutLoanProductsProductIdRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.PutLoanProductsProductIdResponse.class))) }) public String updateLoanProduct(@PathParam("productId") @Parameter(description = "productId") final Long productId, @Parameter(hidden = true) final String apiRequestBodyAsJson) { return getUpdateLoanProductResult(apiRequestBodyAsJson, productId); } @GET @Path("external-id/{externalProductId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Retrieve a Loan Product", description = "Retrieves a Loan Product\n\n" + "Example Requests:\n" + "\n" + "loanproducts/external-id/2075e308-d4a8-44d9-8203-f5a947b8c2f4\n" + "\n" + "\n" + "loanproducts/external-id/2075e308-d4a8-44d9-8203-f5a947b8c2f4?template=true\n" + "\n" + "\n" + "loanproducts/external-id/2075e308-d4a8-44d9-8203-f5a947b8c2f4?fields=name,description,numberOfRepayments") @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.GetLoanProductsProductIdResponse.class))) }) public String retrieveLoanProductDetails( @PathParam("externalProductId") @Parameter(description = "externalProductId") final String externalProductId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSIONS); ExternalId externalId = ExternalIdFactory.produce(externalProductId); Long productId = resolveProductId(externalId); if (Objects.isNull(productId)) { throw new LoanProductNotFoundException(externalId); } return getLoanProductDetails(productId, uriInfo); } @PUT @Path("external-id/{externalProductId}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Operation(summary = "Update a Loan Product", description = "Updates a Loan Product") @RequestBody(required = true, content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.PutLoanProductsProductIdRequest.class))) @ApiResponses({ @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = LoanProductsApiResourceSwagger.PutLoanProductsProductIdResponse.class))) }) public String updateLoanProduct( @PathParam("externalProductId") @Parameter(description = "externalProductId") final String externalProductId, @Parameter(hidden = true) final String apiRequestBodyAsJson) { ExternalId externalId = ExternalIdFactory.produce(externalProductId); Long productId = resolveProductId(externalId); if (Objects.isNull(productId)) { throw new LoanProductNotFoundException(externalId); } return getUpdateLoanProductResult(apiRequestBodyAsJson, productId); } private String getUpdateLoanProductResult(String apiRequestBodyAsJson, Long productId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateLoanProduct(productId).withJson(apiRequestBodyAsJson) .build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } private Long resolveProductId(ExternalId externalProductId) { return loanProductReadPlatformService.retrieveLoanProductByExternalId(externalProductId).getId(); } private String getLoanProductDetails(Long productId, UriInfo uriInfo) { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); Map<String, Object> accountingMappings; Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings; Collection<ChargeToGLAccountMapper> feeToGLAccountMappings; Collection<ChargeToGLAccountMapper> penaltyToGLAccountMappings; List<ChargeOffReasonToGLAccountMapper> chargeOffReasonToGLAccountMappings; List<WriteOffReasonsToExpenseAccountMapper> writeOffReasonsToExpenseAccountMappings; List<ClassificationToGLAccountData> capitalizedIncomeClassificationToGLAccountMappings; List<ClassificationToGLAccountData> buydowFeeClassificationToGLAccountMappings; if (loanProduct.hasAccountingEnabled()) { accountingMappings = this.accountMappingReadPlatformService.fetchAccountMappingDetailsForLoanProduct(productId, loanProduct.getAccountingRule().getId().intValue()); paymentChannelToFundSourceMappings = this.accountMappingReadPlatformService .fetchPaymentTypeToFundSourceMappingsForLoanProduct(productId); feeToGLAccountMappings = this.accountMappingReadPlatformService.fetchFeeToGLAccountMappingsForLoanProduct(productId); penaltyToGLAccountMappings = this.accountMappingReadPlatformService .fetchPenaltyToIncomeAccountMappingsForLoanProduct(productId); chargeOffReasonToGLAccountMappings = this.accountMappingReadPlatformService .fetchChargeOffReasonMappingsForLoanProduct(productId); writeOffReasonsToExpenseAccountMappings = this.accountMappingReadPlatformService .fetchWriteOffReasonMappingsForLoanProduct(productId); capitalizedIncomeClassificationToGLAccountMappings = accountMappingReadPlatformService .fetchClassificationMappingsForLoanProduct(productId, LoanProductAccountingParams.CAPITALIZED_INCOME_CLASSIFICATION_TO_INCOME_ACCOUNT_MAPPINGS); buydowFeeClassificationToGLAccountMappings = accountMappingReadPlatformService.fetchClassificationMappingsForLoanProduct( productId, LoanProductAccountingParams.BUYDOWN_FEE_CLASSIFICATION_TO_INCOME_ACCOUNT_MAPPINGS); loanProduct = LoanProductData.withAccountingDetails(loanProduct, accountingMappings, paymentChannelToFundSourceMappings, feeToGLAccountMappings, penaltyToGLAccountMappings, chargeOffReasonToGLAccountMappings, writeOffReasonsToExpenseAccountMappings, capitalizedIncomeClassificationToGLAccountMappings, buydowFeeClassificationToGLAccountMappings); } if (settings.isTemplate()) { loanProduct = handleTemplate(loanProduct); } return this.toApiJsonSerializer.serialize(settings, loanProduct, LOAN_PRODUCT_DATA_PARAMETERS); } private LoanProductData handleTemplate(final LoanProductData productData) { Collection<ChargeData> chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableFees(); if (chargeOptions.isEmpty()) { chargeOptions = null; } Collection<ChargeData> penaltyOptions = this.chargeReadPlatformService.retrieveLoanApplicablePenalties(); if (penaltyOptions.isEmpty()) { penaltyOptions = null; } boolean isRatesEnabled = this.configurationDomainService.isSubRatesEnabled(); Collection<RateData> rateOptions = this.rateReadService.retrieveLoanApplicableRates(); if (rateOptions.isEmpty()) { rateOptions = null; } final Collection<CurrencyData> currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); final List<EnumOptionData> amortizationTypeOptions = this.dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); final List<EnumOptionData> interestTypeOptions = this.dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); final List<EnumOptionData> interestCalculationPeriodTypeOptions = this.dropdownReadPlatformService .retrieveLoanInterestRateCalculatedInPeriodOptions(); final List<EnumOptionData> repaymentFrequencyTypeOptions = this.dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); final List<EnumOptionData> interestRateFrequencyTypeOptions = this.dropdownReadPlatformService .retrieveInterestRateFrequencyTypeOptions(); final Collection<PaymentTypeData> paymentTypeOptions = this.paymentTypeReadPlatformService.retrieveAllPaymentTypes(); Collection<FundData> fundOptions = this.fundReadPlatformService.retrieveAllFunds(); if (fundOptions.isEmpty()) { fundOptions = null; } Collection<DelinquencyBucketData> delinquencyBucketOptions = this.delinquencyReadPlatformService.retrieveAllDelinquencyBuckets(); if (delinquencyBucketOptions.isEmpty()) { delinquencyBucketOptions = null; } final Collection<TransactionProcessingStrategyData> transactionProcessingStrategyOptions = this.dropdownReadPlatformService .retrieveTransactionProcessingStrategies(); final Map<String, List<GLAccountData>> accountOptions = this.accountingDropdownReadPlatformService .retrieveAccountMappingOptionsForLoanProducts(); final List<EnumOptionData> accountingRuleTypeOptions = this.accountingDropdownReadPlatformService .retrieveAccountingRuleTypeOptions(); final List<EnumOptionData> loanCycleValueConditionTypeOptions = this.dropdownReadPlatformService .retrieveLoanCycleValueConditionTypeOptions(); final List<EnumOptionData> daysInMonthTypeOptions = commonDropdownReadPlatformService.retrieveDaysInMonthTypeOptions(); final List<EnumOptionData> daysInYearTypeOptions = commonDropdownReadPlatformService.retrieveDaysInYearTypeOptions(); final List<EnumOptionData> interestRecalculationCompoundingTypeOptions = dropdownReadPlatformService .retrieveInterestRecalculationCompoundingTypeOptions(); final List<EnumOptionData> rescheduleStrategyTypeOptions = dropdownReadPlatformService.retrieveRescheduleStrategyTypeOptions(); final List<EnumOptionData> interestRecalculationFrequencyTypeOptions = dropdownReadPlatformService .retrieveInterestRecalculationFrequencyTypeOptions(); final List<EnumOptionData> interestRecalculationNthDayTypeOptions = dropdownReadPlatformService .retrieveInterestRecalculationNthDayTypeOptions(); final List<EnumOptionData> interestRecalculationDayOfWeekTypeOptions = dropdownReadPlatformService .retrieveInterestRecalculationDayOfWeekTypeOptions(); final List<EnumOptionData> preCloseInterestCalculationStrategyOptions = dropdownReadPlatformService .retrievePreCloseInterestCalculationStrategyOptions(); final List<FloatingRateData> floatingRateOptions = this.floatingRateReadPlatformService.retrieveLookupActive(); final List<EnumOptionData> repaymentStartDateTypeOptions = dropdownReadPlatformService.retrieveRepaymentStartDateTypeOptions(); final List<EnumOptionData> advancedPaymentAllocationTransactionTypes = PaymentAllocationTransactionType .getValuesAsEnumOptionDataList(); final List<EnumOptionData> advancedPaymentAllocationFutureInstallmentAllocationRules = FutureInstallmentAllocationRule .getValuesAsEnumOptionDataList(); final List<EnumOptionData> advancedPaymentAllocationTypes = PaymentAllocationType.getValuesAsEnumOptionDataList(); final List<EnumOptionData> creditAllocationTransactionTypes = CreditAllocationTransactionType.getValuesAsEnumOptionDataList(); final List<EnumOptionData> creditAllocationAllocationTypes = AllocationType.getValuesAsEnumOptionDataList(); final List<StringEnumOptionData> supportedInterestRefundTypesOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanSupportedInterestRefundTypes.class); final List<StringEnumOptionData> chargeOffBehaviourOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanChargeOffBehaviour.class); final List<CodeValueData> chargeOffReasonOptions = codeValueReadPlatformService .retrieveCodeValuesByCode(LoanApiConstants.CHARGE_OFF_REASONS); final List<StringEnumOptionData> daysInYearCustomStrategyOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(DaysInYearCustomStrategyType.class); final List<StringEnumOptionData> capitalizedIncomeCalculationTypeOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanCapitalizedIncomeCalculationType.class); final List<StringEnumOptionData> capitalizedIncomeStrategyOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanCapitalizedIncomeStrategy.class); final List<StringEnumOptionData> capitalizedIncomeTypeOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanCapitalizedIncomeType.class); final List<StringEnumOptionData> buyDownFeeCalculationTypeOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanBuyDownFeeCalculationType.class); final List<StringEnumOptionData> buyDownFeeStrategyOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanBuyDownFeeStrategy.class); final List<StringEnumOptionData> buyDownFeeIncomeTypeOptions = ApiFacingEnum .getValuesAsStringEnumOptionDataList(LoanBuyDownFeeIncomeType.class); final List<CodeValueData> writeOffReasonOptions = codeValueReadPlatformService .retrieveCodeValuesByCode(LoanApiConstants.WRITEOFFREASONS); final List<CodeValueData> capitalizedIncomeClassificationOptions = codeValueReadPlatformService .retrieveCodeValuesByCode(LoanTransactionApiConstants.CAPITALIZED_INCOME_CLASSIFICATION_CODE); final List<CodeValueData> buydownFeeClassificationOptions = codeValueReadPlatformService .retrieveCodeValuesByCode(LoanTransactionApiConstants.BUY_DOWN_FEE_CLASSIFICATION_CODE); return new LoanProductData(productData, chargeOptions, penaltyOptions, paymentTypeOptions, currencyOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, repaymentFrequencyTypeOptions, interestRateFrequencyTypeOptions, fundOptions, transactionProcessingStrategyOptions, rateOptions, accountOptions, accountingRuleTypeOptions, loanCycleValueConditionTypeOptions, daysInMonthTypeOptions, daysInYearTypeOptions, interestRecalculationCompoundingTypeOptions, rescheduleStrategyTypeOptions, interestRecalculationFrequencyTypeOptions, preCloseInterestCalculationStrategyOptions, floatingRateOptions, interestRecalculationNthDayTypeOptions, interestRecalculationDayOfWeekTypeOptions, isRatesEnabled, delinquencyBucketOptions, repaymentStartDateTypeOptions, advancedPaymentAllocationTransactionTypes, advancedPaymentAllocationFutureInstallmentAllocationRules, advancedPaymentAllocationTypes, LoanScheduleType.getValuesAsEnumOptionDataList(), LoanScheduleProcessingType.getValuesAsEnumOptionDataList(), creditAllocationTransactionTypes, creditAllocationAllocationTypes, supportedInterestRefundTypesOptions, chargeOffBehaviourOptions, chargeOffReasonOptions, daysInYearCustomStrategyOptions, capitalizedIncomeCalculationTypeOptions, capitalizedIncomeStrategyOptions, capitalizedIncomeTypeOptions, buyDownFeeCalculationTypeOptions, buyDownFeeStrategyOptions, buyDownFeeIncomeTypeOptions, writeOffReasonOptions, capitalizedIncomeClassificationOptions, buydownFeeClassificationOptions); } }
apache/skywalking-java
37,988
apm-sniffer/apm-sdk-plugin/jdbc-commons/src/test/java/org/apache/skywalking/apm/plugin/jdbc/SWCallableStatementTest.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.skywalking.apm.plugin.jdbc; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyByte; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyFloat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyShort; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.NClob; import java.sql.Ref; import java.sql.ResultSet; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Properties; import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan; import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity; import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment; import org.apache.skywalking.apm.agent.test.helper.SegmentHelper; import org.apache.skywalking.apm.agent.test.helper.SpanHelper; import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule; import org.apache.skywalking.apm.agent.test.tools.SegmentStorage; import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint; import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import com.mysql.cj.api.jdbc.JdbcConnection; @RunWith(TracingSegmentRunner.class) public class SWCallableStatementTest extends AbstractStatementTest { @SegmentStoragePoint private SegmentStorage segmentStorage; @Rule public AgentServiceRule serviceRule = new AgentServiceRule(); @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private Array array; @Mock private SQLXML sqlxml; @Mock private RowId rowId; @Mock private Ref ref; @Mock private Clob clob; @Mock private NClob nClob; @Mock private Reader reader; @Mock private InputStream inputStream; @Mock private Blob blob; @Mock private com.mysql.cj.jdbc.CallableStatement mysqlCallableStatement; @Mock private JdbcConnection jdbcConnection; private SWConnection swConnection; private SWConnection multiHostConnection; private byte[] bytesParam = new byte[] { 1, 2 }; @Before public void setUp() throws Exception { swConnection = new SWConnection("jdbc:mysql://127.0.0.1:3306/test", new Properties(), jdbcConnection); multiHostConnection = new SWConnection("jdbc:mysql://127.0.0.1:3306,127.0.0.1:3309/test", new Properties(), jdbcConnection); when(jdbcConnection.prepareCall(anyString())).thenReturn(mysqlCallableStatement); when(jdbcConnection.prepareCall(anyString(), anyInt(), anyInt(), anyInt())).thenReturn(mysqlCallableStatement); when(jdbcConnection.prepareCall(anyString(), anyInt(), anyInt())).thenReturn(mysqlCallableStatement); } @Test public void testSetParam() throws SQLException, MalformedURLException { CallableStatement callableStatement = multiHostConnection.prepareCall("SELECT * FROM test WHERE a = ? OR b = ? OR c=? OR d = ? OR e = ?" + " OR e = ? OR f = ? OR g = ? OR h = ? OR i = ? OR j = ? OR k = ? OR l = ? OR m = ? OR n = ? OR o = ? OR p = ? " + " OR r = ? OR s = ? OR t = ? OR u = ? OR v = ? OR w = ? OR x = ? OR y = ? OR z = ? OR a1 = ? OR a2 = ? OR a3 = ?" + " OR a4 = ? OR a5 = ? OR a6 = ? OR a7 = ? OR a8 = ? OR a9 = ? OR b1 = ? OR b2 = ? OR b3 = ? OR b4 = ? OR b5 = ?" + " OR b6 = ? OR b7 = ? OR b8 = ? OR b9 = ? OR c1 = ? OR c2 = ? OR c3 = ?"); callableStatement.clearParameters(); callableStatement.setAsciiStream(1, inputStream); callableStatement.setAsciiStream(2, inputStream, 10); callableStatement.setAsciiStream(3, inputStream, 1000000L); callableStatement.setCharacterStream(4, reader); callableStatement.setCharacterStream(4, reader, 10); callableStatement.setCharacterStream(5, reader, 10L); callableStatement.setShort(6, (short) 12); callableStatement.setInt(7, 1); callableStatement.setString(8, "test"); callableStatement.setBoolean(9, true); callableStatement.setLong(10, 100L); callableStatement.setDouble(11, 12.0); callableStatement.setFloat(12, 12.0f); callableStatement.setByte(13, (byte) 1); callableStatement.setBytes(14, bytesParam); callableStatement.setDate(15, new Date(System.currentTimeMillis())); callableStatement.setNull(16, 1); callableStatement.setNull(17, 1, "test"); callableStatement.setBigDecimal(18, new BigDecimal(10000)); callableStatement.setBlob(19, inputStream); callableStatement.setBlob(20, inputStream, 1000000L); callableStatement.setClob(21, clob); callableStatement.setClob(22, reader); callableStatement.setClob(23, reader, 100L); callableStatement.setNString(24, "test"); callableStatement.setNCharacterStream(25, reader); callableStatement.setNCharacterStream(26, reader, 1); callableStatement.setNClob(27, nClob); callableStatement.setNClob(28, reader, 1); callableStatement.setObject(29, new Object()); callableStatement.setObject(30, new Object(), 1); callableStatement.setObject(31, new Object(), 1, 1); callableStatement.setRef(32, ref); callableStatement.setRowId(33, rowId); callableStatement.setSQLXML(34, sqlxml); callableStatement.setTime(35, new Time(System.currentTimeMillis())); callableStatement.setTimestamp(36, new Timestamp(System.currentTimeMillis())); callableStatement.setTimestamp(37, new Timestamp(System.currentTimeMillis()), Calendar.getInstance()); callableStatement.setURL(38, new URL("http", "127.0.0.1", "test")); callableStatement.setBinaryStream(39, inputStream); callableStatement.setBinaryStream(40, inputStream, 1); callableStatement.setBinaryStream(41, inputStream, 1L); callableStatement.setNClob(42, reader); callableStatement.setTime(43, new Time(System.currentTimeMillis()), Calendar.getInstance()); callableStatement.setArray(45, array); callableStatement.setBlob(46, blob); callableStatement.setDate(47, new Date(System.currentTimeMillis()), Calendar.getInstance()); callableStatement.getCharacterStream(4); callableStatement.getCharacterStream("d"); callableStatement.getShort(6); callableStatement.getShort("g"); callableStatement.getInt(7); callableStatement.getInt("h"); callableStatement.getString(8); callableStatement.getString("i"); callableStatement.getBoolean(9); callableStatement.getBoolean("j"); callableStatement.getLong(10); callableStatement.getLong("k"); callableStatement.getDouble(11); callableStatement.getDouble("l"); callableStatement.getFloat(12); callableStatement.getFloat("m"); callableStatement.getByte(13); callableStatement.getByte("n"); callableStatement.getBytes(14); callableStatement.getBytes("o"); callableStatement.getDate(15); callableStatement.getDate("p"); callableStatement.getBigDecimal(18); callableStatement.getBigDecimal("s"); callableStatement.getBlob(19); callableStatement.getBlob("t"); callableStatement.getClob(21); callableStatement.getClob(21); callableStatement.getClob("u"); callableStatement.getNString(24); callableStatement.getNString("y"); callableStatement.getNCharacterStream(25); callableStatement.getNCharacterStream("z"); callableStatement.getNClob(27); callableStatement.getNClob("a1"); callableStatement.getRef(32); callableStatement.getRef("a2"); callableStatement.getRowId(33); callableStatement.getRowId("a7"); callableStatement.getSQLXML(34); callableStatement.getSQLXML("a8"); callableStatement.getTime(35); callableStatement.getTime("a9"); callableStatement.getTimestamp(36); callableStatement.getTimestamp("b1"); callableStatement.getURL(38); callableStatement.getURL("b3"); callableStatement.getArray(45); callableStatement.getArray("c4"); callableStatement.getDate(15); callableStatement.getDate("p"); callableStatement.getDate(15, Calendar.getInstance()); callableStatement.getDate("p", Calendar.getInstance()); callableStatement.getTime("a9"); callableStatement.getTime("a9", Calendar.getInstance()); callableStatement.getTime(43); callableStatement.getTime(43, Calendar.getInstance()); callableStatement.getTimestamp("p", Calendar.getInstance()); callableStatement.getTimestamp(36, Calendar.getInstance()); callableStatement.getObject(29); callableStatement.getObject(29, new HashMap<String, Class<?>>()); callableStatement.getObject("a4"); callableStatement.getObject("a4", new HashMap<String, Class<?>>()); callableStatement.getBigDecimal(18, 1); callableStatement.wasNull(); callableStatement.setAsciiStream("a", inputStream); callableStatement.setAsciiStream("b", inputStream, 10); callableStatement.setAsciiStream("c", inputStream, 1000000L); callableStatement.setCharacterStream("d", reader); callableStatement.setCharacterStream("e", reader, 10); callableStatement.setCharacterStream("f", reader, 10L); callableStatement.setShort("g", (short) 12); callableStatement.setInt("h", 1); callableStatement.setString("i", "test"); callableStatement.setBoolean("j", true); callableStatement.setLong("k", 100L); callableStatement.setDouble("l", 12.0); callableStatement.setFloat("m", 12.0f); callableStatement.setByte("n", (byte) 1); callableStatement.setBytes("o", bytesParam); callableStatement.setDate("p", new Date(System.currentTimeMillis())); callableStatement.setNull("q", 1); callableStatement.setNull("r", 1, "test"); callableStatement.setBigDecimal("s", new BigDecimal(10000)); callableStatement.setBlob("t", inputStream); callableStatement.setBlob("u", inputStream, 1000000L); callableStatement.setClob("v", clob); callableStatement.setClob("w", reader); callableStatement.setClob("x", reader, 100L); callableStatement.setNString("y", "test"); callableStatement.setNCharacterStream("z", reader); callableStatement.setNCharacterStream("a1", reader, 1); callableStatement.setNClob("a2", nClob); callableStatement.setNClob("a3", reader, 1); callableStatement.setObject("a4", new Object()); callableStatement.setObject("a5", new Object(), 1); callableStatement.setObject("a6", new Object(), 1, 1); callableStatement.setRowId("a7", rowId); callableStatement.setSQLXML("a8", sqlxml); callableStatement.setTime("a9", new Time(System.currentTimeMillis())); callableStatement.setTimestamp("b1", new Timestamp(System.currentTimeMillis())); callableStatement.setTimestamp("b2", new Timestamp(System.currentTimeMillis()), Calendar.getInstance()); callableStatement.setURL("b3", new URL("http", "127.0.0.1", "test")); callableStatement.setBinaryStream("b4", inputStream); callableStatement.setBinaryStream("b5", inputStream, 1); callableStatement.setBinaryStream("b6", inputStream, 1L); callableStatement.setNClob("b7", reader); callableStatement.setTime("b8", new Time(System.currentTimeMillis()), Calendar.getInstance()); callableStatement.setBlob("c1", blob); callableStatement.setDate("c2", new Date(System.currentTimeMillis()), Calendar.getInstance()); callableStatement.registerOutParameter("c4", 1); callableStatement.registerOutParameter("c5", 1, 1); callableStatement.registerOutParameter("c6", 1, "test"); callableStatement.registerOutParameter(48, 1); callableStatement.registerOutParameter(49, 1, 1); callableStatement.registerOutParameter(50, 1, "test"); ResultSet resultSet = callableStatement.executeQuery(); callableStatement.close(); verify(mysqlCallableStatement).clearParameters(); verify(mysqlCallableStatement).executeQuery(); verify(mysqlCallableStatement).close(); verify(mysqlCallableStatement).setAsciiStream(anyInt(), any(InputStream.class)); verify(mysqlCallableStatement).setAsciiStream(anyInt(), any(InputStream.class), anyInt()); verify(mysqlCallableStatement).setAsciiStream(anyInt(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setCharacterStream(anyInt(), any(Reader.class)); verify(mysqlCallableStatement).setCharacterStream(anyInt(), any(Reader.class), anyInt()); verify(mysqlCallableStatement).setCharacterStream(anyInt(), any(Reader.class), anyLong()); verify(mysqlCallableStatement).setShort(anyInt(), anyShort()); verify(mysqlCallableStatement).setInt(anyInt(), anyInt()); verify(mysqlCallableStatement).setString(anyInt(), anyString()); verify(mysqlCallableStatement).setBoolean(anyInt(), anyBoolean()); verify(mysqlCallableStatement).setLong(anyInt(), anyLong()); verify(mysqlCallableStatement).setDouble(anyInt(), anyDouble()); verify(mysqlCallableStatement).setFloat(anyInt(), anyFloat()); verify(mysqlCallableStatement).setByte(anyInt(), anyByte()); verify(mysqlCallableStatement).setBytes(14, bytesParam); verify(mysqlCallableStatement).setDate(anyInt(), any(Date.class)); verify(mysqlCallableStatement).setNull(anyInt(), anyInt()); verify(mysqlCallableStatement).setNull(anyInt(), anyInt(), anyString()); verify(mysqlCallableStatement).setBigDecimal(anyInt(), any(BigDecimal.class)); verify(mysqlCallableStatement).setBlob(anyInt(), any(InputStream.class)); verify(mysqlCallableStatement).setBlob(anyInt(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setClob(anyInt(), any(Clob.class)); verify(mysqlCallableStatement).setClob(anyInt(), any(Reader.class)); verify(mysqlCallableStatement).setClob(anyInt(), any(Reader.class), anyLong()); verify(mysqlCallableStatement).setNString(anyInt(), anyString()); verify(mysqlCallableStatement).setNCharacterStream(anyInt(), any(Reader.class)); verify(mysqlCallableStatement).setNCharacterStream(anyInt(), any(Reader.class), anyLong()); verify(mysqlCallableStatement).setNClob(27, nClob); verify(mysqlCallableStatement).setNClob(28, reader, 1); verify(mysqlCallableStatement).setObject(anyInt(), any()); verify(mysqlCallableStatement).setObject(anyInt(), any(), anyInt()); verify(mysqlCallableStatement).setObject(anyInt(), any(), anyInt(), anyInt()); verify(mysqlCallableStatement).setRef(anyInt(), any(Ref.class)); verify(mysqlCallableStatement).setRowId(anyInt(), any(RowId.class)); verify(mysqlCallableStatement).setSQLXML(anyInt(), any(SQLXML.class)); verify(mysqlCallableStatement).setTime(anyInt(), any(Time.class)); verify(mysqlCallableStatement).setTimestamp(anyInt(), any(Timestamp.class)); verify(mysqlCallableStatement).setTimestamp(anyInt(), any(Timestamp.class), any(Calendar.class)); verify(mysqlCallableStatement).setURL(anyInt(), any(URL.class)); verify(mysqlCallableStatement).setBinaryStream(anyInt(), any(InputStream.class)); verify(mysqlCallableStatement).setBinaryStream(anyInt(), any(InputStream.class), anyInt()); verify(mysqlCallableStatement).setBinaryStream(anyInt(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setNClob(42, reader); verify(mysqlCallableStatement).setTime(anyInt(), any(Time.class), any(Calendar.class)); verify(mysqlCallableStatement).setTimestamp(anyInt(), any(Timestamp.class), any(Calendar.class)); verify(mysqlCallableStatement).setArray(anyInt(), any(Array.class)); verify(mysqlCallableStatement).setBlob(anyInt(), any(Blob.class)); verify(mysqlCallableStatement).setDate(anyInt(), any(Date.class), any(Calendar.class)); verify(mysqlCallableStatement).clearParameters(); verify(mysqlCallableStatement).executeQuery(); verify(mysqlCallableStatement).close(); verify(mysqlCallableStatement).setAsciiStream(anyString(), any(InputStream.class)); verify(mysqlCallableStatement).setAsciiStream(anyString(), any(InputStream.class), anyInt()); verify(mysqlCallableStatement).setAsciiStream(anyString(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setCharacterStream(anyString(), any(Reader.class)); verify(mysqlCallableStatement).setCharacterStream(anyString(), any(Reader.class), anyInt()); verify(mysqlCallableStatement).setCharacterStream(anyString(), any(Reader.class), anyLong()); verify(mysqlCallableStatement).setShort(anyString(), anyShort()); verify(mysqlCallableStatement).setInt(anyString(), anyInt()); verify(mysqlCallableStatement).setString(anyString(), anyString()); verify(mysqlCallableStatement).setBoolean(anyString(), anyBoolean()); verify(mysqlCallableStatement).setLong(anyString(), anyLong()); verify(mysqlCallableStatement).setDouble(anyString(), anyDouble()); verify(mysqlCallableStatement).setFloat(anyString(), anyFloat()); verify(mysqlCallableStatement).setByte(anyString(), anyByte()); verify(mysqlCallableStatement).setBytes(14, bytesParam); verify(mysqlCallableStatement).setDate(anyString(), any(Date.class)); verify(mysqlCallableStatement).setNull(anyString(), anyInt()); verify(mysqlCallableStatement).setNull(anyString(), anyInt(), anyString()); verify(mysqlCallableStatement).setBigDecimal(anyString(), any(BigDecimal.class)); verify(mysqlCallableStatement).setBlob(anyString(), any(InputStream.class)); verify(mysqlCallableStatement).setBlob(anyString(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setClob(anyString(), any(Clob.class)); verify(mysqlCallableStatement).setClob(anyString(), any(Reader.class)); verify(mysqlCallableStatement).setClob(anyString(), any(Reader.class), anyLong()); verify(mysqlCallableStatement).setNString(anyString(), anyString()); verify(mysqlCallableStatement).setNCharacterStream(anyString(), any(Reader.class)); verify(mysqlCallableStatement).setNCharacterStream(anyString(), any(Reader.class), anyLong()); verify(mysqlCallableStatement).setNClob(27, nClob); verify(mysqlCallableStatement).setNClob(28, reader, 1); verify(mysqlCallableStatement).setObject(anyString(), any()); verify(mysqlCallableStatement).setObject(anyString(), any(), anyInt()); verify(mysqlCallableStatement).setObject(anyString(), any(), anyInt(), anyInt()); verify(mysqlCallableStatement).setRowId(anyString(), any(RowId.class)); verify(mysqlCallableStatement).setSQLXML(anyString(), any(SQLXML.class)); verify(mysqlCallableStatement).setTime(anyString(), any(Time.class)); verify(mysqlCallableStatement).setTimestamp(anyString(), any(Timestamp.class)); verify(mysqlCallableStatement).setTimestamp(anyString(), any(Timestamp.class), any(Calendar.class)); verify(mysqlCallableStatement).setURL(anyString(), any(URL.class)); verify(mysqlCallableStatement).setBinaryStream(anyString(), any(InputStream.class)); verify(mysqlCallableStatement).setBinaryStream(anyString(), any(InputStream.class), anyInt()); verify(mysqlCallableStatement).setBinaryStream(anyString(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setNClob(42, reader); verify(mysqlCallableStatement).setTime(anyString(), any(Time.class), any(Calendar.class)); verify(mysqlCallableStatement).setTimestamp(anyString(), any(Timestamp.class), any(Calendar.class)); verify(mysqlCallableStatement).setBlob(anyString(), any(Blob.class)); verify(mysqlCallableStatement).setDate(anyString(), any(Date.class), any(Calendar.class)); } @Test public void testCallableStatementConfig() throws SQLException { CallableStatement callableStatement = swConnection.prepareCall("INSERT INTO test VALUES( ? , ?)", 1, 1); callableStatement.setInt(1, 1); callableStatement.setString(2, "a"); callableStatement.getUpdateCount(); callableStatement.setFetchDirection(1); callableStatement.getFetchDirection(); callableStatement.getResultSetConcurrency(); callableStatement.getResultSetType(); callableStatement.isClosed(); callableStatement.setPoolable(false); callableStatement.isPoolable(); callableStatement.getWarnings(); callableStatement.clearWarnings(); callableStatement.setCursorName("test"); callableStatement.setMaxFieldSize(11); callableStatement.getMaxFieldSize(); callableStatement.setMaxRows(10); callableStatement.getMaxRows(); callableStatement.getParameterMetaData(); callableStatement.setEscapeProcessing(true); callableStatement.setFetchSize(1); callableStatement.getFetchSize(); callableStatement.setQueryTimeout(1); callableStatement.getQueryTimeout(); Connection connection = callableStatement.getConnection(); callableStatement.execute(); callableStatement.getMoreResults(); callableStatement.getMoreResults(1); callableStatement.getResultSetHoldability(); callableStatement.getMetaData(); callableStatement.getResultSet(); callableStatement.close(); verify(mysqlCallableStatement).getUpdateCount(); verify(mysqlCallableStatement).getMoreResults(); verify(mysqlCallableStatement).setFetchDirection(anyInt()); verify(mysqlCallableStatement).getFetchDirection(); verify(mysqlCallableStatement).getResultSetType(); verify(mysqlCallableStatement).isClosed(); verify(mysqlCallableStatement).setPoolable(anyBoolean()); verify(mysqlCallableStatement).getWarnings(); verify(mysqlCallableStatement).clearWarnings(); verify(mysqlCallableStatement).setCursorName(anyString()); verify(mysqlCallableStatement).setMaxFieldSize(anyInt()); verify(mysqlCallableStatement).getMaxFieldSize(); verify(mysqlCallableStatement).setMaxRows(anyInt()); verify(mysqlCallableStatement).getMaxRows(); verify(mysqlCallableStatement).setEscapeProcessing(anyBoolean()); verify(mysqlCallableStatement).getResultSetConcurrency(); verify(mysqlCallableStatement).getResultSetConcurrency(); verify(mysqlCallableStatement).getResultSetType(); verify(mysqlCallableStatement).getMetaData(); verify(mysqlCallableStatement).getParameterMetaData(); verify(mysqlCallableStatement).getMoreResults(anyInt()); verify(mysqlCallableStatement).setFetchSize(anyInt()); verify(mysqlCallableStatement).getFetchSize(); verify(mysqlCallableStatement).getQueryTimeout(); verify(mysqlCallableStatement).setQueryTimeout(anyInt()); verify(mysqlCallableStatement).getResultSet(); assertThat(connection, CoreMatchers.<Connection>is(swConnection)); } @Test public void testExecuteQuery() throws SQLException { CallableStatement callableStatement = swConnection.prepareCall("SELECT * FROM test", 1, 1, 1); ResultSet resultSet = callableStatement.executeQuery(); callableStatement.close(); verify(mysqlCallableStatement).executeQuery(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeQuery", "SELECT * FROM test"); } @Test public void testQuerySqlWithSql() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("SELECT * FROM test", 1, 1); ResultSet resultSet = preparedStatement.executeQuery("SELECT * FROM test"); preparedStatement.getGeneratedKeys(); preparedStatement.close(); verify(mysqlCallableStatement).executeQuery(anyString()); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeQuery", "SELECT * FROM test"); } @Test public void testInsertWithAutoGeneratedKey() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("INSERT INTO test VALUES(?)"); boolean insertCount = preparedStatement.execute("INSERT INTO test VALUES(1)", 1); preparedStatement.close(); verify(mysqlCallableStatement).execute(anyString(), anyInt()); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/execute", "INSERT INTO test VALUES(1)"); } @Test public void testInsertWithIntColumnIndexes() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("INSERT INTO test VALUES(?)"); boolean insertCount = preparedStatement.execute("INSERT INTO test VALUES(1)", new int[] { 1, 2 }); preparedStatement.close(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/execute", "INSERT INTO test VALUES(1)"); } @Test public void testInsertWithStringColumnIndexes() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("INSERT INTO test VALUES(?)"); boolean insertCount = preparedStatement.execute("INSERT INTO test VALUES(1)", new String[] { "1", "2" }); preparedStatement.close(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/execute", "INSERT INTO test VALUES(1)"); } @Test public void testExecute() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("UPDATE test SET a = ?"); preparedStatement.setString(1, "a"); boolean updateCount = preparedStatement.execute("UPDATE test SET a = 1"); preparedStatement.cancel(); preparedStatement.close(); verify(mysqlCallableStatement).execute(anyString()); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/execute", "UPDATE test SET a = 1"); } @Test public void testExecuteUpdate() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("UPDATE test SET a = ?"); preparedStatement.setString(1, "a"); int updateCount = preparedStatement.executeUpdate(); preparedStatement.cancel(); preparedStatement.close(); verify(mysqlCallableStatement).executeUpdate(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeUpdate", "UPDATE test SET a = ?"); } @Test public void testUpdateSql() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("UPDATE test SET a = ?"); int updateCount = preparedStatement.executeUpdate("UPDATE test SET a = 1"); preparedStatement.cancel(); preparedStatement.close(); verify(mysqlCallableStatement).executeUpdate(anyString()); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeUpdate", "UPDATE test SET a = 1"); } @Test public void testUpdateWithAutoGeneratedKey() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("UPDATE test SET a = ?"); int updateCount = preparedStatement.executeUpdate("UPDATE test SET a = 1", 1); preparedStatement.cancel(); preparedStatement.close(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeUpdate", "UPDATE test SET a = 1"); } @Test public void testUpdateWithIntColumnIndexes() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("UPDATE test SET a = ?"); int updateCount = preparedStatement.executeUpdate("UPDATE test SET a = 1", new int[] {1}); preparedStatement.cancel(); preparedStatement.close(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeUpdate", "UPDATE test SET a = 1"); } @Test public void testUpdateWithStringColumnIndexes() throws SQLException { CallableStatement preparedStatement = swConnection.prepareCall("UPDATE test SET a = ?"); int updateCount = preparedStatement.executeUpdate("UPDATE test SET a = 1", new String[] {"1"}); preparedStatement.cancel(); preparedStatement.close(); verify(mysqlCallableStatement).close(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeUpdate", "UPDATE test SET a = 1"); } @Test public void testBatch() throws SQLException, MalformedURLException { CallableStatement preparedStatement = multiHostConnection.prepareCall("UPDATE test SET a = ? WHERE b = ?"); preparedStatement.setShort(1, (short) 12); preparedStatement.setTime(2, new Time(System.currentTimeMillis())); preparedStatement.addBatch(); int[] resultSet = preparedStatement.executeBatch(); preparedStatement.clearBatch(); verify(mysqlCallableStatement).executeBatch(); verify(mysqlCallableStatement).addBatch(); verify(mysqlCallableStatement).clearBatch(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeBatch", ""); } @Test public void testQueryWithMultiHost() throws SQLException { CallableStatement preparedStatement = multiHostConnection.prepareCall("SELECT * FROM test WHERE a = ? OR b = ? OR c=? OR d = ?", 1, 1); preparedStatement.setAsciiStream(1, inputStream); preparedStatement.setAsciiStream(2, inputStream, 10); preparedStatement.setAsciiStream(3, inputStream, 1000000L); preparedStatement.setCharacterStream(4, reader); ResultSet resultSet = preparedStatement.executeQuery(); preparedStatement.close(); verify(mysqlCallableStatement).executeQuery(); verify(mysqlCallableStatement).close(); } @Test(expected = SQLException.class) public void testMultiHostWithException() throws SQLException { when(mysqlCallableStatement.executeQuery()).thenThrow(new SQLException()); try { CallableStatement preparedStatement = multiHostConnection.prepareCall("SELECT * FROM test WHERE a = ? OR b = ? OR c=? OR d = ? OR e=?"); preparedStatement.setBigDecimal(1, new BigDecimal(10000)); preparedStatement.setBlob(2, inputStream); preparedStatement.setBlob(3, inputStream, 1000000L); preparedStatement.setByte(3, (byte) 1); preparedStatement.setBytes(4, bytesParam); preparedStatement.setLong(5, 100L); ResultSet resultSet = preparedStatement.executeQuery(); preparedStatement.close(); } finally { verify(mysqlCallableStatement).executeQuery(); verify(mysqlCallableStatement, times(0)).close(); verify(mysqlCallableStatement).setBigDecimal(anyInt(), any(BigDecimal.class)); verify(mysqlCallableStatement).setBlob(anyInt(), any(InputStream.class)); verify(mysqlCallableStatement).setBlob(anyInt(), any(InputStream.class), anyLong()); verify(mysqlCallableStatement).setByte(anyInt(), anyByte()); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertThat(spans.size(), is(1)); assertDBSpan(spans.get(0), "Mysql/JDBC/CallableStatement/executeQuery", "SELECT * FROM test WHERE a = ? OR b = ? OR c=? OR d = ? OR e=?"); List<LogDataEntity> logs = SpanHelper.getLogs(spans.get(0)); Assert.assertThat(logs.size(), is(1)); assertDBSpanLog(logs.get(0)); } } }
googleapis/google-cloud-java
37,803
java-analyticshub/proto-google-cloud-analyticshub-v1/src/main/java/com/google/cloud/bigquery/analyticshub/v1/ListSubscriptionsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/analyticshub/v1/analyticshub.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.analyticshub.v1; /** * * * <pre> * Message for response to the listing of subscriptions. * </pre> * * Protobuf type {@code google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse} */ public final class ListSubscriptionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) ListSubscriptionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListSubscriptionsResponse.newBuilder() to construct. private ListSubscriptionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSubscriptionsResponse() { subscriptions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSubscriptionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_ListSubscriptionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_ListSubscriptionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse.class, com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse.Builder.class); } public static final int SUBSCRIPTIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.bigquery.analyticshub.v1.Subscription> subscriptions_; /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.bigquery.analyticshub.v1.Subscription> getSubscriptionsList() { return subscriptions_; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder> getSubscriptionsOrBuilderList() { return subscriptions_; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ @java.lang.Override public int getSubscriptionsCount() { return subscriptions_.size(); } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.Subscription getSubscriptions(int index) { return subscriptions_.get(index); } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder getSubscriptionsOrBuilder( int index) { return subscriptions_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * 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> * 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 < subscriptions_.size(); i++) { output.writeMessage(1, subscriptions_.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 < subscriptions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, subscriptions_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse)) { return super.equals(obj); } com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse other = (com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) obj; if (!getSubscriptionsList().equals(other.getSubscriptionsList())) 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 (getSubscriptionsCount() > 0) { hash = (37 * hash) + SUBSCRIPTIONS_FIELD_NUMBER; hash = (53 * hash) + getSubscriptionsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message for response to the listing of subscriptions. * </pre> * * Protobuf type {@code google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_ListSubscriptionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_ListSubscriptionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse.class, com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse.Builder.class); } // Construct using // com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (subscriptionsBuilder_ == null) { subscriptions_ = java.util.Collections.emptyList(); } else { subscriptions_ = null; subscriptionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_ListSubscriptionsResponse_descriptor; } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse getDefaultInstanceForType() { return com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse build() { com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse buildPartial() { com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse result = new com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse result) { if (subscriptionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { subscriptions_ = java.util.Collections.unmodifiableList(subscriptions_); bitField0_ = (bitField0_ & ~0x00000001); } result.subscriptions_ = subscriptions_; } else { result.subscriptions_ = subscriptionsBuilder_.build(); } } private void buildPartial0( com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) { return mergeFrom( (com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse other) { if (other == com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse .getDefaultInstance()) return this; if (subscriptionsBuilder_ == null) { if (!other.subscriptions_.isEmpty()) { if (subscriptions_.isEmpty()) { subscriptions_ = other.subscriptions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSubscriptionsIsMutable(); subscriptions_.addAll(other.subscriptions_); } onChanged(); } } else { if (!other.subscriptions_.isEmpty()) { if (subscriptionsBuilder_.isEmpty()) { subscriptionsBuilder_.dispose(); subscriptionsBuilder_ = null; subscriptions_ = other.subscriptions_; bitField0_ = (bitField0_ & ~0x00000001); subscriptionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSubscriptionsFieldBuilder() : null; } else { subscriptionsBuilder_.addAllMessages(other.subscriptions_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.bigquery.analyticshub.v1.Subscription m = input.readMessage( com.google.cloud.bigquery.analyticshub.v1.Subscription.parser(), extensionRegistry); if (subscriptionsBuilder_ == null) { ensureSubscriptionsIsMutable(); subscriptions_.add(m); } else { subscriptionsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.bigquery.analyticshub.v1.Subscription> subscriptions_ = java.util.Collections.emptyList(); private void ensureSubscriptionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { subscriptions_ = new java.util.ArrayList<com.google.cloud.bigquery.analyticshub.v1.Subscription>( subscriptions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.analyticshub.v1.Subscription, com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder, com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder> subscriptionsBuilder_; /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public java.util.List<com.google.cloud.bigquery.analyticshub.v1.Subscription> getSubscriptionsList() { if (subscriptionsBuilder_ == null) { return java.util.Collections.unmodifiableList(subscriptions_); } else { return subscriptionsBuilder_.getMessageList(); } } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public int getSubscriptionsCount() { if (subscriptionsBuilder_ == null) { return subscriptions_.size(); } else { return subscriptionsBuilder_.getCount(); } } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public com.google.cloud.bigquery.analyticshub.v1.Subscription getSubscriptions(int index) { if (subscriptionsBuilder_ == null) { return subscriptions_.get(index); } else { return subscriptionsBuilder_.getMessage(index); } } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder setSubscriptions( int index, com.google.cloud.bigquery.analyticshub.v1.Subscription value) { if (subscriptionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSubscriptionsIsMutable(); subscriptions_.set(index, value); onChanged(); } else { subscriptionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder setSubscriptions( int index, com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder builderForValue) { if (subscriptionsBuilder_ == null) { ensureSubscriptionsIsMutable(); subscriptions_.set(index, builderForValue.build()); onChanged(); } else { subscriptionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder addSubscriptions(com.google.cloud.bigquery.analyticshub.v1.Subscription value) { if (subscriptionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSubscriptionsIsMutable(); subscriptions_.add(value); onChanged(); } else { subscriptionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder addSubscriptions( int index, com.google.cloud.bigquery.analyticshub.v1.Subscription value) { if (subscriptionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSubscriptionsIsMutable(); subscriptions_.add(index, value); onChanged(); } else { subscriptionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder addSubscriptions( com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder builderForValue) { if (subscriptionsBuilder_ == null) { ensureSubscriptionsIsMutable(); subscriptions_.add(builderForValue.build()); onChanged(); } else { subscriptionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder addSubscriptions( int index, com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder builderForValue) { if (subscriptionsBuilder_ == null) { ensureSubscriptionsIsMutable(); subscriptions_.add(index, builderForValue.build()); onChanged(); } else { subscriptionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder addAllSubscriptions( java.lang.Iterable<? extends com.google.cloud.bigquery.analyticshub.v1.Subscription> values) { if (subscriptionsBuilder_ == null) { ensureSubscriptionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, subscriptions_); onChanged(); } else { subscriptionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder clearSubscriptions() { if (subscriptionsBuilder_ == null) { subscriptions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { subscriptionsBuilder_.clear(); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public Builder removeSubscriptions(int index) { if (subscriptionsBuilder_ == null) { ensureSubscriptionsIsMutable(); subscriptions_.remove(index); onChanged(); } else { subscriptionsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder getSubscriptionsBuilder( int index) { return getSubscriptionsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder getSubscriptionsOrBuilder(int index) { if (subscriptionsBuilder_ == null) { return subscriptions_.get(index); } else { return subscriptionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public java.util.List<? extends com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder> getSubscriptionsOrBuilderList() { if (subscriptionsBuilder_ != null) { return subscriptionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(subscriptions_); } } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder addSubscriptionsBuilder() { return getSubscriptionsFieldBuilder() .addBuilder(com.google.cloud.bigquery.analyticshub.v1.Subscription.getDefaultInstance()); } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder addSubscriptionsBuilder( int index) { return getSubscriptionsFieldBuilder() .addBuilder( index, com.google.cloud.bigquery.analyticshub.v1.Subscription.getDefaultInstance()); } /** * * * <pre> * The list of subscriptions. * </pre> * * <code>repeated .google.cloud.bigquery.analyticshub.v1.Subscription subscriptions = 1;</code> */ public java.util.List<com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder> getSubscriptionsBuilderList() { return getSubscriptionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.analyticshub.v1.Subscription, com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder, com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder> getSubscriptionsFieldBuilder() { if (subscriptionsBuilder_ == null) { subscriptionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.analyticshub.v1.Subscription, com.google.cloud.bigquery.analyticshub.v1.Subscription.Builder, com.google.cloud.bigquery.analyticshub.v1.SubscriptionOrBuilder>( subscriptions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); subscriptions_ = null; } return subscriptionsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * 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> * 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> * 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> * 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> * 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.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse) private static final com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse(); } public static com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSubscriptionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListSubscriptionsResponse>() { @java.lang.Override public ListSubscriptionsResponse 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<ListSubscriptionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSubscriptionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.ListSubscriptionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,814
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListRagCorporaResponse.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/vertex_rag_data_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Response message for * [VertexRagDataService.ListRagCorpora][google.cloud.aiplatform.v1beta1.VertexRagDataService.ListRagCorpora]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListRagCorporaResponse} */ public final class ListRagCorporaResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListRagCorporaResponse) ListRagCorporaResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListRagCorporaResponse.newBuilder() to construct. private ListRagCorporaResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListRagCorporaResponse() { ragCorpora_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListRagCorporaResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.VertexRagDataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListRagCorporaResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.VertexRagDataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListRagCorporaResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.class, com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.Builder.class); } public static final int RAG_CORPORA_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1beta1.RagCorpus> ragCorpora_; /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.RagCorpus> getRagCorporaList() { return ragCorpora_; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder> getRagCorporaOrBuilderList() { return ragCorpora_; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ @java.lang.Override public int getRagCorporaCount() { return ragCorpora_.size(); } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RagCorpus getRagCorpora(int index) { return ragCorpora_.get(index); } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder getRagCorporaOrBuilder(int index) { return ragCorpora_.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 * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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 * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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 < ragCorpora_.size(); i++) { output.writeMessage(1, ragCorpora_.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 < ragCorpora_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, ragCorpora_.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.ListRagCorporaResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse other = (com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse) obj; if (!getRagCorporaList().equals(other.getRagCorporaList())) 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 (getRagCorporaCount() > 0) { hash = (37 * hash) + RAG_CORPORA_FIELD_NUMBER; hash = (53 * hash) + getRagCorporaList().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.ListRagCorporaResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse 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.ListRagCorporaResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse 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.ListRagCorporaResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse 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.ListRagCorporaResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse 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.ListRagCorporaResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse 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.ListRagCorporaResponse 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.ListRagCorporaResponse 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.ListRagCorporaResponse 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 * [VertexRagDataService.ListRagCorpora][google.cloud.aiplatform.v1beta1.VertexRagDataService.ListRagCorpora]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListRagCorporaResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListRagCorporaResponse) com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.VertexRagDataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListRagCorporaResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.VertexRagDataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListRagCorporaResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.class, com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (ragCorporaBuilder_ == null) { ragCorpora_ = java.util.Collections.emptyList(); } else { ragCorpora_ = null; ragCorporaBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.VertexRagDataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListRagCorporaResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse build() { com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse buildPartial() { com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse result = new com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse result) { if (ragCorporaBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { ragCorpora_ = java.util.Collections.unmodifiableList(ragCorpora_); bitField0_ = (bitField0_ & ~0x00000001); } result.ragCorpora_ = ragCorpora_; } else { result.ragCorpora_ = ragCorporaBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse 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.ListRagCorporaResponse) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse other) { if (other == com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse.getDefaultInstance()) return this; if (ragCorporaBuilder_ == null) { if (!other.ragCorpora_.isEmpty()) { if (ragCorpora_.isEmpty()) { ragCorpora_ = other.ragCorpora_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureRagCorporaIsMutable(); ragCorpora_.addAll(other.ragCorpora_); } onChanged(); } } else { if (!other.ragCorpora_.isEmpty()) { if (ragCorporaBuilder_.isEmpty()) { ragCorporaBuilder_.dispose(); ragCorporaBuilder_ = null; ragCorpora_ = other.ragCorpora_; bitField0_ = (bitField0_ & ~0x00000001); ragCorporaBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRagCorporaFieldBuilder() : null; } else { ragCorporaBuilder_.addAllMessages(other.ragCorpora_); } } } 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.RagCorpus m = input.readMessage( com.google.cloud.aiplatform.v1beta1.RagCorpus.parser(), extensionRegistry); if (ragCorporaBuilder_ == null) { ensureRagCorporaIsMutable(); ragCorpora_.add(m); } else { ragCorporaBuilder_.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.RagCorpus> ragCorpora_ = java.util.Collections.emptyList(); private void ensureRagCorporaIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { ragCorpora_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.RagCorpus>(ragCorpora_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RagCorpus, com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder, com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder> ragCorporaBuilder_; /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.RagCorpus> getRagCorporaList() { if (ragCorporaBuilder_ == null) { return java.util.Collections.unmodifiableList(ragCorpora_); } else { return ragCorporaBuilder_.getMessageList(); } } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public int getRagCorporaCount() { if (ragCorporaBuilder_ == null) { return ragCorpora_.size(); } else { return ragCorporaBuilder_.getCount(); } } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.RagCorpus getRagCorpora(int index) { if (ragCorporaBuilder_ == null) { return ragCorpora_.get(index); } else { return ragCorporaBuilder_.getMessage(index); } } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder setRagCorpora(int index, com.google.cloud.aiplatform.v1beta1.RagCorpus value) { if (ragCorporaBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRagCorporaIsMutable(); ragCorpora_.set(index, value); onChanged(); } else { ragCorporaBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder setRagCorpora( int index, com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder builderForValue) { if (ragCorporaBuilder_ == null) { ensureRagCorporaIsMutable(); ragCorpora_.set(index, builderForValue.build()); onChanged(); } else { ragCorporaBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder addRagCorpora(com.google.cloud.aiplatform.v1beta1.RagCorpus value) { if (ragCorporaBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRagCorporaIsMutable(); ragCorpora_.add(value); onChanged(); } else { ragCorporaBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder addRagCorpora(int index, com.google.cloud.aiplatform.v1beta1.RagCorpus value) { if (ragCorporaBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRagCorporaIsMutable(); ragCorpora_.add(index, value); onChanged(); } else { ragCorporaBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder addRagCorpora( com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder builderForValue) { if (ragCorporaBuilder_ == null) { ensureRagCorporaIsMutable(); ragCorpora_.add(builderForValue.build()); onChanged(); } else { ragCorporaBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder addRagCorpora( int index, com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder builderForValue) { if (ragCorporaBuilder_ == null) { ensureRagCorporaIsMutable(); ragCorpora_.add(index, builderForValue.build()); onChanged(); } else { ragCorporaBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder addAllRagCorpora( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.RagCorpus> values) { if (ragCorporaBuilder_ == null) { ensureRagCorporaIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, ragCorpora_); onChanged(); } else { ragCorporaBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder clearRagCorpora() { if (ragCorporaBuilder_ == null) { ragCorpora_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { ragCorporaBuilder_.clear(); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public Builder removeRagCorpora(int index) { if (ragCorporaBuilder_ == null) { ensureRagCorporaIsMutable(); ragCorpora_.remove(index); onChanged(); } else { ragCorporaBuilder_.remove(index); } return this; } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder getRagCorporaBuilder(int index) { return getRagCorporaFieldBuilder().getBuilder(index); } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder getRagCorporaOrBuilder( int index) { if (ragCorporaBuilder_ == null) { return ragCorpora_.get(index); } else { return ragCorporaBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder> getRagCorporaOrBuilderList() { if (ragCorporaBuilder_ != null) { return ragCorporaBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(ragCorpora_); } } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder addRagCorporaBuilder() { return getRagCorporaFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1beta1.RagCorpus.getDefaultInstance()); } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder addRagCorporaBuilder(int index) { return getRagCorporaFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1beta1.RagCorpus.getDefaultInstance()); } /** * * * <pre> * List of RagCorpora in the requested page. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.RagCorpus rag_corpora = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder> getRagCorporaBuilderList() { return getRagCorporaFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RagCorpus, com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder, com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder> getRagCorporaFieldBuilder() { if (ragCorporaBuilder_ == null) { ragCorporaBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RagCorpus, com.google.cloud.aiplatform.v1beta1.RagCorpus.Builder, com.google.cloud.aiplatform.v1beta1.RagCorpusOrBuilder>( ragCorpora_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); ragCorpora_ = null; } return ragCorporaBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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 * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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 * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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 * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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 * [ListRagCorporaRequest.page_token][google.cloud.aiplatform.v1beta1.ListRagCorporaRequest.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.ListRagCorporaResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListRagCorporaResponse) private static final com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse(); } public static com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListRagCorporaResponse> PARSER = new com.google.protobuf.AbstractParser<ListRagCorporaResponse>() { @java.lang.Override public ListRagCorporaResponse 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<ListRagCorporaResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListRagCorporaResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListRagCorporaResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,800
java-artifact-registry/proto-google-cloud-artifact-registry-v1/src/main/java/com/google/devtools/artifactregistry/v1/ListDockerImagesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/artifactregistry/v1/artifact.proto // Protobuf Java Version: 3.25.8 package com.google.devtools.artifactregistry.v1; /** * * * <pre> * The response from listing docker images. * </pre> * * Protobuf type {@code google.devtools.artifactregistry.v1.ListDockerImagesResponse} */ public final class ListDockerImagesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1.ListDockerImagesResponse) ListDockerImagesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDockerImagesResponse.newBuilder() to construct. private ListDockerImagesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDockerImagesResponse() { dockerImages_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDockerImagesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.artifactregistry.v1.ArtifactProto .internal_static_google_devtools_artifactregistry_v1_ListDockerImagesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.artifactregistry.v1.ArtifactProto .internal_static_google_devtools_artifactregistry_v1_ListDockerImagesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.class, com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.Builder.class); } public static final int DOCKER_IMAGES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.devtools.artifactregistry.v1.DockerImage> dockerImages_; /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ @java.lang.Override public java.util.List<com.google.devtools.artifactregistry.v1.DockerImage> getDockerImagesList() { return dockerImages_; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.devtools.artifactregistry.v1.DockerImageOrBuilder> getDockerImagesOrBuilderList() { return dockerImages_; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ @java.lang.Override public int getDockerImagesCount() { return dockerImages_.size(); } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ @java.lang.Override public com.google.devtools.artifactregistry.v1.DockerImage getDockerImages(int index) { return dockerImages_.get(index); } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ @java.lang.Override public com.google.devtools.artifactregistry.v1.DockerImageOrBuilder getDockerImagesOrBuilder( int index) { return dockerImages_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < dockerImages_.size(); i++) { output.writeMessage(1, dockerImages_.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 < dockerImages_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dockerImages_.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.devtools.artifactregistry.v1.ListDockerImagesResponse)) { return super.equals(obj); } com.google.devtools.artifactregistry.v1.ListDockerImagesResponse other = (com.google.devtools.artifactregistry.v1.ListDockerImagesResponse) obj; if (!getDockerImagesList().equals(other.getDockerImagesList())) 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 (getDockerImagesCount() > 0) { hash = (37 * hash) + DOCKER_IMAGES_FIELD_NUMBER; hash = (53 * hash) + getDockerImagesList().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.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.devtools.artifactregistry.v1.ListDockerImagesResponse 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 listing docker images. * </pre> * * Protobuf type {@code google.devtools.artifactregistry.v1.ListDockerImagesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1.ListDockerImagesResponse) com.google.devtools.artifactregistry.v1.ListDockerImagesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.artifactregistry.v1.ArtifactProto .internal_static_google_devtools_artifactregistry_v1_ListDockerImagesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.artifactregistry.v1.ArtifactProto .internal_static_google_devtools_artifactregistry_v1_ListDockerImagesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.class, com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.Builder.class); } // Construct using com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dockerImagesBuilder_ == null) { dockerImages_ = java.util.Collections.emptyList(); } else { dockerImages_ = null; dockerImagesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.devtools.artifactregistry.v1.ArtifactProto .internal_static_google_devtools_artifactregistry_v1_ListDockerImagesResponse_descriptor; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListDockerImagesResponse getDefaultInstanceForType() { return com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.getDefaultInstance(); } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListDockerImagesResponse build() { com.google.devtools.artifactregistry.v1.ListDockerImagesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListDockerImagesResponse buildPartial() { com.google.devtools.artifactregistry.v1.ListDockerImagesResponse result = new com.google.devtools.artifactregistry.v1.ListDockerImagesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.devtools.artifactregistry.v1.ListDockerImagesResponse result) { if (dockerImagesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dockerImages_ = java.util.Collections.unmodifiableList(dockerImages_); bitField0_ = (bitField0_ & ~0x00000001); } result.dockerImages_ = dockerImages_; } else { result.dockerImages_ = dockerImagesBuilder_.build(); } } private void buildPartial0( com.google.devtools.artifactregistry.v1.ListDockerImagesResponse 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.devtools.artifactregistry.v1.ListDockerImagesResponse) { return mergeFrom((com.google.devtools.artifactregistry.v1.ListDockerImagesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.devtools.artifactregistry.v1.ListDockerImagesResponse other) { if (other == com.google.devtools.artifactregistry.v1.ListDockerImagesResponse.getDefaultInstance()) return this; if (dockerImagesBuilder_ == null) { if (!other.dockerImages_.isEmpty()) { if (dockerImages_.isEmpty()) { dockerImages_ = other.dockerImages_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDockerImagesIsMutable(); dockerImages_.addAll(other.dockerImages_); } onChanged(); } } else { if (!other.dockerImages_.isEmpty()) { if (dockerImagesBuilder_.isEmpty()) { dockerImagesBuilder_.dispose(); dockerImagesBuilder_ = null; dockerImages_ = other.dockerImages_; bitField0_ = (bitField0_ & ~0x00000001); dockerImagesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDockerImagesFieldBuilder() : null; } else { dockerImagesBuilder_.addAllMessages(other.dockerImages_); } } } 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.devtools.artifactregistry.v1.DockerImage m = input.readMessage( com.google.devtools.artifactregistry.v1.DockerImage.parser(), extensionRegistry); if (dockerImagesBuilder_ == null) { ensureDockerImagesIsMutable(); dockerImages_.add(m); } else { dockerImagesBuilder_.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.devtools.artifactregistry.v1.DockerImage> dockerImages_ = java.util.Collections.emptyList(); private void ensureDockerImagesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dockerImages_ = new java.util.ArrayList<com.google.devtools.artifactregistry.v1.DockerImage>( dockerImages_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.DockerImage, com.google.devtools.artifactregistry.v1.DockerImage.Builder, com.google.devtools.artifactregistry.v1.DockerImageOrBuilder> dockerImagesBuilder_; /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public java.util.List<com.google.devtools.artifactregistry.v1.DockerImage> getDockerImagesList() { if (dockerImagesBuilder_ == null) { return java.util.Collections.unmodifiableList(dockerImages_); } else { return dockerImagesBuilder_.getMessageList(); } } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public int getDockerImagesCount() { if (dockerImagesBuilder_ == null) { return dockerImages_.size(); } else { return dockerImagesBuilder_.getCount(); } } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public com.google.devtools.artifactregistry.v1.DockerImage getDockerImages(int index) { if (dockerImagesBuilder_ == null) { return dockerImages_.get(index); } else { return dockerImagesBuilder_.getMessage(index); } } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder setDockerImages( int index, com.google.devtools.artifactregistry.v1.DockerImage value) { if (dockerImagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDockerImagesIsMutable(); dockerImages_.set(index, value); onChanged(); } else { dockerImagesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder setDockerImages( int index, com.google.devtools.artifactregistry.v1.DockerImage.Builder builderForValue) { if (dockerImagesBuilder_ == null) { ensureDockerImagesIsMutable(); dockerImages_.set(index, builderForValue.build()); onChanged(); } else { dockerImagesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder addDockerImages(com.google.devtools.artifactregistry.v1.DockerImage value) { if (dockerImagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDockerImagesIsMutable(); dockerImages_.add(value); onChanged(); } else { dockerImagesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder addDockerImages( int index, com.google.devtools.artifactregistry.v1.DockerImage value) { if (dockerImagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDockerImagesIsMutable(); dockerImages_.add(index, value); onChanged(); } else { dockerImagesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder addDockerImages( com.google.devtools.artifactregistry.v1.DockerImage.Builder builderForValue) { if (dockerImagesBuilder_ == null) { ensureDockerImagesIsMutable(); dockerImages_.add(builderForValue.build()); onChanged(); } else { dockerImagesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder addDockerImages( int index, com.google.devtools.artifactregistry.v1.DockerImage.Builder builderForValue) { if (dockerImagesBuilder_ == null) { ensureDockerImagesIsMutable(); dockerImages_.add(index, builderForValue.build()); onChanged(); } else { dockerImagesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder addAllDockerImages( java.lang.Iterable<? extends com.google.devtools.artifactregistry.v1.DockerImage> values) { if (dockerImagesBuilder_ == null) { ensureDockerImagesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dockerImages_); onChanged(); } else { dockerImagesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder clearDockerImages() { if (dockerImagesBuilder_ == null) { dockerImages_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dockerImagesBuilder_.clear(); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public Builder removeDockerImages(int index) { if (dockerImagesBuilder_ == null) { ensureDockerImagesIsMutable(); dockerImages_.remove(index); onChanged(); } else { dockerImagesBuilder_.remove(index); } return this; } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public com.google.devtools.artifactregistry.v1.DockerImage.Builder getDockerImagesBuilder( int index) { return getDockerImagesFieldBuilder().getBuilder(index); } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public com.google.devtools.artifactregistry.v1.DockerImageOrBuilder getDockerImagesOrBuilder( int index) { if (dockerImagesBuilder_ == null) { return dockerImages_.get(index); } else { return dockerImagesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public java.util.List<? extends com.google.devtools.artifactregistry.v1.DockerImageOrBuilder> getDockerImagesOrBuilderList() { if (dockerImagesBuilder_ != null) { return dockerImagesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dockerImages_); } } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public com.google.devtools.artifactregistry.v1.DockerImage.Builder addDockerImagesBuilder() { return getDockerImagesFieldBuilder() .addBuilder(com.google.devtools.artifactregistry.v1.DockerImage.getDefaultInstance()); } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public com.google.devtools.artifactregistry.v1.DockerImage.Builder addDockerImagesBuilder( int index) { return getDockerImagesFieldBuilder() .addBuilder( index, com.google.devtools.artifactregistry.v1.DockerImage.getDefaultInstance()); } /** * * * <pre> * The docker images returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.DockerImage docker_images = 1;</code> */ public java.util.List<com.google.devtools.artifactregistry.v1.DockerImage.Builder> getDockerImagesBuilderList() { return getDockerImagesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.DockerImage, com.google.devtools.artifactregistry.v1.DockerImage.Builder, com.google.devtools.artifactregistry.v1.DockerImageOrBuilder> getDockerImagesFieldBuilder() { if (dockerImagesBuilder_ == null) { dockerImagesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.DockerImage, com.google.devtools.artifactregistry.v1.DockerImage.Builder, com.google.devtools.artifactregistry.v1.DockerImageOrBuilder>( dockerImages_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dockerImages_ = null; } return dockerImagesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The token to retrieve the next page of artifacts, or empty if there are no * more artifacts to return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.devtools.artifactregistry.v1.ListDockerImagesResponse) } // @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1.ListDockerImagesResponse) private static final com.google.devtools.artifactregistry.v1.ListDockerImagesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1.ListDockerImagesResponse(); } public static com.google.devtools.artifactregistry.v1.ListDockerImagesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDockerImagesResponse> PARSER = new com.google.protobuf.AbstractParser<ListDockerImagesResponse>() { @java.lang.Override public ListDockerImagesResponse 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<ListDockerImagesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDockerImagesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListDockerImagesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
38,133
java-aiplatform/google-cloud-aiplatform/src/main/java/com/google/cloud/aiplatform/v1/stub/GrpcFeatureRegistryServiceStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.aiplatform.v1.stub; import static com.google.cloud.aiplatform.v1.FeatureRegistryServiceClient.ListFeatureGroupsPagedResponse; import static com.google.cloud.aiplatform.v1.FeatureRegistryServiceClient.ListFeaturesPagedResponse; import static com.google.cloud.aiplatform.v1.FeatureRegistryServiceClient.ListLocationsPagedResponse; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.grpc.GrpcCallSettings; import com.google.api.gax.grpc.GrpcStubCallableFactory; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.aiplatform.v1.BatchCreateFeaturesOperationMetadata; import com.google.cloud.aiplatform.v1.BatchCreateFeaturesRequest; import com.google.cloud.aiplatform.v1.BatchCreateFeaturesResponse; import com.google.cloud.aiplatform.v1.CreateFeatureGroupOperationMetadata; import com.google.cloud.aiplatform.v1.CreateFeatureGroupRequest; import com.google.cloud.aiplatform.v1.CreateFeatureOperationMetadata; import com.google.cloud.aiplatform.v1.CreateFeatureRequest; import com.google.cloud.aiplatform.v1.DeleteFeatureGroupRequest; import com.google.cloud.aiplatform.v1.DeleteFeatureRequest; import com.google.cloud.aiplatform.v1.DeleteOperationMetadata; import com.google.cloud.aiplatform.v1.Feature; import com.google.cloud.aiplatform.v1.FeatureGroup; import com.google.cloud.aiplatform.v1.GetFeatureGroupRequest; import com.google.cloud.aiplatform.v1.GetFeatureRequest; import com.google.cloud.aiplatform.v1.ListFeatureGroupsRequest; import com.google.cloud.aiplatform.v1.ListFeatureGroupsResponse; import com.google.cloud.aiplatform.v1.ListFeaturesRequest; import com.google.cloud.aiplatform.v1.ListFeaturesResponse; import com.google.cloud.aiplatform.v1.UpdateFeatureGroupOperationMetadata; import com.google.cloud.aiplatform.v1.UpdateFeatureGroupRequest; import com.google.cloud.aiplatform.v1.UpdateFeatureOperationMetadata; import com.google.cloud.aiplatform.v1.UpdateFeatureRequest; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.longrunning.stub.GrpcOperationsStub; import com.google.protobuf.Empty; import io.grpc.MethodDescriptor; import io.grpc.protobuf.ProtoUtils; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * gRPC stub implementation for the FeatureRegistryService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class GrpcFeatureRegistryServiceStub extends FeatureRegistryServiceStub { private static final MethodDescriptor<CreateFeatureGroupRequest, Operation> createFeatureGroupMethodDescriptor = MethodDescriptor.<CreateFeatureGroupRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1.FeatureRegistryService/CreateFeatureGroup") .setRequestMarshaller( ProtoUtils.marshaller(CreateFeatureGroupRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetFeatureGroupRequest, FeatureGroup> getFeatureGroupMethodDescriptor = MethodDescriptor.<GetFeatureGroupRequest, FeatureGroup>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1.FeatureRegistryService/GetFeatureGroup") .setRequestMarshaller( ProtoUtils.marshaller(GetFeatureGroupRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(FeatureGroup.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListFeatureGroupsRequest, ListFeatureGroupsResponse> listFeatureGroupsMethodDescriptor = MethodDescriptor.<ListFeatureGroupsRequest, ListFeatureGroupsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1.FeatureRegistryService/ListFeatureGroups") .setRequestMarshaller( ProtoUtils.marshaller(ListFeatureGroupsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListFeatureGroupsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UpdateFeatureGroupRequest, Operation> updateFeatureGroupMethodDescriptor = MethodDescriptor.<UpdateFeatureGroupRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1.FeatureRegistryService/UpdateFeatureGroup") .setRequestMarshaller( ProtoUtils.marshaller(UpdateFeatureGroupRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteFeatureGroupRequest, Operation> deleteFeatureGroupMethodDescriptor = MethodDescriptor.<DeleteFeatureGroupRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1.FeatureRegistryService/DeleteFeatureGroup") .setRequestMarshaller( ProtoUtils.marshaller(DeleteFeatureGroupRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<CreateFeatureRequest, Operation> createFeatureMethodDescriptor = MethodDescriptor.<CreateFeatureRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1.FeatureRegistryService/CreateFeature") .setRequestMarshaller( ProtoUtils.marshaller(CreateFeatureRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<BatchCreateFeaturesRequest, Operation> batchCreateFeaturesMethodDescriptor = MethodDescriptor.<BatchCreateFeaturesRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.aiplatform.v1.FeatureRegistryService/BatchCreateFeatures") .setRequestMarshaller( ProtoUtils.marshaller(BatchCreateFeaturesRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetFeatureRequest, Feature> getFeatureMethodDescriptor = MethodDescriptor.<GetFeatureRequest, Feature>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1.FeatureRegistryService/GetFeature") .setRequestMarshaller(ProtoUtils.marshaller(GetFeatureRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Feature.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListFeaturesRequest, ListFeaturesResponse> listFeaturesMethodDescriptor = MethodDescriptor.<ListFeaturesRequest, ListFeaturesResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1.FeatureRegistryService/ListFeatures") .setRequestMarshaller(ProtoUtils.marshaller(ListFeaturesRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListFeaturesResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UpdateFeatureRequest, Operation> updateFeatureMethodDescriptor = MethodDescriptor.<UpdateFeatureRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1.FeatureRegistryService/UpdateFeature") .setRequestMarshaller( ProtoUtils.marshaller(UpdateFeatureRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteFeatureRequest, Operation> deleteFeatureMethodDescriptor = MethodDescriptor.<DeleteFeatureRequest, Operation>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.aiplatform.v1.FeatureRegistryService/DeleteFeature") .setRequestMarshaller( ProtoUtils.marshaller(DeleteFeatureRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListLocationsRequest, ListLocationsResponse> listLocationsMethodDescriptor = MethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.location.Locations/ListLocations") .setRequestMarshaller( ProtoUtils.marshaller(ListLocationsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListLocationsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor = MethodDescriptor.<GetLocationRequest, Location>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.location.Locations/GetLocation") .setRequestMarshaller(ProtoUtils.marshaller(GetLocationRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Location.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor = MethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") .setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor = MethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") .setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsMethodDescriptor = MethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") .setRequestMarshaller( ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private final UnaryCallable<CreateFeatureGroupRequest, Operation> createFeatureGroupCallable; private final OperationCallable< CreateFeatureGroupRequest, FeatureGroup, CreateFeatureGroupOperationMetadata> createFeatureGroupOperationCallable; private final UnaryCallable<GetFeatureGroupRequest, FeatureGroup> getFeatureGroupCallable; private final UnaryCallable<ListFeatureGroupsRequest, ListFeatureGroupsResponse> listFeatureGroupsCallable; private final UnaryCallable<ListFeatureGroupsRequest, ListFeatureGroupsPagedResponse> listFeatureGroupsPagedCallable; private final UnaryCallable<UpdateFeatureGroupRequest, Operation> updateFeatureGroupCallable; private final OperationCallable< UpdateFeatureGroupRequest, FeatureGroup, UpdateFeatureGroupOperationMetadata> updateFeatureGroupOperationCallable; private final UnaryCallable<DeleteFeatureGroupRequest, Operation> deleteFeatureGroupCallable; private final OperationCallable<DeleteFeatureGroupRequest, Empty, DeleteOperationMetadata> deleteFeatureGroupOperationCallable; private final UnaryCallable<CreateFeatureRequest, Operation> createFeatureCallable; private final OperationCallable<CreateFeatureRequest, Feature, CreateFeatureOperationMetadata> createFeatureOperationCallable; private final UnaryCallable<BatchCreateFeaturesRequest, Operation> batchCreateFeaturesCallable; private final OperationCallable< BatchCreateFeaturesRequest, BatchCreateFeaturesResponse, BatchCreateFeaturesOperationMetadata> batchCreateFeaturesOperationCallable; private final UnaryCallable<GetFeatureRequest, Feature> getFeatureCallable; private final UnaryCallable<ListFeaturesRequest, ListFeaturesResponse> listFeaturesCallable; private final UnaryCallable<ListFeaturesRequest, ListFeaturesPagedResponse> listFeaturesPagedCallable; private final UnaryCallable<UpdateFeatureRequest, Operation> updateFeatureCallable; private final OperationCallable<UpdateFeatureRequest, Feature, UpdateFeatureOperationMetadata> updateFeatureOperationCallable; private final UnaryCallable<DeleteFeatureRequest, Operation> deleteFeatureCallable; private final OperationCallable<DeleteFeatureRequest, Empty, DeleteOperationMetadata> deleteFeatureOperationCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable; private final UnaryCallable<GetLocationRequest, Location> getLocationCallable; private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable; private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable; private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final GrpcOperationsStub operationsStub; private final GrpcStubCallableFactory callableFactory; public static final GrpcFeatureRegistryServiceStub create( FeatureRegistryServiceStubSettings settings) throws IOException { return new GrpcFeatureRegistryServiceStub(settings, ClientContext.create(settings)); } public static final GrpcFeatureRegistryServiceStub create(ClientContext clientContext) throws IOException { return new GrpcFeatureRegistryServiceStub( FeatureRegistryServiceStubSettings.newBuilder().build(), clientContext); } public static final GrpcFeatureRegistryServiceStub create( ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { return new GrpcFeatureRegistryServiceStub( FeatureRegistryServiceStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of GrpcFeatureRegistryServiceStub, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected GrpcFeatureRegistryServiceStub( FeatureRegistryServiceStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new GrpcFeatureRegistryServiceCallableFactory()); } /** * Constructs an instance of GrpcFeatureRegistryServiceStub, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected GrpcFeatureRegistryServiceStub( FeatureRegistryServiceStubSettings settings, ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); GrpcCallSettings<CreateFeatureGroupRequest, Operation> createFeatureGroupTransportSettings = GrpcCallSettings.<CreateFeatureGroupRequest, Operation>newBuilder() .setMethodDescriptor(createFeatureGroupMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<GetFeatureGroupRequest, FeatureGroup> getFeatureGroupTransportSettings = GrpcCallSettings.<GetFeatureGroupRequest, FeatureGroup>newBuilder() .setMethodDescriptor(getFeatureGroupMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListFeatureGroupsRequest, ListFeatureGroupsResponse> listFeatureGroupsTransportSettings = GrpcCallSettings.<ListFeatureGroupsRequest, ListFeatureGroupsResponse>newBuilder() .setMethodDescriptor(listFeatureGroupsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<UpdateFeatureGroupRequest, Operation> updateFeatureGroupTransportSettings = GrpcCallSettings.<UpdateFeatureGroupRequest, Operation>newBuilder() .setMethodDescriptor(updateFeatureGroupMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add( "feature_group.name", String.valueOf(request.getFeatureGroup().getName())); return builder.build(); }) .build(); GrpcCallSettings<DeleteFeatureGroupRequest, Operation> deleteFeatureGroupTransportSettings = GrpcCallSettings.<DeleteFeatureGroupRequest, Operation>newBuilder() .setMethodDescriptor(deleteFeatureGroupMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<CreateFeatureRequest, Operation> createFeatureTransportSettings = GrpcCallSettings.<CreateFeatureRequest, Operation>newBuilder() .setMethodDescriptor(createFeatureMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<BatchCreateFeaturesRequest, Operation> batchCreateFeaturesTransportSettings = GrpcCallSettings.<BatchCreateFeaturesRequest, Operation>newBuilder() .setMethodDescriptor(batchCreateFeaturesMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<GetFeatureRequest, Feature> getFeatureTransportSettings = GrpcCallSettings.<GetFeatureRequest, Feature>newBuilder() .setMethodDescriptor(getFeatureMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListFeaturesRequest, ListFeaturesResponse> listFeaturesTransportSettings = GrpcCallSettings.<ListFeaturesRequest, ListFeaturesResponse>newBuilder() .setMethodDescriptor(listFeaturesMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<UpdateFeatureRequest, Operation> updateFeatureTransportSettings = GrpcCallSettings.<UpdateFeatureRequest, Operation>newBuilder() .setMethodDescriptor(updateFeatureMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("feature.name", String.valueOf(request.getFeature().getName())); return builder.build(); }) .build(); GrpcCallSettings<DeleteFeatureRequest, Operation> deleteFeatureTransportSettings = GrpcCallSettings.<DeleteFeatureRequest, Operation>newBuilder() .setMethodDescriptor(deleteFeatureMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings = GrpcCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setMethodDescriptor(listLocationsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<GetLocationRequest, Location> getLocationTransportSettings = GrpcCallSettings.<GetLocationRequest, Location>newBuilder() .setMethodDescriptor(getLocationMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings = GrpcCallSettings.<SetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(setIamPolicyMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); GrpcCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings = GrpcCallSettings.<GetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(getIamPolicyMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); GrpcCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsTransportSettings = GrpcCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.createFeatureGroupCallable = callableFactory.createUnaryCallable( createFeatureGroupTransportSettings, settings.createFeatureGroupSettings(), clientContext); this.createFeatureGroupOperationCallable = callableFactory.createOperationCallable( createFeatureGroupTransportSettings, settings.createFeatureGroupOperationSettings(), clientContext, operationsStub); this.getFeatureGroupCallable = callableFactory.createUnaryCallable( getFeatureGroupTransportSettings, settings.getFeatureGroupSettings(), clientContext); this.listFeatureGroupsCallable = callableFactory.createUnaryCallable( listFeatureGroupsTransportSettings, settings.listFeatureGroupsSettings(), clientContext); this.listFeatureGroupsPagedCallable = callableFactory.createPagedCallable( listFeatureGroupsTransportSettings, settings.listFeatureGroupsSettings(), clientContext); this.updateFeatureGroupCallable = callableFactory.createUnaryCallable( updateFeatureGroupTransportSettings, settings.updateFeatureGroupSettings(), clientContext); this.updateFeatureGroupOperationCallable = callableFactory.createOperationCallable( updateFeatureGroupTransportSettings, settings.updateFeatureGroupOperationSettings(), clientContext, operationsStub); this.deleteFeatureGroupCallable = callableFactory.createUnaryCallable( deleteFeatureGroupTransportSettings, settings.deleteFeatureGroupSettings(), clientContext); this.deleteFeatureGroupOperationCallable = callableFactory.createOperationCallable( deleteFeatureGroupTransportSettings, settings.deleteFeatureGroupOperationSettings(), clientContext, operationsStub); this.createFeatureCallable = callableFactory.createUnaryCallable( createFeatureTransportSettings, settings.createFeatureSettings(), clientContext); this.createFeatureOperationCallable = callableFactory.createOperationCallable( createFeatureTransportSettings, settings.createFeatureOperationSettings(), clientContext, operationsStub); this.batchCreateFeaturesCallable = callableFactory.createUnaryCallable( batchCreateFeaturesTransportSettings, settings.batchCreateFeaturesSettings(), clientContext); this.batchCreateFeaturesOperationCallable = callableFactory.createOperationCallable( batchCreateFeaturesTransportSettings, settings.batchCreateFeaturesOperationSettings(), clientContext, operationsStub); this.getFeatureCallable = callableFactory.createUnaryCallable( getFeatureTransportSettings, settings.getFeatureSettings(), clientContext); this.listFeaturesCallable = callableFactory.createUnaryCallable( listFeaturesTransportSettings, settings.listFeaturesSettings(), clientContext); this.listFeaturesPagedCallable = callableFactory.createPagedCallable( listFeaturesTransportSettings, settings.listFeaturesSettings(), clientContext); this.updateFeatureCallable = callableFactory.createUnaryCallable( updateFeatureTransportSettings, settings.updateFeatureSettings(), clientContext); this.updateFeatureOperationCallable = callableFactory.createOperationCallable( updateFeatureTransportSettings, settings.updateFeatureOperationSettings(), clientContext, operationsStub); this.deleteFeatureCallable = callableFactory.createUnaryCallable( deleteFeatureTransportSettings, settings.deleteFeatureSettings(), clientContext); this.deleteFeatureOperationCallable = callableFactory.createOperationCallable( deleteFeatureTransportSettings, settings.deleteFeatureOperationSettings(), clientContext, operationsStub); this.listLocationsCallable = callableFactory.createUnaryCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.listLocationsPagedCallable = callableFactory.createPagedCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.getLocationCallable = callableFactory.createUnaryCallable( getLocationTransportSettings, settings.getLocationSettings(), clientContext); this.setIamPolicyCallable = callableFactory.createUnaryCallable( setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); this.getIamPolicyCallable = callableFactory.createUnaryCallable( getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); this.testIamPermissionsCallable = callableFactory.createUnaryCallable( testIamPermissionsTransportSettings, settings.testIamPermissionsSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } public GrpcOperationsStub getOperationsStub() { return operationsStub; } @Override public UnaryCallable<CreateFeatureGroupRequest, Operation> createFeatureGroupCallable() { return createFeatureGroupCallable; } @Override public OperationCallable< CreateFeatureGroupRequest, FeatureGroup, CreateFeatureGroupOperationMetadata> createFeatureGroupOperationCallable() { return createFeatureGroupOperationCallable; } @Override public UnaryCallable<GetFeatureGroupRequest, FeatureGroup> getFeatureGroupCallable() { return getFeatureGroupCallable; } @Override public UnaryCallable<ListFeatureGroupsRequest, ListFeatureGroupsResponse> listFeatureGroupsCallable() { return listFeatureGroupsCallable; } @Override public UnaryCallable<ListFeatureGroupsRequest, ListFeatureGroupsPagedResponse> listFeatureGroupsPagedCallable() { return listFeatureGroupsPagedCallable; } @Override public UnaryCallable<UpdateFeatureGroupRequest, Operation> updateFeatureGroupCallable() { return updateFeatureGroupCallable; } @Override public OperationCallable< UpdateFeatureGroupRequest, FeatureGroup, UpdateFeatureGroupOperationMetadata> updateFeatureGroupOperationCallable() { return updateFeatureGroupOperationCallable; } @Override public UnaryCallable<DeleteFeatureGroupRequest, Operation> deleteFeatureGroupCallable() { return deleteFeatureGroupCallable; } @Override public OperationCallable<DeleteFeatureGroupRequest, Empty, DeleteOperationMetadata> deleteFeatureGroupOperationCallable() { return deleteFeatureGroupOperationCallable; } @Override public UnaryCallable<CreateFeatureRequest, Operation> createFeatureCallable() { return createFeatureCallable; } @Override public OperationCallable<CreateFeatureRequest, Feature, CreateFeatureOperationMetadata> createFeatureOperationCallable() { return createFeatureOperationCallable; } @Override public UnaryCallable<BatchCreateFeaturesRequest, Operation> batchCreateFeaturesCallable() { return batchCreateFeaturesCallable; } @Override public OperationCallable< BatchCreateFeaturesRequest, BatchCreateFeaturesResponse, BatchCreateFeaturesOperationMetadata> batchCreateFeaturesOperationCallable() { return batchCreateFeaturesOperationCallable; } @Override public UnaryCallable<GetFeatureRequest, Feature> getFeatureCallable() { return getFeatureCallable; } @Override public UnaryCallable<ListFeaturesRequest, ListFeaturesResponse> listFeaturesCallable() { return listFeaturesCallable; } @Override public UnaryCallable<ListFeaturesRequest, ListFeaturesPagedResponse> listFeaturesPagedCallable() { return listFeaturesPagedCallable; } @Override public UnaryCallable<UpdateFeatureRequest, Operation> updateFeatureCallable() { return updateFeatureCallable; } @Override public OperationCallable<UpdateFeatureRequest, Feature, UpdateFeatureOperationMetadata> updateFeatureOperationCallable() { return updateFeatureOperationCallable; } @Override public UnaryCallable<DeleteFeatureRequest, Operation> deleteFeatureCallable() { return deleteFeatureCallable; } @Override public OperationCallable<DeleteFeatureRequest, Empty, DeleteOperationMetadata> deleteFeatureOperationCallable() { return deleteFeatureOperationCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return listLocationsCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return listLocationsPagedCallable; } @Override public UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return getLocationCallable; } @Override public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return setIamPolicyCallable; } @Override public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return getIamPolicyCallable; } @Override public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable() { return testIamPermissionsCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
apache/hive
37,896
standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/GetTablesExtRequest.java
/** * Autogenerated by Thrift Compiler (0.16.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hive.metastore.api; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.16.0)") @org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class GetTablesExtRequest implements org.apache.thrift.TBase<GetTablesExtRequest, GetTablesExtRequest._Fields>, java.io.Serializable, Cloneable, Comparable<GetTablesExtRequest> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetTablesExtRequest"); private static final org.apache.thrift.protocol.TField CATALOG_FIELD_DESC = new org.apache.thrift.protocol.TField("catalog", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField DATABASE_FIELD_DESC = new org.apache.thrift.protocol.TField("database", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField TABLE_NAME_PATTERN_FIELD_DESC = new org.apache.thrift.protocol.TField("tableNamePattern", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField REQUESTED_FIELDS_FIELD_DESC = new org.apache.thrift.protocol.TField("requestedFields", org.apache.thrift.protocol.TType.I32, (short)4); private static final org.apache.thrift.protocol.TField LIMIT_FIELD_DESC = new org.apache.thrift.protocol.TField("limit", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField PROCESSOR_CAPABILITIES_FIELD_DESC = new org.apache.thrift.protocol.TField("processorCapabilities", org.apache.thrift.protocol.TType.LIST, (short)6); private static final org.apache.thrift.protocol.TField PROCESSOR_IDENTIFIER_FIELD_DESC = new org.apache.thrift.protocol.TField("processorIdentifier", org.apache.thrift.protocol.TType.STRING, (short)7); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new GetTablesExtRequestStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new GetTablesExtRequestTupleSchemeFactory(); private @org.apache.thrift.annotation.Nullable java.lang.String catalog; // required private @org.apache.thrift.annotation.Nullable java.lang.String database; // required private @org.apache.thrift.annotation.Nullable java.lang.String tableNamePattern; // required private int requestedFields; // required private int limit; // optional private @org.apache.thrift.annotation.Nullable java.util.List<java.lang.String> processorCapabilities; // optional private @org.apache.thrift.annotation.Nullable java.lang.String processorIdentifier; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { CATALOG((short)1, "catalog"), DATABASE((short)2, "database"), TABLE_NAME_PATTERN((short)3, "tableNamePattern"), REQUESTED_FIELDS((short)4, "requestedFields"), LIMIT((short)5, "limit"), PROCESSOR_CAPABILITIES((short)6, "processorCapabilities"), PROCESSOR_IDENTIFIER((short)7, "processorIdentifier"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // CATALOG return CATALOG; case 2: // DATABASE return DATABASE; case 3: // TABLE_NAME_PATTERN return TABLE_NAME_PATTERN; case 4: // REQUESTED_FIELDS return REQUESTED_FIELDS; case 5: // LIMIT return LIMIT; case 6: // PROCESSOR_CAPABILITIES return PROCESSOR_CAPABILITIES; case 7: // PROCESSOR_IDENTIFIER return PROCESSOR_IDENTIFIER; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final int __REQUESTEDFIELDS_ISSET_ID = 0; private static final int __LIMIT_ISSET_ID = 1; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.LIMIT,_Fields.PROCESSOR_CAPABILITIES,_Fields.PROCESSOR_IDENTIFIER}; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.CATALOG, new org.apache.thrift.meta_data.FieldMetaData("catalog", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.DATABASE, new org.apache.thrift.meta_data.FieldMetaData("database", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.TABLE_NAME_PATTERN, new org.apache.thrift.meta_data.FieldMetaData("tableNamePattern", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.REQUESTED_FIELDS, new org.apache.thrift.meta_data.FieldMetaData("requestedFields", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.LIMIT, new org.apache.thrift.meta_data.FieldMetaData("limit", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.PROCESSOR_CAPABILITIES, new org.apache.thrift.meta_data.FieldMetaData("processorCapabilities", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.PROCESSOR_IDENTIFIER, new org.apache.thrift.meta_data.FieldMetaData("processorIdentifier", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetTablesExtRequest.class, metaDataMap); } public GetTablesExtRequest() { } public GetTablesExtRequest( java.lang.String catalog, java.lang.String database, java.lang.String tableNamePattern, int requestedFields) { this(); this.catalog = catalog; this.database = database; this.tableNamePattern = tableNamePattern; this.requestedFields = requestedFields; setRequestedFieldsIsSet(true); } /** * Performs a deep copy on <i>other</i>. */ public GetTablesExtRequest(GetTablesExtRequest other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetCatalog()) { this.catalog = other.catalog; } if (other.isSetDatabase()) { this.database = other.database; } if (other.isSetTableNamePattern()) { this.tableNamePattern = other.tableNamePattern; } this.requestedFields = other.requestedFields; this.limit = other.limit; if (other.isSetProcessorCapabilities()) { java.util.List<java.lang.String> __this__processorCapabilities = new java.util.ArrayList<java.lang.String>(other.processorCapabilities); this.processorCapabilities = __this__processorCapabilities; } if (other.isSetProcessorIdentifier()) { this.processorIdentifier = other.processorIdentifier; } } public GetTablesExtRequest deepCopy() { return new GetTablesExtRequest(this); } @Override public void clear() { this.catalog = null; this.database = null; this.tableNamePattern = null; setRequestedFieldsIsSet(false); this.requestedFields = 0; setLimitIsSet(false); this.limit = 0; this.processorCapabilities = null; this.processorIdentifier = null; } @org.apache.thrift.annotation.Nullable public java.lang.String getCatalog() { return this.catalog; } public void setCatalog(@org.apache.thrift.annotation.Nullable java.lang.String catalog) { this.catalog = catalog; } public void unsetCatalog() { this.catalog = null; } /** Returns true if field catalog is set (has been assigned a value) and false otherwise */ public boolean isSetCatalog() { return this.catalog != null; } public void setCatalogIsSet(boolean value) { if (!value) { this.catalog = null; } } @org.apache.thrift.annotation.Nullable public java.lang.String getDatabase() { return this.database; } public void setDatabase(@org.apache.thrift.annotation.Nullable java.lang.String database) { this.database = database; } public void unsetDatabase() { this.database = null; } /** Returns true if field database is set (has been assigned a value) and false otherwise */ public boolean isSetDatabase() { return this.database != null; } public void setDatabaseIsSet(boolean value) { if (!value) { this.database = null; } } @org.apache.thrift.annotation.Nullable public java.lang.String getTableNamePattern() { return this.tableNamePattern; } public void setTableNamePattern(@org.apache.thrift.annotation.Nullable java.lang.String tableNamePattern) { this.tableNamePattern = tableNamePattern; } public void unsetTableNamePattern() { this.tableNamePattern = null; } /** Returns true if field tableNamePattern is set (has been assigned a value) and false otherwise */ public boolean isSetTableNamePattern() { return this.tableNamePattern != null; } public void setTableNamePatternIsSet(boolean value) { if (!value) { this.tableNamePattern = null; } } public int getRequestedFields() { return this.requestedFields; } public void setRequestedFields(int requestedFields) { this.requestedFields = requestedFields; setRequestedFieldsIsSet(true); } public void unsetRequestedFields() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __REQUESTEDFIELDS_ISSET_ID); } /** Returns true if field requestedFields is set (has been assigned a value) and false otherwise */ public boolean isSetRequestedFields() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __REQUESTEDFIELDS_ISSET_ID); } public void setRequestedFieldsIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __REQUESTEDFIELDS_ISSET_ID, value); } public int getLimit() { return this.limit; } public void setLimit(int limit) { this.limit = limit; setLimitIsSet(true); } public void unsetLimit() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __LIMIT_ISSET_ID); } /** Returns true if field limit is set (has been assigned a value) and false otherwise */ public boolean isSetLimit() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __LIMIT_ISSET_ID); } public void setLimitIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __LIMIT_ISSET_ID, value); } public int getProcessorCapabilitiesSize() { return (this.processorCapabilities == null) ? 0 : this.processorCapabilities.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<java.lang.String> getProcessorCapabilitiesIterator() { return (this.processorCapabilities == null) ? null : this.processorCapabilities.iterator(); } public void addToProcessorCapabilities(java.lang.String elem) { if (this.processorCapabilities == null) { this.processorCapabilities = new java.util.ArrayList<java.lang.String>(); } this.processorCapabilities.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<java.lang.String> getProcessorCapabilities() { return this.processorCapabilities; } public void setProcessorCapabilities(@org.apache.thrift.annotation.Nullable java.util.List<java.lang.String> processorCapabilities) { this.processorCapabilities = processorCapabilities; } public void unsetProcessorCapabilities() { this.processorCapabilities = null; } /** Returns true if field processorCapabilities is set (has been assigned a value) and false otherwise */ public boolean isSetProcessorCapabilities() { return this.processorCapabilities != null; } public void setProcessorCapabilitiesIsSet(boolean value) { if (!value) { this.processorCapabilities = null; } } @org.apache.thrift.annotation.Nullable public java.lang.String getProcessorIdentifier() { return this.processorIdentifier; } public void setProcessorIdentifier(@org.apache.thrift.annotation.Nullable java.lang.String processorIdentifier) { this.processorIdentifier = processorIdentifier; } public void unsetProcessorIdentifier() { this.processorIdentifier = null; } /** Returns true if field processorIdentifier is set (has been assigned a value) and false otherwise */ public boolean isSetProcessorIdentifier() { return this.processorIdentifier != null; } public void setProcessorIdentifierIsSet(boolean value) { if (!value) { this.processorIdentifier = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case CATALOG: if (value == null) { unsetCatalog(); } else { setCatalog((java.lang.String)value); } break; case DATABASE: if (value == null) { unsetDatabase(); } else { setDatabase((java.lang.String)value); } break; case TABLE_NAME_PATTERN: if (value == null) { unsetTableNamePattern(); } else { setTableNamePattern((java.lang.String)value); } break; case REQUESTED_FIELDS: if (value == null) { unsetRequestedFields(); } else { setRequestedFields((java.lang.Integer)value); } break; case LIMIT: if (value == null) { unsetLimit(); } else { setLimit((java.lang.Integer)value); } break; case PROCESSOR_CAPABILITIES: if (value == null) { unsetProcessorCapabilities(); } else { setProcessorCapabilities((java.util.List<java.lang.String>)value); } break; case PROCESSOR_IDENTIFIER: if (value == null) { unsetProcessorIdentifier(); } else { setProcessorIdentifier((java.lang.String)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case CATALOG: return getCatalog(); case DATABASE: return getDatabase(); case TABLE_NAME_PATTERN: return getTableNamePattern(); case REQUESTED_FIELDS: return getRequestedFields(); case LIMIT: return getLimit(); case PROCESSOR_CAPABILITIES: return getProcessorCapabilities(); case PROCESSOR_IDENTIFIER: return getProcessorIdentifier(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case CATALOG: return isSetCatalog(); case DATABASE: return isSetDatabase(); case TABLE_NAME_PATTERN: return isSetTableNamePattern(); case REQUESTED_FIELDS: return isSetRequestedFields(); case LIMIT: return isSetLimit(); case PROCESSOR_CAPABILITIES: return isSetProcessorCapabilities(); case PROCESSOR_IDENTIFIER: return isSetProcessorIdentifier(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof GetTablesExtRequest) return this.equals((GetTablesExtRequest)that); return false; } public boolean equals(GetTablesExtRequest that) { if (that == null) return false; if (this == that) return true; boolean this_present_catalog = true && this.isSetCatalog(); boolean that_present_catalog = true && that.isSetCatalog(); if (this_present_catalog || that_present_catalog) { if (!(this_present_catalog && that_present_catalog)) return false; if (!this.catalog.equals(that.catalog)) return false; } boolean this_present_database = true && this.isSetDatabase(); boolean that_present_database = true && that.isSetDatabase(); if (this_present_database || that_present_database) { if (!(this_present_database && that_present_database)) return false; if (!this.database.equals(that.database)) return false; } boolean this_present_tableNamePattern = true && this.isSetTableNamePattern(); boolean that_present_tableNamePattern = true && that.isSetTableNamePattern(); if (this_present_tableNamePattern || that_present_tableNamePattern) { if (!(this_present_tableNamePattern && that_present_tableNamePattern)) return false; if (!this.tableNamePattern.equals(that.tableNamePattern)) return false; } boolean this_present_requestedFields = true; boolean that_present_requestedFields = true; if (this_present_requestedFields || that_present_requestedFields) { if (!(this_present_requestedFields && that_present_requestedFields)) return false; if (this.requestedFields != that.requestedFields) return false; } boolean this_present_limit = true && this.isSetLimit(); boolean that_present_limit = true && that.isSetLimit(); if (this_present_limit || that_present_limit) { if (!(this_present_limit && that_present_limit)) return false; if (this.limit != that.limit) return false; } boolean this_present_processorCapabilities = true && this.isSetProcessorCapabilities(); boolean that_present_processorCapabilities = true && that.isSetProcessorCapabilities(); if (this_present_processorCapabilities || that_present_processorCapabilities) { if (!(this_present_processorCapabilities && that_present_processorCapabilities)) return false; if (!this.processorCapabilities.equals(that.processorCapabilities)) return false; } boolean this_present_processorIdentifier = true && this.isSetProcessorIdentifier(); boolean that_present_processorIdentifier = true && that.isSetProcessorIdentifier(); if (this_present_processorIdentifier || that_present_processorIdentifier) { if (!(this_present_processorIdentifier && that_present_processorIdentifier)) return false; if (!this.processorIdentifier.equals(that.processorIdentifier)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetCatalog()) ? 131071 : 524287); if (isSetCatalog()) hashCode = hashCode * 8191 + catalog.hashCode(); hashCode = hashCode * 8191 + ((isSetDatabase()) ? 131071 : 524287); if (isSetDatabase()) hashCode = hashCode * 8191 + database.hashCode(); hashCode = hashCode * 8191 + ((isSetTableNamePattern()) ? 131071 : 524287); if (isSetTableNamePattern()) hashCode = hashCode * 8191 + tableNamePattern.hashCode(); hashCode = hashCode * 8191 + requestedFields; hashCode = hashCode * 8191 + ((isSetLimit()) ? 131071 : 524287); if (isSetLimit()) hashCode = hashCode * 8191 + limit; hashCode = hashCode * 8191 + ((isSetProcessorCapabilities()) ? 131071 : 524287); if (isSetProcessorCapabilities()) hashCode = hashCode * 8191 + processorCapabilities.hashCode(); hashCode = hashCode * 8191 + ((isSetProcessorIdentifier()) ? 131071 : 524287); if (isSetProcessorIdentifier()) hashCode = hashCode * 8191 + processorIdentifier.hashCode(); return hashCode; } @Override public int compareTo(GetTablesExtRequest other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetCatalog(), other.isSetCatalog()); if (lastComparison != 0) { return lastComparison; } if (isSetCatalog()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.catalog, other.catalog); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetDatabase(), other.isSetDatabase()); if (lastComparison != 0) { return lastComparison; } if (isSetDatabase()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.database, other.database); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetTableNamePattern(), other.isSetTableNamePattern()); if (lastComparison != 0) { return lastComparison; } if (isSetTableNamePattern()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.tableNamePattern, other.tableNamePattern); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetRequestedFields(), other.isSetRequestedFields()); if (lastComparison != 0) { return lastComparison; } if (isSetRequestedFields()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.requestedFields, other.requestedFields); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetLimit(), other.isSetLimit()); if (lastComparison != 0) { return lastComparison; } if (isSetLimit()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.limit, other.limit); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetProcessorCapabilities(), other.isSetProcessorCapabilities()); if (lastComparison != 0) { return lastComparison; } if (isSetProcessorCapabilities()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.processorCapabilities, other.processorCapabilities); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetProcessorIdentifier(), other.isSetProcessorIdentifier()); if (lastComparison != 0) { return lastComparison; } if (isSetProcessorIdentifier()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.processorIdentifier, other.processorIdentifier); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("GetTablesExtRequest("); boolean first = true; sb.append("catalog:"); if (this.catalog == null) { sb.append("null"); } else { sb.append(this.catalog); } first = false; if (!first) sb.append(", "); sb.append("database:"); if (this.database == null) { sb.append("null"); } else { sb.append(this.database); } first = false; if (!first) sb.append(", "); sb.append("tableNamePattern:"); if (this.tableNamePattern == null) { sb.append("null"); } else { sb.append(this.tableNamePattern); } first = false; if (!first) sb.append(", "); sb.append("requestedFields:"); sb.append(this.requestedFields); first = false; if (isSetLimit()) { if (!first) sb.append(", "); sb.append("limit:"); sb.append(this.limit); first = false; } if (isSetProcessorCapabilities()) { if (!first) sb.append(", "); sb.append("processorCapabilities:"); if (this.processorCapabilities == null) { sb.append("null"); } else { sb.append(this.processorCapabilities); } first = false; } if (isSetProcessorIdentifier()) { if (!first) sb.append(", "); sb.append("processorIdentifier:"); if (this.processorIdentifier == null) { sb.append("null"); } else { sb.append(this.processorIdentifier); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (!isSetCatalog()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'catalog' is unset! Struct:" + toString()); } if (!isSetDatabase()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'database' is unset! Struct:" + toString()); } if (!isSetTableNamePattern()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'tableNamePattern' is unset! Struct:" + toString()); } if (!isSetRequestedFields()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'requestedFields' is unset! Struct:" + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class GetTablesExtRequestStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public GetTablesExtRequestStandardScheme getScheme() { return new GetTablesExtRequestStandardScheme(); } } private static class GetTablesExtRequestStandardScheme extends org.apache.thrift.scheme.StandardScheme<GetTablesExtRequest> { public void read(org.apache.thrift.protocol.TProtocol iprot, GetTablesExtRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // CATALOG if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.catalog = iprot.readString(); struct.setCatalogIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DATABASE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.database = iprot.readString(); struct.setDatabaseIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TABLE_NAME_PATTERN if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.tableNamePattern = iprot.readString(); struct.setTableNamePatternIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // REQUESTED_FIELDS if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.requestedFields = iprot.readI32(); struct.setRequestedFieldsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // LIMIT if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.limit = iprot.readI32(); struct.setLimitIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // PROCESSOR_CAPABILITIES if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list1238 = iprot.readListBegin(); struct.processorCapabilities = new java.util.ArrayList<java.lang.String>(_list1238.size); @org.apache.thrift.annotation.Nullable java.lang.String _elem1239; for (int _i1240 = 0; _i1240 < _list1238.size; ++_i1240) { _elem1239 = iprot.readString(); struct.processorCapabilities.add(_elem1239); } iprot.readListEnd(); } struct.setProcessorCapabilitiesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // PROCESSOR_IDENTIFIER if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.processorIdentifier = iprot.readString(); struct.setProcessorIdentifierIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, GetTablesExtRequest struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.catalog != null) { oprot.writeFieldBegin(CATALOG_FIELD_DESC); oprot.writeString(struct.catalog); oprot.writeFieldEnd(); } if (struct.database != null) { oprot.writeFieldBegin(DATABASE_FIELD_DESC); oprot.writeString(struct.database); oprot.writeFieldEnd(); } if (struct.tableNamePattern != null) { oprot.writeFieldBegin(TABLE_NAME_PATTERN_FIELD_DESC); oprot.writeString(struct.tableNamePattern); oprot.writeFieldEnd(); } oprot.writeFieldBegin(REQUESTED_FIELDS_FIELD_DESC); oprot.writeI32(struct.requestedFields); oprot.writeFieldEnd(); if (struct.isSetLimit()) { oprot.writeFieldBegin(LIMIT_FIELD_DESC); oprot.writeI32(struct.limit); oprot.writeFieldEnd(); } if (struct.processorCapabilities != null) { if (struct.isSetProcessorCapabilities()) { oprot.writeFieldBegin(PROCESSOR_CAPABILITIES_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.processorCapabilities.size())); for (java.lang.String _iter1241 : struct.processorCapabilities) { oprot.writeString(_iter1241); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } } if (struct.processorIdentifier != null) { if (struct.isSetProcessorIdentifier()) { oprot.writeFieldBegin(PROCESSOR_IDENTIFIER_FIELD_DESC); oprot.writeString(struct.processorIdentifier); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class GetTablesExtRequestTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public GetTablesExtRequestTupleScheme getScheme() { return new GetTablesExtRequestTupleScheme(); } } private static class GetTablesExtRequestTupleScheme extends org.apache.thrift.scheme.TupleScheme<GetTablesExtRequest> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, GetTablesExtRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; oprot.writeString(struct.catalog); oprot.writeString(struct.database); oprot.writeString(struct.tableNamePattern); oprot.writeI32(struct.requestedFields); java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetLimit()) { optionals.set(0); } if (struct.isSetProcessorCapabilities()) { optionals.set(1); } if (struct.isSetProcessorIdentifier()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetLimit()) { oprot.writeI32(struct.limit); } if (struct.isSetProcessorCapabilities()) { { oprot.writeI32(struct.processorCapabilities.size()); for (java.lang.String _iter1242 : struct.processorCapabilities) { oprot.writeString(_iter1242); } } } if (struct.isSetProcessorIdentifier()) { oprot.writeString(struct.processorIdentifier); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, GetTablesExtRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; struct.catalog = iprot.readString(); struct.setCatalogIsSet(true); struct.database = iprot.readString(); struct.setDatabaseIsSet(true); struct.tableNamePattern = iprot.readString(); struct.setTableNamePatternIsSet(true); struct.requestedFields = iprot.readI32(); struct.setRequestedFieldsIsSet(true); java.util.BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.limit = iprot.readI32(); struct.setLimitIsSet(true); } if (incoming.get(1)) { { org.apache.thrift.protocol.TList _list1243 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRING); struct.processorCapabilities = new java.util.ArrayList<java.lang.String>(_list1243.size); @org.apache.thrift.annotation.Nullable java.lang.String _elem1244; for (int _i1245 = 0; _i1245 < _list1243.size; ++_i1245) { _elem1244 = iprot.readString(); struct.processorCapabilities.add(_elem1244); } } struct.setProcessorCapabilitiesIsSet(true); } if (incoming.get(2)) { struct.processorIdentifier = iprot.readString(); struct.setProcessorIdentifierIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
google/j2objc
37,703
jre_emul/android/platform/libcore/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/LinkedListTest.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.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Spliterator; import libcore.java.util.ForEachRemainingTester; import libcore.java.util.SpliteratorTester; import org.apache.harmony.testframework.serialization.SerializationTest; import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; import tests.support.Support_ListTest; import static libcore.java.util.RemoveIfTester.*; public class LinkedListTest extends junit.framework.TestCase { LinkedList ll; LinkedList<Object> testList; private Object testObjOne; private Object testObjTwo; private Object testObjThree; private Object testObjFour; private Object testObjLast; Object[] objArray; /** * java.util.LinkedList#LinkedList() */ public void test_Constructor() { // Test for method java.util.LinkedList() new Support_ListTest("", ll).runTest(); LinkedList subList = new LinkedList(); for (int i = -50; i < 150; i++) subList.add(new Integer(i)); new Support_ListTest("", subList.subList(50, 150)).runTest(); } /** * java.util.LinkedList#LinkedList(java.util.Collection) */ public void test_ConstructorLjava_util_Collection() { // Test for method java.util.LinkedList(java.util.Collection) assertTrue("Incorrect LinkedList constructed", new LinkedList(ll) .equals(ll)); try { new LinkedList(null); fail("NullPointerException expected"); } catch (NullPointerException e) { //expected } } /** * java.util.LinkedList#add(int, java.lang.Object) */ public void test_addILjava_lang_Object() { // Test for method void java.util.LinkedList.add(int, java.lang.Object) Object o; ll.add(50, o = "Test"); assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll .get(50) == o); assertTrue("Failed to fix up list after insert", ll.get(51) == objArray[50] && (ll.get(52) == objArray[51])); ll.add(50, null); assertNull("Did not add null correctly", ll.get(50)); try { ll.add(-1, "Test"); fail("Should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Excepted } try { ll.add(-1, null); fail("Should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Excepted } try { ll.add(ll.size() + 1, "Test"); fail("Should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Excepted } try { ll.add(ll.size() + 1, null); fail("Should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // Excepted } } /** * java.util.LinkedList#add(java.lang.Object) */ public void test_addLjava_lang_Object() { // Test for method boolean java.util.LinkedList.add(java.lang.Object) Object o; ll.add(o = new Object()); assertTrue("Failed to add Object", ll.getLast() == o); ll.add(null); assertNull("Did not add null correctly", ll.get(ll.size() - 1)); } /** * java.util.LinkedList#addAll(int, java.util.Collection) */ public void test_addAllILjava_util_Collection() { // Test for method boolean java.util.LinkedList.addAll(int, // java.util.Collection) ll.addAll(50, (Collection) ll.clone()); assertEquals("Returned incorrect size after adding to existing list", 200, ll .size()); for (int i = 0; i < 50; i++) assertTrue("Manipulated elements < index", ll.get(i) == objArray[i]); for (int i = 0; i >= 50 && (i < 150); i++) assertTrue("Failed to ad elements properly", ll.get(i) == objArray[i - 50]); for (int i = 0; i >= 150 && (i < 200); i++) assertTrue("Failed to ad elements properly", ll.get(i) == objArray[i - 100]); List myList = new LinkedList(); myList.add(null); myList.add("Blah"); myList.add(null); myList.add("Booga"); myList.add(null); ll.addAll(50, myList); assertNull("a) List w/nulls not added correctly", ll.get(50)); assertEquals("b) List w/nulls not added correctly", "Blah", ll.get(51)); assertNull("c) List w/nulls not added correctly", ll.get(52)); assertEquals("d) List w/nulls not added correctly", "Booga", ll.get(53)); assertNull("e) List w/nulls not added correctly", ll.get(54)); try { ll.addAll(-1, (Collection) null); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { //expected } try { ll.addAll(ll.size() + 1, (Collection) null); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { //expected } try { ll.addAll(0, null); fail("NullPointerException expected"); } catch (NullPointerException e) { //expected } } /** * java.util.LinkedList#addAll(int, java.util.Collection) */ public void test_addAllILjava_util_Collection_2() { // Regression for HARMONY-467 LinkedList obj = new LinkedList(); try { obj.addAll(-1, (Collection) null); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { } } /** * java.util.LinkedList#addAll(java.util.Collection) */ public void test_addAllLjava_util_Collection() { // Test for method boolean // java.util.LinkedList.addAll(java.util.Collection) List l = new ArrayList(); l.addAll((Collection) ll.clone()); for (int i = 0; i < ll.size(); i++) assertTrue("Failed to add elements properly", l.get(i).equals( ll.get(i))); ll.addAll((Collection) ll.clone()); assertEquals("Returned incorrect siZe after adding to existing list", 200, ll .size()); for (int i = 0; i < 100; i++) { assertTrue("Added to list in incorrect order", ll.get(i).equals( l.get(i))); assertTrue("Failed to add to existing list", ll.get(i + 100) .equals(l.get(i))); } List myList = new LinkedList(); myList.add(null); myList.add("Blah"); myList.add(null); myList.add("Booga"); myList.add(null); ll.addAll(myList); assertNull("a) List w/nulls not added correctly", ll.get(200)); assertEquals("b) List w/nulls not added correctly", "Blah", ll.get(201)); assertNull("c) List w/nulls not added correctly", ll.get(202)); assertEquals("d) List w/nulls not added correctly", "Booga", ll.get(203)); assertNull("e) List w/nulls not added correctly", ll.get(204)); try { ll.addAll(null); fail("Should throw NullPointerException"); } catch (NullPointerException e) { // Excepted } } public void test_addAll_Self_Ljava_util_Collection() { LinkedList linkedList = new LinkedList(); linkedList.addLast(1); assertEquals(1, linkedList.size()); assertTrue(linkedList.addAll(linkedList)); assertEquals(2, linkedList.size()); } public void test_addAll_Self_ILjava_util_Collection() { LinkedList linkedList = new LinkedList(); linkedList.addLast(1); assertEquals(1, linkedList.size()); assertTrue(linkedList.addAll(1, linkedList)); assertEquals(2, linkedList.size()); } /** * java.util.LinkedList#addFirst(java.lang.Object) */ public void test_addFirstLjava_lang_Object() { // Test for method void java.util.LinkedList.addFirst(java.lang.Object) Object o; ll.addFirst(o = new Object()); assertTrue("Failed to add Object", ll.getFirst() == o); ll.addFirst(null); assertNull("Failed to add null", ll.getFirst()); } /** * java.util.LinkedList#addLast(java.lang.Object) */ public void test_addLastLjava_lang_Object() { // Test for method void java.util.LinkedList.addLast(java.lang.Object) Object o; ll.addLast(o = new Object()); assertTrue("Failed to add Object", ll.getLast() == o); ll.addLast(null); assertNull("Failed to add null", ll.getLast()); } /** * java.util.LinkedList#clear() */ public void test_clear() { // Test for method void java.util.LinkedList.clear() ll.clear(); for (int i = 0; i < ll.size(); i++) assertNull("Failed to clear list", ll.get(i)); } /** * java.util.LinkedList#clone() */ public void test_clone() { // Test for method java.lang.Object java.util.LinkedList.clone() Object x = ll.clone(); assertTrue("Cloned list was inequal to cloned", x.equals(ll)); for (int i = 0; i < ll.size(); i++) assertTrue("Cloned list contains incorrect elements", ll.get(i) .equals(((LinkedList) x).get(i))); ll.addFirst(null); x = ll.clone(); assertTrue("List with a null did not clone properly", ll.equals(x)); } /** * java.util.LinkedList#contains(java.lang.Object) */ public void test_containsLjava_lang_Object() { // Test for method boolean // java.util.LinkedList.contains(java.lang.Object) assertTrue("Returned false for valid element", ll .contains(objArray[99])); assertTrue("Returned false for equal element", ll.contains(new Integer( 8))); assertTrue("Returned true for invalid element", !ll .contains(new Object())); assertTrue("Should not contain null", !ll.contains(null)); ll.add(25, null); assertTrue("Should contain null", ll.contains(null)); } /** * java.util.LinkedList#get(int) */ public void test_getI() { // Test for method java.lang.Object java.util.LinkedList.get(int) assertTrue("Returned incorrect element", ll.get(22) == objArray[22]); try { ll.get(8765); fail("Failed to throw expected exception for index > size"); } catch (IndexOutOfBoundsException e) { } } /** * {@link java.util.LinkedList#peek()} */ public void test_peek() { LinkedList list = new LinkedList(); assertNull("Should return null if this list is empty", list.peek()); assertEquals("Returned incorrect first element", ll.peek(), objArray[0]); assertEquals("Peek remove the head (first element) of this list", ll.getFirst(), objArray[0]); } /** * java.util.LinkedList#getFirst() */ public void test_getFirst() { // Test for method java.lang.Object java.util.LinkedList.getFirst() assertTrue("Returned incorrect first element", ll.getFirst().equals( objArray[0])); LinkedList list = new LinkedList(); try { list.getFirst(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { // Excepted } } /** * java.util.LinkedList#getLast() */ public void test_getLast() { // Test for method java.lang.Object java.util.LinkedList.getLast() assertTrue("Returned incorrect first element", ll.getLast().equals( objArray[objArray.length - 1])); LinkedList list = new LinkedList(); try { list.getLast(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { // Excepted } } /** * java.util.LinkedList#indexOf(java.lang.Object) */ public void test_indexOfLjava_lang_Object() { // Test for method int java.util.LinkedList.indexOf(java.lang.Object) assertEquals("Returned incorrect index", 87, ll.indexOf(objArray[87])); assertEquals("Returned index for invalid Object", -1, ll .indexOf(new Object())); ll.add(20, null); ll.add(24, null); assertTrue("Index of null should be 20, but got: " + ll.indexOf(null), ll.indexOf(null) == 20); } /** * java.util.LinkedList#lastIndexOf(java.lang.Object) */ public void test_lastIndexOfLjava_lang_Object() { // Test for method int // java.util.LinkedList.lastIndexOf(java.lang.Object) ll.add(new Integer(99)); assertEquals("Returned incorrect index", 100, ll.lastIndexOf(objArray[99])); assertEquals("Returned index for invalid Object", -1, ll .lastIndexOf(new Object())); ll.add(20, null); ll.add(24, null); assertTrue("Last index of null should be 20, but got: " + ll.lastIndexOf(null), ll.lastIndexOf(null) == 24); } /** * java.util.LinkedList#listIterator(int) */ public void test_listIteratorI() { // Test for method java.util.ListIterator // java.util.LinkedList.listIterator(int) ListIterator i1 = ll.listIterator(); ListIterator i2 = ll.listIterator(0); Object elm; int n = 0; while (i2.hasNext()) { if (n == 0 || n == objArray.length - 1) { if (n == 0) assertTrue("First element claimed to have a previous", !i2 .hasPrevious()); if (n == objArray.length) assertTrue("Last element claimed to have next", !i2 .hasNext()); } elm = i2.next(); assertTrue("Iterator returned elements in wrong order", elm == objArray[n]); if (n > 0 && n < objArray.length - 1) { assertTrue("Next index returned incorrect value", i2.nextIndex() == n + 1); assertTrue("previousIndex returned incorrect value : " + i2.previousIndex() + ", n val: " + n, i2 .previousIndex() == n); } elm = i1.next(); assertTrue("Iterator returned elements in wrong order", elm == objArray[n]); ++n; } i2 = ll.listIterator(ll.size()/2); assertTrue((Integer)i2.next() == ll.size()/2); List myList = new LinkedList(); myList.add(null); myList.add("Blah"); myList.add(null); myList.add("Booga"); myList.add(null); ListIterator li = myList.listIterator(); assertTrue("li.hasPrevious() should be false", !li.hasPrevious()); assertNull("li.next() should be null", li.next()); assertTrue("li.hasPrevious() should be true", li.hasPrevious()); assertNull("li.prev() should be null", li.previous()); assertNull("li.next() should be null", li.next()); assertEquals("li.next() should be Blah", "Blah", li.next()); assertNull("li.next() should be null", li.next()); assertEquals("li.next() should be Booga", "Booga", li.next()); assertTrue("li.hasNext() should be true", li.hasNext()); assertNull("li.next() should be null", li.next()); assertTrue("li.hasNext() should be false", !li.hasNext()); try { ll.listIterator(-1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { //expected } try { ll.listIterator(ll.size() + 1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { //expected } } /** * java.util.LinkedList#remove(int) */ public void test_removeI() { // Test for method java.lang.Object java.util.LinkedList.remove(int) ll.remove(10); assertEquals("Failed to remove element", -1, ll.indexOf(objArray[10])); try { ll.remove(999); fail("Failed to throw expected exception when index out of range"); } catch (IndexOutOfBoundsException e) { // Correct } ll.add(20, null); ll.remove(20); assertNotNull("Should have removed null", ll.get(20)); } /** * java.util.LinkedList#remove(java.lang.Object) */ public void test_removeLjava_lang_Object() { // Test for method boolean java.util.LinkedList.remove(java.lang.Object) assertTrue("Failed to remove valid Object", ll.remove(objArray[87])); assertTrue("Removed invalid object", !ll.remove(new Object())); assertEquals("Found Object after removal", -1, ll.indexOf(objArray[87])); ll.add(null); ll.remove(null); assertTrue("Should not contain null afrer removal", !ll.contains(null)); } /** * java.util.LinkedList#removeFirst() */ public void test_removeFirst() { // Test for method java.lang.Object java.util.LinkedList.removeFirst() ll.removeFirst(); assertTrue("Failed to remove first element", ll.getFirst() != objArray[0]); LinkedList list = new LinkedList(); try { list.removeFirst(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { // Excepted } } /** * java.util.LinkedList#removeLast() */ public void test_removeLast() { // Test for method java.lang.Object java.util.LinkedList.removeLast() ll.removeLast(); assertTrue("Failed to remove last element", ll.getLast() != objArray[objArray.length - 1]); LinkedList list = new LinkedList(); try { list.removeLast(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { // Excepted } } /** * java.util.LinkedList#set(int, java.lang.Object) */ public void test_setILjava_lang_Object() { // Test for method java.lang.Object java.util.LinkedList.set(int, // java.lang.Object) Object obj; ll.set(65, obj = new Object()); assertTrue("Failed to set object", ll.get(65) == obj); try { ll.set(-1, obj = new Object()); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { //expected } try { ll.set(ll.size() + 1, obj = new Object()); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { //expected } } /** * java.util.LinkedList#size() */ public void test_size() { // Test for method int java.util.LinkedList.size() assertTrue("Returned incorrect size", ll.size() == objArray.length); ll.removeFirst(); assertTrue("Returned incorrect size", ll.size() == objArray.length - 1); } /** * java.util.LinkedList#toArray() */ public void test_toArray() { // Test for method java.lang.Object [] java.util.LinkedList.toArray() ll.add(null); Object[] obj = ll.toArray(); assertEquals("Returned array of incorrect size", objArray.length + 1, obj.length); for (int i = 0; i < obj.length - 1; i++) assertTrue("Returned incorrect array: " + i, obj[i] == objArray[i]); assertNull("Returned incorrect array--end isn't null", obj[obj.length - 1]); } /** * java.util.LinkedList#toArray(java.lang.Object[]) */ public void test_toArray$Ljava_lang_Object() { // Test for method java.lang.Object [] // java.util.LinkedList.toArray(java.lang.Object []) Integer[] argArray = new Integer[100]; Object[] retArray; retArray = ll.toArray(argArray); assertTrue("Returned different array than passed", retArray == argArray); List retList = new LinkedList(Arrays.asList(retArray)); Iterator li = ll.iterator(); Iterator ri = retList.iterator(); while (li.hasNext()) assertTrue("Lists are not equal", li.next() == ri.next()); argArray = new Integer[1000]; retArray = ll.toArray(argArray); assertNull("Failed to set first extra element to null", argArray[ll .size()]); for (int i = 0; i < ll.size(); i++) assertTrue("Returned incorrect array: " + i, retArray[i] == objArray[i]); ll.add(50, null); argArray = new Integer[101]; retArray = ll.toArray(argArray); assertTrue("Returned different array than passed", retArray == argArray); retArray = ll.toArray(argArray); assertTrue("Returned different array than passed", retArray == argArray); retList = new LinkedList(Arrays.asList(retArray)); li = ll.iterator(); ri = retList.iterator(); while (li.hasNext()) assertTrue("Lists are not equal", li.next() == ri.next()); try { ll.toArray(null); fail("NullPointerException expected"); } catch (NullPointerException e) { //expected } LinkedList<String> lls = new LinkedList<String>(); lls.add("First"); lls.add("Second"); try { lls.toArray(argArray); fail("ArrayStoreException expected"); } catch (ArrayStoreException e) { //expected } } public void test_offer() { int origSize = ll.size(); assertTrue("offer() should return true'", ll.offer(objArray[0])); assertEquals("offer() should add an element as the last one", origSize, ll.lastIndexOf(objArray[0])); } public void test_poll() { for (int i = 0; i < objArray.length; i++) { assertEquals("should remove the head", objArray[i], ll.poll()); } assertEquals("should be empty", 0, ll.size()); assertNull("should return 'null' if list is empty", ll.poll()); } public void test_remove() { for (int i = 0; i < objArray.length; i++) { assertEquals("should remove the head", objArray[i], ll.remove()); } assertEquals("should be empty", 0, ll.size()); try { ll.remove(); fail("NoSuchElementException is expected when removing from the empty list"); } catch (NoSuchElementException e) { //-- expected } } public void test_element() { assertEquals("should return the head", objArray[0], ll.element()); assertEquals("element() should remove nothing", objArray.length, ll.size()); try { new LinkedList().remove(); fail("NoSuchElementException is expected when the list is empty"); } catch (NoSuchElementException e) { //-- expected } } /** * {@link java.util.LinkedList#removeFirstOccurrence(Object)} */ public void test_removeFirstOccurrence() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjThree)); assertTrue(testList.offerLast(testObjOne)); assertEquals(5, testList.size()); assertTrue(testList.removeFirstOccurrence(testObjOne)); assertFalse(testList.removeFirstOccurrence(testObjFour)); assertEquals(testObjTwo, testList.peekFirst()); assertEquals(testObjOne, testList.peekLast()); assertEquals(4, testList.size()); assertTrue(testList.removeFirstOccurrence(testObjOne)); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.peekLast()); assertTrue(testList.removeFirstOccurrence(testObjOne)); assertEquals(2, testList.size()); assertEquals(testObjThree, testList.peekLast()); assertFalse(testList.removeFirstOccurrence(testObjOne)); } /** * {@link java.util.LinkedList#removeLastOccurrence(Object)} */ public void test_removeLastOccurrence() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjThree)); assertTrue(testList.offerLast(testObjOne)); assertEquals(5, testList.size()); assertTrue(testList.removeLastOccurrence(testObjOne)); assertFalse(testList.removeLastOccurrence(testObjFour)); assertEquals(testObjOne, testList.peekFirst()); assertEquals(testObjThree, testList.peekLast()); assertEquals(4, testList.size()); assertTrue(testList.removeLastOccurrence(testObjOne)); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.peekFirst()); assertEquals(testObjThree, testList.peekLast()); assertTrue(testList.removeLastOccurrence(testObjOne)); assertEquals(2, testList.size()); assertEquals(testObjThree, testList.peekLast()); assertFalse(testList.removeLastOccurrence(testObjOne)); } /** * {@link java.util.LinkedList#offerFirst(Object)} */ public void test_offerFirst() throws Exception { assertTrue(testList.offerFirst(testObjOne)); assertEquals(1, testList.size()); assertEquals(testObjOne, testList.peek()); assertTrue(testList.offerFirst(testObjOne)); assertEquals(2, testList.size()); assertEquals(testObjOne, testList.peek()); assertTrue(testList.offerFirst(testObjTwo)); assertEquals(3, testList.size()); assertEquals(testObjTwo, testList.peek()); assertEquals(testObjOne, testList.getLast()); assertTrue(testList.offerFirst(null)); assertEquals(4, testList.size()); } /** * {@link java.util.LinkedList#offerLast(Object)} */ public void test_offerLast() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertEquals(1, testList.size()); assertEquals(testObjOne, testList.peek()); assertTrue(testList.offerLast(testObjOne)); assertEquals(2, testList.size()); assertEquals(testObjOne, testList.peek()); assertTrue(testList.offerLast(testObjTwo)); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.peek()); assertEquals(testObjTwo, testList.getLast()); assertTrue(testList.offerLast(null)); assertEquals(4, testList.size()); } /** * {@link java.util.LinkedList#push(Object)} */ public void test_push() throws Exception { testList.push(testObjOne); assertEquals(1, testList.size()); assertEquals(testObjOne, testList.peek()); testList.push(testObjOne); assertEquals(2, testList.size()); assertEquals(testObjOne, testList.peek()); testList.push(testObjTwo); assertEquals(3, testList.size()); assertEquals(testObjTwo, testList.peek()); assertEquals(testObjOne, testList.getLast()); testList.push(null); assertEquals(4, testList.size()); } /** * {@link java.util.LinkedList#pop()} */ public void test_pop() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjThree)); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.pop()); assertEquals(2, testList.size()); assertEquals(testObjTwo, testList.pop()); assertEquals(testObjThree, testList.pop()); assertEquals(0, testList.size()); testList.push(null); assertEquals(1, testList.size()); assertNull(testList.pop()); try { testList.pop(); fail("should throw NoSuchElementException "); } catch (NoSuchElementException e) { // expected } } /** * {@link java.util.LinkedList#descendingIterator()} */ public void test_descendingIterator() throws Exception { assertFalse(testList.descendingIterator().hasNext()); assertTrue(testList.add(testObjOne)); assertTrue(testList.add(testObjTwo)); assertTrue(testList.add(testObjOne)); assertTrue(testList.add(testObjThree)); assertTrue(testList.add(testObjLast)); Iterator result = testList.descendingIterator(); assertEquals(5, testList.size()); try { result.remove(); fail("should throw IllegalStateException"); } catch (IllegalStateException e) { // expected } assertTrue(testList.add(testObjFour)); try { assertEquals(testObjLast, result.next()); fail("should throw ConcurrentModificationException"); } catch (ConcurrentModificationException e) { // expected } result = testList.descendingIterator(); assertEquals(testObjFour, result.next()); assertEquals(testObjLast, result.next()); assertEquals(testObjThree, result.next()); assertEquals(testObjOne, result.next()); assertEquals(testObjTwo, result.next()); assertTrue(result.hasNext()); result.remove(); assertEquals(testObjOne, result.next()); assertFalse(result.hasNext()); try { result.next(); fail("should throw NoSuchElementException"); } catch (NoSuchElementException e) { // expected } } /** * {@link java.util.LinkedList#pollFirst()} */ public void test_pollFirst() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjThree)); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.pollFirst()); assertEquals(2, testList.size()); assertEquals(testObjTwo, testList.pollFirst()); assertEquals(testObjThree, testList.pollFirst()); assertEquals(0, testList.size()); assertNull(testList.pollFirst()); } /** * {@link java.util.LinkedList#pollLast()} */ public void test_pollLast() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjThree)); assertEquals(3, testList.size()); assertEquals(testObjThree, testList.pollLast()); assertEquals(2, testList.size()); assertEquals(testObjTwo, testList.pollLast()); assertEquals(testObjOne, testList.pollLast()); assertEquals(0, testList.size()); assertNull(testList.pollFirst()); } /** * {@link java.util.LinkedList#peekFirst()} */ public void test_peekFirst() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjThree)); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.peekFirst()); assertEquals(3, testList.size()); assertEquals(testObjOne, testList.pollFirst()); assertEquals(testObjTwo, testList.peekFirst()); assertEquals(testObjTwo, testList.pollFirst()); assertEquals(testObjThree, testList.pollFirst()); assertEquals(0, testList.size()); assertEquals(null, testList.peekFirst()); } /** * {@link java.util.LinkedList#peek()} */ public void test_peekLast() throws Exception { assertTrue(testList.offerLast(testObjOne)); assertTrue(testList.offerLast(testObjTwo)); assertTrue(testList.offerLast(testObjThree)); assertEquals(3, testList.size()); assertEquals(testObjThree, testList.peekLast()); assertEquals(3, testList.size()); assertEquals(testObjThree, testList.pollLast()); assertEquals(testObjTwo, testList.peekLast()); assertEquals(testObjTwo, testList.pollLast()); assertEquals(testObjOne, testList.pollLast()); assertEquals(0, testList.size()); assertNull(testList.peekLast()); } public void test_forEachRemaining_iterator() throws Exception { ForEachRemainingTester.runTests(LinkedList::new, new String[]{ "foo", "bar", "baz "}); ForEachRemainingTester.runTests(LinkedList::new, new String[] { "foo" }); } public void test_spliterator() throws Exception { ArrayList<Integer> testElements = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)); LinkedList<Integer> list = new LinkedList<>(); list.addAll(testElements); SpliteratorTester.runBasicIterationTests(list.spliterator(), testElements); SpliteratorTester.runBasicSplitTests(list, testElements); SpliteratorTester.testSpliteratorNPE(list.spliterator()); assertTrue(list.spliterator().hasCharacteristics( Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED)); SpliteratorTester.runOrderedTests(list); SpliteratorTester.runSizedTests(list, 16 /* expected size */); SpliteratorTester.runSubSizedTests(list, 16 /* expected size */); SpliteratorTester.assertSupportsTrySplit(list); } public void test_spliterator_CME() throws Exception { LinkedList<Integer> list = new LinkedList<>(); list.add(52); Spliterator<Integer> sp = list.spliterator(); try { sp.tryAdvance(value -> list.add(value)); fail(); } catch (ConcurrentModificationException expected) { } try { sp.forEachRemaining(value -> list.add(value)); fail(); } catch (ConcurrentModificationException expected) { } } public void test_removeIf() { runBasicRemoveIfTests(LinkedList<Integer>::new); runBasicRemoveIfTestsUnordered(LinkedList<Integer>::new); runRemoveIfOnEmpty(LinkedList<Integer>::new); testRemoveIfNPE(LinkedList<Integer>::new); testRemoveIfCME(LinkedList<Integer>::new); } /** * java.util.LinkedList#Serialization() */ public void test_serialization() throws Exception { assertTrue(ll.add(new Integer(1))); assertTrue(ll.add(new Integer(2))); assertTrue(ll.add(new Integer(3))); assertTrue(ll.add(new Integer(4))); assertTrue(ll.add(new Integer(5))); SerializationTest.verifySelf(ll, new SerializableAssert() { public void assertDeserialized(Serializable initial, Serializable deserialized) { LinkedList<Object> formerQue = (LinkedList) initial; LinkedList<Object> deserializedQue = (LinkedList) deserialized; assertEquals(formerQue.remove(), deserializedQue.remove()); } }); } /** * Sets up the fixture, for example, open a network connection. This method * is called before a test is executed. */ protected void setUp() throws Exception { super.setUp(); objArray = new Object[100]; for (int i = 0; i < objArray.length; i++) { objArray[i] = new Integer(i); } ll = new LinkedList(); for (int i = 0; i < objArray.length; i++) { ll.add(objArray[i]); } testList = new LinkedList<Object>(); testObjOne = new Object(); testObjTwo = new Object(); testObjThree = new Object(); testObjFour = new Object(); testObjLast = new Object(); } }
googleapis/google-cloud-java
37,877
java-chat/proto-google-cloud-chat-v1/src/main/java/com/google/chat/v1/UpdateSpaceNotificationSettingRequest.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/space_notification_setting.proto // Protobuf Java Version: 3.25.8 package com.google.chat.v1; /** * * * <pre> * Request to update the space notification settings. * Only supports updating notification setting for the calling user. * </pre> * * Protobuf type {@code google.chat.v1.UpdateSpaceNotificationSettingRequest} */ public final class UpdateSpaceNotificationSettingRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.chat.v1.UpdateSpaceNotificationSettingRequest) UpdateSpaceNotificationSettingRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateSpaceNotificationSettingRequest.newBuilder() to construct. private UpdateSpaceNotificationSettingRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateSpaceNotificationSettingRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateSpaceNotificationSettingRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chat.v1.SpaceNotificationSettingProto .internal_static_google_chat_v1_UpdateSpaceNotificationSettingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chat.v1.SpaceNotificationSettingProto .internal_static_google_chat_v1_UpdateSpaceNotificationSettingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chat.v1.UpdateSpaceNotificationSettingRequest.class, com.google.chat.v1.UpdateSpaceNotificationSettingRequest.Builder.class); } private int bitField0_; public static final int SPACE_NOTIFICATION_SETTING_FIELD_NUMBER = 1; private com.google.chat.v1.SpaceNotificationSetting spaceNotificationSetting_; /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the spaceNotificationSetting field is set. */ @java.lang.Override public boolean hasSpaceNotificationSetting() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The spaceNotificationSetting. */ @java.lang.Override public com.google.chat.v1.SpaceNotificationSetting getSpaceNotificationSetting() { return spaceNotificationSetting_ == null ? com.google.chat.v1.SpaceNotificationSetting.getDefaultInstance() : spaceNotificationSetting_; } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.chat.v1.SpaceNotificationSettingOrBuilder getSpaceNotificationSettingOrBuilder() { return spaceNotificationSetting_ == null ? com.google.chat.v1.SpaceNotificationSetting.getDefaultInstance() : spaceNotificationSetting_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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, getSpaceNotificationSetting()); } 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, getSpaceNotificationSetting()); } 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.chat.v1.UpdateSpaceNotificationSettingRequest)) { return super.equals(obj); } com.google.chat.v1.UpdateSpaceNotificationSettingRequest other = (com.google.chat.v1.UpdateSpaceNotificationSettingRequest) obj; if (hasSpaceNotificationSetting() != other.hasSpaceNotificationSetting()) return false; if (hasSpaceNotificationSetting()) { if (!getSpaceNotificationSetting().equals(other.getSpaceNotificationSetting())) 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 (hasSpaceNotificationSetting()) { hash = (37 * hash) + SPACE_NOTIFICATION_SETTING_FIELD_NUMBER; hash = (53 * hash) + getSpaceNotificationSetting().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.chat.v1.UpdateSpaceNotificationSettingRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest 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.UpdateSpaceNotificationSettingRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest 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.UpdateSpaceNotificationSettingRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest 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.UpdateSpaceNotificationSettingRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest 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.UpdateSpaceNotificationSettingRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest 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.UpdateSpaceNotificationSettingRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request to update the space notification settings. * Only supports updating notification setting for the calling user. * </pre> * * Protobuf type {@code google.chat.v1.UpdateSpaceNotificationSettingRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.chat.v1.UpdateSpaceNotificationSettingRequest) com.google.chat.v1.UpdateSpaceNotificationSettingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chat.v1.SpaceNotificationSettingProto .internal_static_google_chat_v1_UpdateSpaceNotificationSettingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chat.v1.SpaceNotificationSettingProto .internal_static_google_chat_v1_UpdateSpaceNotificationSettingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chat.v1.UpdateSpaceNotificationSettingRequest.class, com.google.chat.v1.UpdateSpaceNotificationSettingRequest.Builder.class); } // Construct using com.google.chat.v1.UpdateSpaceNotificationSettingRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getSpaceNotificationSettingFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; spaceNotificationSetting_ = null; if (spaceNotificationSettingBuilder_ != null) { spaceNotificationSettingBuilder_.dispose(); spaceNotificationSettingBuilder_ = 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.chat.v1.SpaceNotificationSettingProto .internal_static_google_chat_v1_UpdateSpaceNotificationSettingRequest_descriptor; } @java.lang.Override public com.google.chat.v1.UpdateSpaceNotificationSettingRequest getDefaultInstanceForType() { return com.google.chat.v1.UpdateSpaceNotificationSettingRequest.getDefaultInstance(); } @java.lang.Override public com.google.chat.v1.UpdateSpaceNotificationSettingRequest build() { com.google.chat.v1.UpdateSpaceNotificationSettingRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.chat.v1.UpdateSpaceNotificationSettingRequest buildPartial() { com.google.chat.v1.UpdateSpaceNotificationSettingRequest result = new com.google.chat.v1.UpdateSpaceNotificationSettingRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.chat.v1.UpdateSpaceNotificationSettingRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.spaceNotificationSetting_ = spaceNotificationSettingBuilder_ == null ? spaceNotificationSetting_ : spaceNotificationSettingBuilder_.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.chat.v1.UpdateSpaceNotificationSettingRequest) { return mergeFrom((com.google.chat.v1.UpdateSpaceNotificationSettingRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.chat.v1.UpdateSpaceNotificationSettingRequest other) { if (other == com.google.chat.v1.UpdateSpaceNotificationSettingRequest.getDefaultInstance()) return this; if (other.hasSpaceNotificationSetting()) { mergeSpaceNotificationSetting(other.getSpaceNotificationSetting()); } 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( getSpaceNotificationSettingFieldBuilder().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.chat.v1.SpaceNotificationSetting spaceNotificationSetting_; private com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.SpaceNotificationSetting, com.google.chat.v1.SpaceNotificationSetting.Builder, com.google.chat.v1.SpaceNotificationSettingOrBuilder> spaceNotificationSettingBuilder_; /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the spaceNotificationSetting field is set. */ public boolean hasSpaceNotificationSetting() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The spaceNotificationSetting. */ public com.google.chat.v1.SpaceNotificationSetting getSpaceNotificationSetting() { if (spaceNotificationSettingBuilder_ == null) { return spaceNotificationSetting_ == null ? com.google.chat.v1.SpaceNotificationSetting.getDefaultInstance() : spaceNotificationSetting_; } else { return spaceNotificationSettingBuilder_.getMessage(); } } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSpaceNotificationSetting(com.google.chat.v1.SpaceNotificationSetting value) { if (spaceNotificationSettingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } spaceNotificationSetting_ = value; } else { spaceNotificationSettingBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSpaceNotificationSetting( com.google.chat.v1.SpaceNotificationSetting.Builder builderForValue) { if (spaceNotificationSettingBuilder_ == null) { spaceNotificationSetting_ = builderForValue.build(); } else { spaceNotificationSettingBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeSpaceNotificationSetting( com.google.chat.v1.SpaceNotificationSetting value) { if (spaceNotificationSettingBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && spaceNotificationSetting_ != null && spaceNotificationSetting_ != com.google.chat.v1.SpaceNotificationSetting.getDefaultInstance()) { getSpaceNotificationSettingBuilder().mergeFrom(value); } else { spaceNotificationSetting_ = value; } } else { spaceNotificationSettingBuilder_.mergeFrom(value); } if (spaceNotificationSetting_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearSpaceNotificationSetting() { bitField0_ = (bitField0_ & ~0x00000001); spaceNotificationSetting_ = null; if (spaceNotificationSettingBuilder_ != null) { spaceNotificationSettingBuilder_.dispose(); spaceNotificationSettingBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.chat.v1.SpaceNotificationSetting.Builder getSpaceNotificationSettingBuilder() { bitField0_ |= 0x00000001; onChanged(); return getSpaceNotificationSettingFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.chat.v1.SpaceNotificationSettingOrBuilder getSpaceNotificationSettingOrBuilder() { if (spaceNotificationSettingBuilder_ != null) { return spaceNotificationSettingBuilder_.getMessageOrBuilder(); } else { return spaceNotificationSetting_ == null ? com.google.chat.v1.SpaceNotificationSetting.getDefaultInstance() : spaceNotificationSetting_; } } /** * * * <pre> * Required. The resource name for the space notification settings must be * populated in the form of * `users/{user}/spaces/{space}/spaceNotificationSetting`. Only fields * specified by `update_mask` are updated. * </pre> * * <code> * .google.chat.v1.SpaceNotificationSetting space_notification_setting = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.SpaceNotificationSetting, com.google.chat.v1.SpaceNotificationSetting.Builder, com.google.chat.v1.SpaceNotificationSettingOrBuilder> getSpaceNotificationSettingFieldBuilder() { if (spaceNotificationSettingBuilder_ == null) { spaceNotificationSettingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.SpaceNotificationSetting, com.google.chat.v1.SpaceNotificationSetting.Builder, com.google.chat.v1.SpaceNotificationSettingOrBuilder>( getSpaceNotificationSetting(), getParentForChildren(), isClean()); spaceNotificationSetting_ = null; } return spaceNotificationSettingBuilder_; } 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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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. Supported field paths: * * - `notification_setting` * * - `mute_setting` * </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.chat.v1.UpdateSpaceNotificationSettingRequest) } // @@protoc_insertion_point(class_scope:google.chat.v1.UpdateSpaceNotificationSettingRequest) private static final com.google.chat.v1.UpdateSpaceNotificationSettingRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.chat.v1.UpdateSpaceNotificationSettingRequest(); } public static com.google.chat.v1.UpdateSpaceNotificationSettingRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateSpaceNotificationSettingRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateSpaceNotificationSettingRequest>() { @java.lang.Override public UpdateSpaceNotificationSettingRequest 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<UpdateSpaceNotificationSettingRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateSpaceNotificationSettingRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.chat.v1.UpdateSpaceNotificationSettingRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,810
java-scheduler/proto-google-cloud-scheduler-v1/src/main/java/com/google/cloud/scheduler/v1/PubsubTarget.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/scheduler/v1/target.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.scheduler.v1; /** * * * <pre> * Pub/Sub target. The job will be delivered by publishing a message to * the given Pub/Sub topic. * </pre> * * Protobuf type {@code google.cloud.scheduler.v1.PubsubTarget} */ public final class PubsubTarget extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.scheduler.v1.PubsubTarget) PubsubTargetOrBuilder { private static final long serialVersionUID = 0L; // Use PubsubTarget.newBuilder() to construct. private PubsubTarget(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PubsubTarget() { topicName_ = ""; data_ = com.google.protobuf.ByteString.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new PubsubTarget(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.scheduler.v1.TargetProto .internal_static_google_cloud_scheduler_v1_PubsubTarget_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 4: return internalGetAttributes(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.scheduler.v1.TargetProto .internal_static_google_cloud_scheduler_v1_PubsubTarget_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.scheduler.v1.PubsubTarget.class, com.google.cloud.scheduler.v1.PubsubTarget.Builder.class); } public static final int TOPIC_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object topicName_ = ""; /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The topicName. */ @java.lang.Override public java.lang.String getTopicName() { java.lang.Object ref = topicName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); topicName_ = s; return s; } } /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for topicName. */ @java.lang.Override public com.google.protobuf.ByteString getTopicNameBytes() { java.lang.Object ref = topicName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); topicName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_FIELD_NUMBER = 3; private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; /** * * * <pre> * The message payload for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>bytes data = 3;</code> * * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return data_; } public static final int ATTRIBUTES_FIELD_NUMBER = 4; private static final class AttributesDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance( com.google.cloud.scheduler.v1.TargetProto .internal_static_google_cloud_scheduler_v1_PubsubTarget_AttributesEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, ""); } @SuppressWarnings("serial") private com.google.protobuf.MapField<java.lang.String, java.lang.String> attributes_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetAttributes() { if (attributes_ == null) { return com.google.protobuf.MapField.emptyMapField(AttributesDefaultEntryHolder.defaultEntry); } return attributes_; } public int getAttributesCount() { return internalGetAttributes().getMap().size(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public boolean containsAttributes(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetAttributes().getMap().containsKey(key); } /** Use {@link #getAttributesMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getAttributes() { return getAttributesMap(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getAttributesMap() { return internalGetAttributes().getMap(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public /* nullable */ java.lang.String getAttributesOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetAttributes().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public java.lang.String getAttributesOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetAttributes().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(topicName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, topicName_); } if (!data_.isEmpty()) { output.writeBytes(3, data_); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetAttributes(), AttributesDefaultEntryHolder.defaultEntry, 4); 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(topicName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, topicName_); } if (!data_.isEmpty()) { size += com.google.protobuf.CodedOutputStream.computeBytesSize(3, data_); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetAttributes().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> attributes__ = AttributesDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, attributes__); } 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.scheduler.v1.PubsubTarget)) { return super.equals(obj); } com.google.cloud.scheduler.v1.PubsubTarget other = (com.google.cloud.scheduler.v1.PubsubTarget) obj; if (!getTopicName().equals(other.getTopicName())) return false; if (!getData().equals(other.getData())) return false; if (!internalGetAttributes().equals(other.internalGetAttributes())) 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) + TOPIC_NAME_FIELD_NUMBER; hash = (53 * hash) + getTopicName().hashCode(); hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData().hashCode(); if (!internalGetAttributes().getMap().isEmpty()) { hash = (37 * hash) + ATTRIBUTES_FIELD_NUMBER; hash = (53 * hash) + internalGetAttributes().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.scheduler.v1.PubsubTarget parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.scheduler.v1.PubsubTarget 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.scheduler.v1.PubsubTarget parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.scheduler.v1.PubsubTarget 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.scheduler.v1.PubsubTarget parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.scheduler.v1.PubsubTarget parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.scheduler.v1.PubsubTarget parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.scheduler.v1.PubsubTarget 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.scheduler.v1.PubsubTarget parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.scheduler.v1.PubsubTarget 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.scheduler.v1.PubsubTarget parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.scheduler.v1.PubsubTarget 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.scheduler.v1.PubsubTarget 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> * Pub/Sub target. The job will be delivered by publishing a message to * the given Pub/Sub topic. * </pre> * * Protobuf type {@code google.cloud.scheduler.v1.PubsubTarget} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.scheduler.v1.PubsubTarget) com.google.cloud.scheduler.v1.PubsubTargetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.scheduler.v1.TargetProto .internal_static_google_cloud_scheduler_v1_PubsubTarget_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 4: return internalGetAttributes(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 4: return internalGetMutableAttributes(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.scheduler.v1.TargetProto .internal_static_google_cloud_scheduler_v1_PubsubTarget_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.scheduler.v1.PubsubTarget.class, com.google.cloud.scheduler.v1.PubsubTarget.Builder.class); } // Construct using com.google.cloud.scheduler.v1.PubsubTarget.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; topicName_ = ""; data_ = com.google.protobuf.ByteString.EMPTY; internalGetMutableAttributes().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.scheduler.v1.TargetProto .internal_static_google_cloud_scheduler_v1_PubsubTarget_descriptor; } @java.lang.Override public com.google.cloud.scheduler.v1.PubsubTarget getDefaultInstanceForType() { return com.google.cloud.scheduler.v1.PubsubTarget.getDefaultInstance(); } @java.lang.Override public com.google.cloud.scheduler.v1.PubsubTarget build() { com.google.cloud.scheduler.v1.PubsubTarget result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.scheduler.v1.PubsubTarget buildPartial() { com.google.cloud.scheduler.v1.PubsubTarget result = new com.google.cloud.scheduler.v1.PubsubTarget(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.scheduler.v1.PubsubTarget result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.topicName_ = topicName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.data_ = data_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.attributes_ = internalGetAttributes(); result.attributes_.makeImmutable(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.scheduler.v1.PubsubTarget) { return mergeFrom((com.google.cloud.scheduler.v1.PubsubTarget) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.scheduler.v1.PubsubTarget other) { if (other == com.google.cloud.scheduler.v1.PubsubTarget.getDefaultInstance()) return this; if (!other.getTopicName().isEmpty()) { topicName_ = other.topicName_; bitField0_ |= 0x00000001; onChanged(); } if (other.getData() != com.google.protobuf.ByteString.EMPTY) { setData(other.getData()); } internalGetMutableAttributes().mergeFrom(other.internalGetAttributes()); bitField0_ |= 0x00000004; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { topicName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 26: { data_ = input.readBytes(); bitField0_ |= 0x00000002; break; } // case 26 case 34: { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> attributes__ = input.readMessage( AttributesDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableAttributes() .getMutableMap() .put(attributes__.getKey(), attributes__.getValue()); bitField0_ |= 0x00000004; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object topicName_ = ""; /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The topicName. */ public java.lang.String getTopicName() { java.lang.Object ref = topicName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); topicName_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for topicName. */ public com.google.protobuf.ByteString getTopicNameBytes() { java.lang.Object ref = topicName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); topicName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The topicName to set. * @return This builder for chaining. */ public Builder setTopicName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } topicName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearTopicName() { topicName_ = getDefaultInstance().getTopicName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the Cloud Pub/Sub topic to which messages will * be published when a job is delivered. The topic name must be in the * same format as required by Pub/Sub's * [PublishRequest.name](https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#publishrequest), * for example `projects/PROJECT_ID/topics/TOPIC_ID`. * * The topic must be in the same project as the Cloud Scheduler job. * </pre> * * <code>string topic_name = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for topicName to set. * @return This builder for chaining. */ public Builder setTopicNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); topicName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; /** * * * <pre> * The message payload for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>bytes data = 3;</code> * * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return data_; } /** * * * <pre> * The message payload for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>bytes data = 3;</code> * * @param value The data to set. * @return This builder for chaining. */ public Builder setData(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } data_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The message payload for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>bytes data = 3;</code> * * @return This builder for chaining. */ public Builder clearData() { bitField0_ = (bitField0_ & ~0x00000002); data_ = getDefaultInstance().getData(); onChanged(); return this; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> attributes_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetAttributes() { if (attributes_ == null) { return com.google.protobuf.MapField.emptyMapField( AttributesDefaultEntryHolder.defaultEntry); } return attributes_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableAttributes() { if (attributes_ == null) { attributes_ = com.google.protobuf.MapField.newMapField(AttributesDefaultEntryHolder.defaultEntry); } if (!attributes_.isMutable()) { attributes_ = attributes_.copy(); } bitField0_ |= 0x00000004; onChanged(); return attributes_; } public int getAttributesCount() { return internalGetAttributes().getMap().size(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public boolean containsAttributes(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetAttributes().getMap().containsKey(key); } /** Use {@link #getAttributesMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getAttributes() { return getAttributesMap(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getAttributesMap() { return internalGetAttributes().getMap(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public /* nullable */ java.lang.String getAttributesOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetAttributes().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ @java.lang.Override public java.lang.String getAttributesOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetAttributes().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearAttributes() { bitField0_ = (bitField0_ & ~0x00000004); internalGetMutableAttributes().getMutableMap().clear(); return this; } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ public Builder removeAttributes(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableAttributes().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableAttributes() { bitField0_ |= 0x00000004; return internalGetMutableAttributes().getMutableMap(); } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ public Builder putAttributes(java.lang.String key, java.lang.String value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableAttributes().getMutableMap().put(key, value); bitField0_ |= 0x00000004; return this; } /** * * * <pre> * Attributes for PubsubMessage. * * Pubsub message must contain either non-empty data, or at least one * attribute. * </pre> * * <code>map&lt;string, string&gt; attributes = 4;</code> */ public Builder putAllAttributes(java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableAttributes().getMutableMap().putAll(values); bitField0_ |= 0x00000004; return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.scheduler.v1.PubsubTarget) } // @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.PubsubTarget) private static final com.google.cloud.scheduler.v1.PubsubTarget DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.scheduler.v1.PubsubTarget(); } public static com.google.cloud.scheduler.v1.PubsubTarget getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PubsubTarget> PARSER = new com.google.protobuf.AbstractParser<PubsubTarget>() { @java.lang.Override public PubsubTarget 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<PubsubTarget> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PubsubTarget> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.scheduler.v1.PubsubTarget getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,832
java-shopping-merchant-accounts/proto-google-shopping-merchant-accounts-v1/src/main/java/com/google/shopping/merchant/accounts/v1/UpdateAccountRelationshipRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/merchant/accounts/v1/accountrelationships.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.accounts.v1; /** * * * <pre> * Request message for the `UpdateAccountRelationship` method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest} */ public final class UpdateAccountRelationshipRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) UpdateAccountRelationshipRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateAccountRelationshipRequest.newBuilder() to construct. private UpdateAccountRelationshipRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateAccountRelationshipRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateAccountRelationshipRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1.AccountRelationshipsProto .internal_static_google_shopping_merchant_accounts_v1_UpdateAccountRelationshipRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1.AccountRelationshipsProto .internal_static_google_shopping_merchant_accounts_v1_UpdateAccountRelationshipRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest.class, com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest.Builder .class); } private int bitField0_; public static final int ACCOUNT_RELATIONSHIP_FIELD_NUMBER = 1; private com.google.shopping.merchant.accounts.v1.AccountRelationship accountRelationship_; /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the accountRelationship field is set. */ @java.lang.Override public boolean hasAccountRelationship() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The accountRelationship. */ @java.lang.Override public com.google.shopping.merchant.accounts.v1.AccountRelationship getAccountRelationship() { return accountRelationship_ == null ? com.google.shopping.merchant.accounts.v1.AccountRelationship.getDefaultInstance() : accountRelationship_; } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1.AccountRelationshipOrBuilder getAccountRelationshipOrBuilder() { return accountRelationship_ == null ? com.google.shopping.merchant.accounts.v1.AccountRelationship.getDefaultInstance() : accountRelationship_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getAccountRelationship()); } 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, getAccountRelationship()); } 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.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest)) { return super.equals(obj); } com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest other = (com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) obj; if (hasAccountRelationship() != other.hasAccountRelationship()) return false; if (hasAccountRelationship()) { if (!getAccountRelationship().equals(other.getAccountRelationship())) 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 (hasAccountRelationship()) { hash = (37 * hash) + ACCOUNT_RELATIONSHIP_FIELD_NUMBER; hash = (53 * hash) + getAccountRelationship().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.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the `UpdateAccountRelationship` method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1.AccountRelationshipsProto .internal_static_google_shopping_merchant_accounts_v1_UpdateAccountRelationshipRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1.AccountRelationshipsProto .internal_static_google_shopping_merchant_accounts_v1_UpdateAccountRelationshipRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest.class, com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest.Builder .class); } // Construct using // com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getAccountRelationshipFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; accountRelationship_ = null; if (accountRelationshipBuilder_ != null) { accountRelationshipBuilder_.dispose(); accountRelationshipBuilder_ = 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.shopping.merchant.accounts.v1.AccountRelationshipsProto .internal_static_google_shopping_merchant_accounts_v1_UpdateAccountRelationshipRequest_descriptor; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest getDefaultInstanceForType() { return com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest .getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest build() { com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest buildPartial() { com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest result = new com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.accountRelationship_ = accountRelationshipBuilder_ == null ? accountRelationship_ : accountRelationshipBuilder_.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.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) { return mergeFrom( (com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest other) { if (other == com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest .getDefaultInstance()) return this; if (other.hasAccountRelationship()) { mergeAccountRelationship(other.getAccountRelationship()); } 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( getAccountRelationshipFieldBuilder().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.shopping.merchant.accounts.v1.AccountRelationship accountRelationship_; private com.google.protobuf.SingleFieldBuilderV3< com.google.shopping.merchant.accounts.v1.AccountRelationship, com.google.shopping.merchant.accounts.v1.AccountRelationship.Builder, com.google.shopping.merchant.accounts.v1.AccountRelationshipOrBuilder> accountRelationshipBuilder_; /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the accountRelationship field is set. */ public boolean hasAccountRelationship() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The accountRelationship. */ public com.google.shopping.merchant.accounts.v1.AccountRelationship getAccountRelationship() { if (accountRelationshipBuilder_ == null) { return accountRelationship_ == null ? com.google.shopping.merchant.accounts.v1.AccountRelationship.getDefaultInstance() : accountRelationship_; } else { return accountRelationshipBuilder_.getMessage(); } } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setAccountRelationship( com.google.shopping.merchant.accounts.v1.AccountRelationship value) { if (accountRelationshipBuilder_ == null) { if (value == null) { throw new NullPointerException(); } accountRelationship_ = value; } else { accountRelationshipBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setAccountRelationship( com.google.shopping.merchant.accounts.v1.AccountRelationship.Builder builderForValue) { if (accountRelationshipBuilder_ == null) { accountRelationship_ = builderForValue.build(); } else { accountRelationshipBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeAccountRelationship( com.google.shopping.merchant.accounts.v1.AccountRelationship value) { if (accountRelationshipBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && accountRelationship_ != null && accountRelationship_ != com.google.shopping.merchant.accounts.v1.AccountRelationship .getDefaultInstance()) { getAccountRelationshipBuilder().mergeFrom(value); } else { accountRelationship_ = value; } } else { accountRelationshipBuilder_.mergeFrom(value); } if (accountRelationship_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearAccountRelationship() { bitField0_ = (bitField0_ & ~0x00000001); accountRelationship_ = null; if (accountRelationshipBuilder_ != null) { accountRelationshipBuilder_.dispose(); accountRelationshipBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.shopping.merchant.accounts.v1.AccountRelationship.Builder getAccountRelationshipBuilder() { bitField0_ |= 0x00000001; onChanged(); return getAccountRelationshipFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.shopping.merchant.accounts.v1.AccountRelationshipOrBuilder getAccountRelationshipOrBuilder() { if (accountRelationshipBuilder_ != null) { return accountRelationshipBuilder_.getMessageOrBuilder(); } else { return accountRelationship_ == null ? com.google.shopping.merchant.accounts.v1.AccountRelationship.getDefaultInstance() : accountRelationship_; } } /** * * * <pre> * Required. The new version of the account relationship. * </pre> * * <code> * .google.shopping.merchant.accounts.v1.AccountRelationship account_relationship = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.shopping.merchant.accounts.v1.AccountRelationship, com.google.shopping.merchant.accounts.v1.AccountRelationship.Builder, com.google.shopping.merchant.accounts.v1.AccountRelationshipOrBuilder> getAccountRelationshipFieldBuilder() { if (accountRelationshipBuilder_ == null) { accountRelationshipBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.shopping.merchant.accounts.v1.AccountRelationship, com.google.shopping.merchant.accounts.v1.AccountRelationship.Builder, com.google.shopping.merchant.accounts.v1.AccountRelationshipOrBuilder>( getAccountRelationship(), getParentForChildren(), isClean()); accountRelationship_ = null; } return accountRelationshipBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Optional. List of fields being updated. * * The following fields are supported (in both `snake_case` and * `lowerCamelCase`): * * - `account_id_alias` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest) private static final com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest(); } public static com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateAccountRelationshipRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateAccountRelationshipRequest>() { @java.lang.Override public UpdateAccountRelationshipRequest 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<UpdateAccountRelationshipRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateAccountRelationshipRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,843
java-speech/proto-google-cloud-speech-v2/src/main/java/com/google/cloud/speech/v2/UpdatePhraseSetRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v2/cloud_speech.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.speech.v2; /** * * * <pre> * Request message for the * [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] method. * </pre> * * Protobuf type {@code google.cloud.speech.v2.UpdatePhraseSetRequest} */ public final class UpdatePhraseSetRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v2.UpdatePhraseSetRequest) UpdatePhraseSetRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdatePhraseSetRequest.newBuilder() to construct. private UpdatePhraseSetRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdatePhraseSetRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdatePhraseSetRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdatePhraseSetRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdatePhraseSetRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.UpdatePhraseSetRequest.class, com.google.cloud.speech.v2.UpdatePhraseSetRequest.Builder.class); } private int bitField0_; public static final int PHRASE_SET_FIELD_NUMBER = 1; private com.google.cloud.speech.v2.PhraseSet phraseSet_; /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the phraseSet field is set. */ @java.lang.Override public boolean hasPhraseSet() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The phraseSet. */ @java.lang.Override public com.google.cloud.speech.v2.PhraseSet getPhraseSet() { return phraseSet_ == null ? com.google.cloud.speech.v2.PhraseSet.getDefaultInstance() : phraseSet_; } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.speech.v2.PhraseSetOrBuilder getPhraseSetOrBuilder() { return phraseSet_ == null ? com.google.cloud.speech.v2.PhraseSet.getDefaultInstance() : phraseSet_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_ = false; /** * * * <pre> * If set, validate the request and preview the updated PhraseSet, but do not * actually update it. * </pre> * * <code>bool validate_only = 4;</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getPhraseSet()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getPhraseSet()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.speech.v2.UpdatePhraseSetRequest)) { return super.equals(obj); } com.google.cloud.speech.v2.UpdatePhraseSetRequest other = (com.google.cloud.speech.v2.UpdatePhraseSetRequest) obj; if (hasPhraseSet() != other.hasPhraseSet()) return false; if (hasPhraseSet()) { if (!getPhraseSet().equals(other.getPhraseSet())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasPhraseSet()) { hash = (37 * hash) + PHRASE_SET_FIELD_NUMBER; hash = (53 * hash) + getPhraseSet().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.speech.v2.UpdatePhraseSetRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for the * [UpdatePhraseSet][google.cloud.speech.v2.Speech.UpdatePhraseSet] method. * </pre> * * Protobuf type {@code google.cloud.speech.v2.UpdatePhraseSetRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v2.UpdatePhraseSetRequest) com.google.cloud.speech.v2.UpdatePhraseSetRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdatePhraseSetRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdatePhraseSetRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.UpdatePhraseSetRequest.class, com.google.cloud.speech.v2.UpdatePhraseSetRequest.Builder.class); } // Construct using com.google.cloud.speech.v2.UpdatePhraseSetRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getPhraseSetFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; phraseSet_ = null; if (phraseSetBuilder_ != null) { phraseSetBuilder_.dispose(); phraseSetBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdatePhraseSetRequest_descriptor; } @java.lang.Override public com.google.cloud.speech.v2.UpdatePhraseSetRequest getDefaultInstanceForType() { return com.google.cloud.speech.v2.UpdatePhraseSetRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v2.UpdatePhraseSetRequest build() { com.google.cloud.speech.v2.UpdatePhraseSetRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v2.UpdatePhraseSetRequest buildPartial() { com.google.cloud.speech.v2.UpdatePhraseSetRequest result = new com.google.cloud.speech.v2.UpdatePhraseSetRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.speech.v2.UpdatePhraseSetRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.phraseSet_ = phraseSetBuilder_ == null ? phraseSet_ : phraseSetBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.speech.v2.UpdatePhraseSetRequest) { return mergeFrom((com.google.cloud.speech.v2.UpdatePhraseSetRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v2.UpdatePhraseSetRequest other) { if (other == com.google.cloud.speech.v2.UpdatePhraseSetRequest.getDefaultInstance()) return this; if (other.hasPhraseSet()) { mergePhraseSet(other.getPhraseSet()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getPhraseSetFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 32: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.speech.v2.PhraseSet phraseSet_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.speech.v2.PhraseSet, com.google.cloud.speech.v2.PhraseSet.Builder, com.google.cloud.speech.v2.PhraseSetOrBuilder> phraseSetBuilder_; /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the phraseSet field is set. */ public boolean hasPhraseSet() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The phraseSet. */ public com.google.cloud.speech.v2.PhraseSet getPhraseSet() { if (phraseSetBuilder_ == null) { return phraseSet_ == null ? com.google.cloud.speech.v2.PhraseSet.getDefaultInstance() : phraseSet_; } else { return phraseSetBuilder_.getMessage(); } } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setPhraseSet(com.google.cloud.speech.v2.PhraseSet value) { if (phraseSetBuilder_ == null) { if (value == null) { throw new NullPointerException(); } phraseSet_ = value; } else { phraseSetBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setPhraseSet(com.google.cloud.speech.v2.PhraseSet.Builder builderForValue) { if (phraseSetBuilder_ == null) { phraseSet_ = builderForValue.build(); } else { phraseSetBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergePhraseSet(com.google.cloud.speech.v2.PhraseSet value) { if (phraseSetBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && phraseSet_ != null && phraseSet_ != com.google.cloud.speech.v2.PhraseSet.getDefaultInstance()) { getPhraseSetBuilder().mergeFrom(value); } else { phraseSet_ = value; } } else { phraseSetBuilder_.mergeFrom(value); } if (phraseSet_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearPhraseSet() { bitField0_ = (bitField0_ & ~0x00000001); phraseSet_ = null; if (phraseSetBuilder_ != null) { phraseSetBuilder_.dispose(); phraseSetBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.speech.v2.PhraseSet.Builder getPhraseSetBuilder() { bitField0_ |= 0x00000001; onChanged(); return getPhraseSetFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.speech.v2.PhraseSetOrBuilder getPhraseSetOrBuilder() { if (phraseSetBuilder_ != null) { return phraseSetBuilder_.getMessageOrBuilder(); } else { return phraseSet_ == null ? com.google.cloud.speech.v2.PhraseSet.getDefaultInstance() : phraseSet_; } } /** * * * <pre> * Required. The PhraseSet to update. * * The PhraseSet's `name` field is used to identify the PhraseSet to update. * Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. * </pre> * * <code> * .google.cloud.speech.v2.PhraseSet phrase_set = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.speech.v2.PhraseSet, com.google.cloud.speech.v2.PhraseSet.Builder, com.google.cloud.speech.v2.PhraseSetOrBuilder> getPhraseSetFieldBuilder() { if (phraseSetBuilder_ == null) { phraseSetBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.speech.v2.PhraseSet, com.google.cloud.speech.v2.PhraseSet.Builder, com.google.cloud.speech.v2.PhraseSetOrBuilder>( getPhraseSet(), getParentForChildren(), isClean()); phraseSet_ = null; } return phraseSetBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * The list of fields to update. If empty, all non-default valued fields are * considered for update. Use `*` to update the entire PhraseSet resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private boolean validateOnly_; /** * * * <pre> * If set, validate the request and preview the updated PhraseSet, but do not * actually update it. * </pre> * * <code>bool validate_only = 4;</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * If set, validate the request and preview the updated PhraseSet, but do not * actually update it. * </pre> * * <code>bool validate_only = 4;</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * If set, validate the request and preview the updated PhraseSet, but do not * actually update it. * </pre> * * <code>bool validate_only = 4;</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.speech.v2.UpdatePhraseSetRequest) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v2.UpdatePhraseSetRequest) private static final com.google.cloud.speech.v2.UpdatePhraseSetRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v2.UpdatePhraseSetRequest(); } public static com.google.cloud.speech.v2.UpdatePhraseSetRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdatePhraseSetRequest> PARSER = new com.google.protobuf.AbstractParser<UpdatePhraseSetRequest>() { @java.lang.Override public UpdatePhraseSetRequest 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<UpdatePhraseSetRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdatePhraseSetRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v2.UpdatePhraseSetRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,749
java-talent/proto-google-cloud-talent-v4/src/main/java/com/google/cloud/talent/v4/BatchCreateJobsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/talent/v4/job_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.talent.v4; /** * * * <pre> * Request to create a batch of jobs. * </pre> * * Protobuf type {@code google.cloud.talent.v4.BatchCreateJobsRequest} */ public final class BatchCreateJobsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.talent.v4.BatchCreateJobsRequest) BatchCreateJobsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use BatchCreateJobsRequest.newBuilder() to construct. private BatchCreateJobsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BatchCreateJobsRequest() { parent_ = ""; jobs_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BatchCreateJobsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.talent.v4.JobServiceProto .internal_static_google_cloud_talent_v4_BatchCreateJobsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.talent.v4.JobServiceProto .internal_static_google_cloud_talent_v4_BatchCreateJobsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.talent.v4.BatchCreateJobsRequest.class, com.google.cloud.talent.v4.BatchCreateJobsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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 tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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 JOBS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.cloud.talent.v4.Job> jobs_; /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code>repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.talent.v4.Job> getJobsList() { return jobs_; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code>repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.talent.v4.JobOrBuilder> getJobsOrBuilderList() { return jobs_; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code>repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public int getJobsCount() { return jobs_.size(); } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code>repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.talent.v4.Job getJobs(int index) { return jobs_.get(index); } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code>repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.talent.v4.JobOrBuilder getJobsOrBuilder(int index) { return jobs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } for (int i = 0; i < jobs_.size(); i++) { output.writeMessage(2, jobs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } for (int i = 0; i < jobs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, jobs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.talent.v4.BatchCreateJobsRequest)) { return super.equals(obj); } com.google.cloud.talent.v4.BatchCreateJobsRequest other = (com.google.cloud.talent.v4.BatchCreateJobsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getJobsList().equals(other.getJobsList())) 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 (getJobsCount() > 0) { hash = (37 * hash) + JOBS_FIELD_NUMBER; hash = (53 * hash) + getJobsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.talent.v4.BatchCreateJobsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request to create a batch of jobs. * </pre> * * Protobuf type {@code google.cloud.talent.v4.BatchCreateJobsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.talent.v4.BatchCreateJobsRequest) com.google.cloud.talent.v4.BatchCreateJobsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.talent.v4.JobServiceProto .internal_static_google_cloud_talent_v4_BatchCreateJobsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.talent.v4.JobServiceProto .internal_static_google_cloud_talent_v4_BatchCreateJobsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.talent.v4.BatchCreateJobsRequest.class, com.google.cloud.talent.v4.BatchCreateJobsRequest.Builder.class); } // Construct using com.google.cloud.talent.v4.BatchCreateJobsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; if (jobsBuilder_ == null) { jobs_ = java.util.Collections.emptyList(); } else { jobs_ = null; jobsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.talent.v4.JobServiceProto .internal_static_google_cloud_talent_v4_BatchCreateJobsRequest_descriptor; } @java.lang.Override public com.google.cloud.talent.v4.BatchCreateJobsRequest getDefaultInstanceForType() { return com.google.cloud.talent.v4.BatchCreateJobsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.talent.v4.BatchCreateJobsRequest build() { com.google.cloud.talent.v4.BatchCreateJobsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.talent.v4.BatchCreateJobsRequest buildPartial() { com.google.cloud.talent.v4.BatchCreateJobsRequest result = new com.google.cloud.talent.v4.BatchCreateJobsRequest(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.talent.v4.BatchCreateJobsRequest result) { if (jobsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { jobs_ = java.util.Collections.unmodifiableList(jobs_); bitField0_ = (bitField0_ & ~0x00000002); } result.jobs_ = jobs_; } else { result.jobs_ = jobsBuilder_.build(); } } private void buildPartial0(com.google.cloud.talent.v4.BatchCreateJobsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.talent.v4.BatchCreateJobsRequest) { return mergeFrom((com.google.cloud.talent.v4.BatchCreateJobsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.talent.v4.BatchCreateJobsRequest other) { if (other == com.google.cloud.talent.v4.BatchCreateJobsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (jobsBuilder_ == null) { if (!other.jobs_.isEmpty()) { if (jobs_.isEmpty()) { jobs_ = other.jobs_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureJobsIsMutable(); jobs_.addAll(other.jobs_); } onChanged(); } } else { if (!other.jobs_.isEmpty()) { if (jobsBuilder_.isEmpty()) { jobsBuilder_.dispose(); jobsBuilder_ = null; jobs_ = other.jobs_; bitField0_ = (bitField0_ & ~0x00000002); jobsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getJobsFieldBuilder() : null; } else { jobsBuilder_.addAllMessages(other.jobs_); } } } 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: { com.google.cloud.talent.v4.Job m = input.readMessage(com.google.cloud.talent.v4.Job.parser(), extensionRegistry); if (jobsBuilder_ == null) { ensureJobsIsMutable(); jobs_.add(m); } else { jobsBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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 tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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 tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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 tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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 tenant under which the job is created. * * The format is "projects/{project_id}/tenants/{tenant_id}". For example, * "projects/foo/tenants/bar". * </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.util.List<com.google.cloud.talent.v4.Job> jobs_ = java.util.Collections.emptyList(); private void ensureJobsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { jobs_ = new java.util.ArrayList<com.google.cloud.talent.v4.Job>(jobs_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.talent.v4.Job, com.google.cloud.talent.v4.Job.Builder, com.google.cloud.talent.v4.JobOrBuilder> jobsBuilder_; /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.talent.v4.Job> getJobsList() { if (jobsBuilder_ == null) { return java.util.Collections.unmodifiableList(jobs_); } else { return jobsBuilder_.getMessageList(); } } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public int getJobsCount() { if (jobsBuilder_ == null) { return jobs_.size(); } else { return jobsBuilder_.getCount(); } } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4.Job getJobs(int index) { if (jobsBuilder_ == null) { return jobs_.get(index); } else { return jobsBuilder_.getMessage(index); } } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setJobs(int index, com.google.cloud.talent.v4.Job value) { if (jobsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureJobsIsMutable(); jobs_.set(index, value); onChanged(); } else { jobsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setJobs(int index, com.google.cloud.talent.v4.Job.Builder builderForValue) { if (jobsBuilder_ == null) { ensureJobsIsMutable(); jobs_.set(index, builderForValue.build()); onChanged(); } else { jobsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addJobs(com.google.cloud.talent.v4.Job value) { if (jobsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureJobsIsMutable(); jobs_.add(value); onChanged(); } else { jobsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addJobs(int index, com.google.cloud.talent.v4.Job value) { if (jobsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureJobsIsMutable(); jobs_.add(index, value); onChanged(); } else { jobsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addJobs(com.google.cloud.talent.v4.Job.Builder builderForValue) { if (jobsBuilder_ == null) { ensureJobsIsMutable(); jobs_.add(builderForValue.build()); onChanged(); } else { jobsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addJobs(int index, com.google.cloud.talent.v4.Job.Builder builderForValue) { if (jobsBuilder_ == null) { ensureJobsIsMutable(); jobs_.add(index, builderForValue.build()); onChanged(); } else { jobsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addAllJobs(java.lang.Iterable<? extends com.google.cloud.talent.v4.Job> values) { if (jobsBuilder_ == null) { ensureJobsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, jobs_); onChanged(); } else { jobsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearJobs() { if (jobsBuilder_ == null) { jobs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { jobsBuilder_.clear(); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder removeJobs(int index) { if (jobsBuilder_ == null) { ensureJobsIsMutable(); jobs_.remove(index); onChanged(); } else { jobsBuilder_.remove(index); } return this; } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4.Job.Builder getJobsBuilder(int index) { return getJobsFieldBuilder().getBuilder(index); } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4.JobOrBuilder getJobsOrBuilder(int index) { if (jobsBuilder_ == null) { return jobs_.get(index); } else { return jobsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<? extends com.google.cloud.talent.v4.JobOrBuilder> getJobsOrBuilderList() { if (jobsBuilder_ != null) { return jobsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(jobs_); } } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4.Job.Builder addJobsBuilder() { return getJobsFieldBuilder().addBuilder(com.google.cloud.talent.v4.Job.getDefaultInstance()); } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4.Job.Builder addJobsBuilder(int index) { return getJobsFieldBuilder() .addBuilder(index, com.google.cloud.talent.v4.Job.getDefaultInstance()); } /** * * * <pre> * Required. The jobs to be created. * A maximum of 200 jobs can be created in a batch. * </pre> * * <code> * repeated .google.cloud.talent.v4.Job jobs = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.talent.v4.Job.Builder> getJobsBuilderList() { return getJobsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.talent.v4.Job, com.google.cloud.talent.v4.Job.Builder, com.google.cloud.talent.v4.JobOrBuilder> getJobsFieldBuilder() { if (jobsBuilder_ == null) { jobsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.talent.v4.Job, com.google.cloud.talent.v4.Job.Builder, com.google.cloud.talent.v4.JobOrBuilder>( jobs_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); jobs_ = null; } return jobsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.talent.v4.BatchCreateJobsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.talent.v4.BatchCreateJobsRequest) private static final com.google.cloud.talent.v4.BatchCreateJobsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.talent.v4.BatchCreateJobsRequest(); } public static com.google.cloud.talent.v4.BatchCreateJobsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BatchCreateJobsRequest> PARSER = new com.google.protobuf.AbstractParser<BatchCreateJobsRequest>() { @java.lang.Override public BatchCreateJobsRequest 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<BatchCreateJobsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BatchCreateJobsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.talent.v4.BatchCreateJobsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ozone
37,463
hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/api/TestOpenKeysSearchEndpoint.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.ozone.recon.api; import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_DB_DIRS; import static org.apache.hadoop.ozone.recon.OMMetadataManagerTestUtils.getTestReconOmMetadataManager; import static org.apache.hadoop.ozone.recon.OMMetadataManagerTestUtils.writeDirToOm; import static org.apache.hadoop.ozone.recon.OMMetadataManagerTestUtils.writeOpenFileToOm; import static org.apache.hadoop.ozone.recon.OMMetadataManagerTestUtils.writeOpenKeyToOm; import static org.apache.hadoop.ozone.recon.ReconServerConfigKeys.OZONE_RECON_NSSUMMARY_FLUSH_TO_DB_MAX_THRESHOLD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import javax.ws.rs.core.Response; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager; import org.apache.hadoop.ozone.om.OMMetadataManager; import org.apache.hadoop.ozone.om.OmMetadataManagerImpl; import org.apache.hadoop.ozone.om.helpers.BucketLayout; import org.apache.hadoop.ozone.om.helpers.OmBucketInfo; import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs; import org.apache.hadoop.ozone.recon.ReconTestInjector; import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse; import org.apache.hadoop.ozone.recon.persistence.AbstractReconSqlDBTest; import org.apache.hadoop.ozone.recon.persistence.ContainerHealthSchemaManager; import org.apache.hadoop.ozone.recon.recovery.ReconOMMetadataManager; import org.apache.hadoop.ozone.recon.scm.ReconStorageContainerManagerFacade; import org.apache.hadoop.ozone.recon.spi.ReconNamespaceSummaryManager; import org.apache.hadoop.ozone.recon.spi.StorageContainerServiceProvider; import org.apache.hadoop.ozone.recon.spi.impl.OzoneManagerServiceProviderImpl; import org.apache.hadoop.ozone.recon.spi.impl.StorageContainerServiceProviderImpl; import org.apache.hadoop.ozone.recon.tasks.NSSummaryTaskWithFSO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; /** * Test class for OMDBInsightSearchEndpoint. * * This class tests various scenarios for searching open keys within a * given volume, bucket, and directory structure. The tests include: * * 1. Test Root Level Search Restriction: Ensures searching at the root level returns a bad request. * 2. Test Volume Level Search Restriction: Ensures searching at the volume level returns a bad request. * 3. Test Bucket Level Search: Verifies search results within different types of buckets (FSO, OBS, Legacy). * 4. Test Directory Level Search: Validates searching inside specific directories. * 5. Test Key Level Search: Confirms search results for specific keys within buckets. * 6. Test Key Level Search Under Directory: Verifies searching for keys within nested directories. * 7. Test Search Under Nested Directory: Checks search results within nested directories under dira3. * 8. Test Limit Search: Tests the limit functionality of the search API. * 9. Test Search Open Keys with Bad Request: Ensures bad requests with invalid parameters return appropriate responses. * 10. Test Last Key in Response: Confirms the presence of the last key in paginated responses. * 11. Test Search Open Keys with Pagination: Verifies paginated search results. * 12. Test Search in Empty Bucket: Checks the response for searching within an empty bucket. */ public class TestOpenKeysSearchEndpoint extends AbstractReconSqlDBTest { @TempDir private Path temporaryFolder; private ReconOMMetadataManager reconOMMetadataManager; private OMDBInsightEndpoint omdbInsightEndpoint; private static final String ROOT_PATH = "/"; private static final String TEST_USER = "TestUser"; @BeforeEach public void setUp() throws Exception { OzoneConfiguration ozoneConfiguration = new OzoneConfiguration(); ozoneConfiguration.setLong(OZONE_RECON_NSSUMMARY_FLUSH_TO_DB_MAX_THRESHOLD, 100); OMMetadataManager omMetadataManager = initializeNewOmMetadataManager( Files.createDirectory(temporaryFolder.resolve("JunitOmDBDir")).toFile()); reconOMMetadataManager = getTestReconOmMetadataManager(omMetadataManager, Files.createDirectory(temporaryFolder.resolve("OmMetataDir")).toFile()); ReconTestInjector reconTestInjector = new ReconTestInjector.Builder(temporaryFolder.toFile()) .withReconSqlDb() .withReconOm(reconOMMetadataManager) .withOmServiceProvider(mock(OzoneManagerServiceProviderImpl.class)) .addBinding(OzoneStorageContainerManager.class, ReconStorageContainerManagerFacade.class) .withContainerDB() .addBinding(StorageContainerServiceProvider.class, mock(StorageContainerServiceProviderImpl.class)) .addBinding(OMDBInsightEndpoint.class) .addBinding(ContainerHealthSchemaManager.class) .build(); ReconNamespaceSummaryManager reconNamespaceSummaryManager = reconTestInjector.getInstance(ReconNamespaceSummaryManager.class); omdbInsightEndpoint = reconTestInjector.getInstance(OMDBInsightEndpoint.class); // populate OM DB and reprocess into Recon RocksDB populateOMDB(); NSSummaryTaskWithFSO nSSummaryTaskWithFso = new NSSummaryTaskWithFSO(reconNamespaceSummaryManager, reconOMMetadataManager, 10); nSSummaryTaskWithFso.reprocessWithFSO(reconOMMetadataManager); } /** * Create a new OM Metadata manager instance with one user, one vol, and two * buckets. * * @throws IOException ioEx */ private static OMMetadataManager initializeNewOmMetadataManager( File omDbDir) throws IOException { OzoneConfiguration omConfiguration = new OzoneConfiguration(); omConfiguration.set(OZONE_OM_DB_DIRS, omDbDir.getAbsolutePath()); OMMetadataManager omMetadataManager = new OmMetadataManagerImpl( omConfiguration, null); return omMetadataManager; } @Test public void testRootLevelSearchRestriction() throws IOException { // Test with root level path String rootPath = "/"; Response response = omdbInsightEndpoint.getOpenKeyInfo(-1, "", rootPath, true, true); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("Invalid startPrefix: Path must be at the bucket level or deeper"), "Expected a message indicating the path must be at the bucket level or deeper"); } @Test public void testVolumeLevelSearchRestriction() throws IOException { // Test with volume level path String volumePath = "/vola"; Response response = omdbInsightEndpoint.getOpenKeyInfo(20, "", volumePath, true, true); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("Invalid startPrefix: Path must be at the bucket level or deeper"), "Expected a message indicating the path must be at the bucket level or deeper"); // Test with another volume level path volumePath = "/volb"; response = omdbInsightEndpoint.getOpenKeyInfo(20, "", volumePath, true, true); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); entity = (String) response.getEntity(); assertTrue(entity.contains("Invalid startPrefix: Path must be at the bucket level or deeper"), "Expected a message indicating the path must be at the bucket level or deeper"); } @Test public void testBucketLevelSearch() throws IOException { // Search inside FSO bucket Response response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/vola/bucketa1", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(14, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(14000, result.getUnreplicatedDataSize()); assertEquals(14000 * 3, result.getReplicatedDataSize()); // Search inside OBS bucket response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/volb/bucketb1", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(5, result.getNonFSOKeyInfoList().size()); assertEquals(0, result.getFsoKeyInfoList().size()); // Assert Total Size assertEquals(5000, result.getUnreplicatedDataSize()); assertEquals(5000 * 3, result.getReplicatedDataSize()); // Search Inside LEGACY bucket response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/volc/bucketc1", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(7, result.getNonFSOKeyInfoList().size()); // Test with bucket that does not exist response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/vola/nonexistentbucket", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); } @Test public void testDirectoryLevelSearch() throws IOException { Response response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/vola/bucketa1/dira1", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(1000, result.getUnreplicatedDataSize()); assertEquals(1000 * 3, result.getReplicatedDataSize()); response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/vola/bucketa1/dira2", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(1000, result.getUnreplicatedDataSize()); assertEquals(1000 * 3, result.getReplicatedDataSize()); response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/vola/bucketa1/dira3", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(10, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(10000, result.getUnreplicatedDataSize()); assertEquals(10000 * 3, result.getReplicatedDataSize()); // Test with non-existent directory response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/vola/bucketa1/nonexistentdir", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); } @Test public void testKeyLevelSearch() throws IOException { // FSO Bucket key-level search Response response = omdbInsightEndpoint.getOpenKeyInfo(10, "", "/vola/bucketa1/filea1", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(1000, result.getUnreplicatedDataSize()); assertEquals(1000 * 3, result.getReplicatedDataSize()); response = omdbInsightEndpoint.getOpenKeyInfo(10, "", "/vola/bucketa1/filea2", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(1000, result.getUnreplicatedDataSize()); assertEquals(1000 * 3, result.getReplicatedDataSize()); // OBS Bucket key-level search response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/volb/bucketb1/fileb1", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(0, result.getFsoKeyInfoList().size()); assertEquals(1, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(1000, result.getUnreplicatedDataSize()); assertEquals(1000 * 3, result.getReplicatedDataSize()); response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/volb/bucketb1/fileb2", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(0, result.getFsoKeyInfoList().size()); assertEquals(1, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(1000, result.getUnreplicatedDataSize()); assertEquals(1000 * 3, result.getReplicatedDataSize()); // Test with non-existent key response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/volb/bucketb1/nonexistentfile", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/volb/bucketb1/nonexistentfile", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); } // Test searching for keys under a directory @Test public void testKeyLevelSearchUnderDirectory() throws IOException { // FSO Bucket key-level search Response response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/vola/bucketa1/dira1/innerfile", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/vola/bucketa1/dira2/innerfile", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Test for unknown file in fso bucket response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/vola/bucketa1/dira1/unknownfile", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); // Test for unknown file in fso bucket response = omdbInsightEndpoint .getOpenKeyInfo(10, "", "/vola/bucketa1/dira2/unknownfile", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); } @Test public void testSearchUnderNestedDirectory() throws IOException { Response response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(10, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Search under dira31 response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3/dira31", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(6, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Search under dira32 response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3/dira31/dira32", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(3, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Search under dira33 response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3/dira31/dira32/dira33", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Search for the exact file under dira33 response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3/dira31/dira32/dira33/file33_1", true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); // Search for a non existant file under each nested directory response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3/dira31/dira32/dira33/nonexistentfile", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/vola/bucketa1/dira3/dira31/dira32/nonexistentfile", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); } @Test public void testLimitSearch() throws IOException { Response response = omdbInsightEndpoint.getOpenKeyInfo(2, "", "/vola/bucketa1", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(2, result.getFsoKeyInfoList().size()); assertEquals(0, result.getNonFSOKeyInfoList().size()); } @Test public void testSearchOpenKeysWithBadRequest() throws IOException { // Give a negative limit int negativeLimit = -1; Response response = omdbInsightEndpoint .getOpenKeyInfo(negativeLimit, "", "@323232", true, true); // Then the response should indicate that the request was bad assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus(), "Expected a 400 BAD REQUEST status"); String entity = (String) response.getEntity(); assertTrue(entity.contains("Invalid startPrefix: Path must be at the bucket level or deeper"), "Expected a message indicating the path must be at the bucket level or deeper"); response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "///", true, true); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); entity = (String) response.getEntity(); assertTrue(entity.contains("Invalid startPrefix: Path must be at the bucket level or deeper"), "Expected a message indicating the path must be at the bucket level or deeper"); } @Test public void testLastKeyInResponse() throws IOException { Response response = omdbInsightEndpoint .getOpenKeyInfo(20, "", "/volb/bucketb1", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(0, result.getFsoKeyInfoList().size()); assertEquals(5, result.getNonFSOKeyInfoList().size()); // Assert Total Size assertEquals(5000, result.getUnreplicatedDataSize()); assertEquals(5000 * 3, result.getReplicatedDataSize()); // Assert Last Key assertEquals(ROOT_PATH + "volb/bucketb1/fileb5", result.getLastKey(), "Expected last key to be 'fileb5'"); } @Test public void testSearchOpenKeysWithPagination() throws IOException { // Set the initial parameters String startPrefix = "/volb/bucketb1"; int limit = 2; String prevKey = ""; // Perform the first search request Response response = omdbInsightEndpoint.getOpenKeyInfo(limit, prevKey, startPrefix, true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(2, result.getNonFSOKeyInfoList().size()); assertEquals(0, result.getFsoKeyInfoList().size()); // Extract the last key from the response prevKey = result.getLastKey(); assertNotNull(prevKey, "Last key should not be null"); // Perform the second search request using the last key response = omdbInsightEndpoint.getOpenKeyInfo(limit, prevKey, startPrefix, true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(2, result.getNonFSOKeyInfoList().size()); assertEquals(0, result.getFsoKeyInfoList().size()); // Extract the last key from the response prevKey = result.getLastKey(); assertNotNull(prevKey, "Last key should not be null"); // Perform the third search request using the last key response = omdbInsightEndpoint.getOpenKeyInfo(limit, prevKey, startPrefix, true, true); assertEquals(200, response.getStatus()); result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(1, result.getNonFSOKeyInfoList().size()); assertEquals(0, result.getFsoKeyInfoList().size()); assertEquals(result.getNonFSOKeyInfoList().get(0).getKey(), result.getLastKey(), "Expected last key to be empty"); } @Test public void testSearchInEmptyBucket() throws IOException { // Search in empty bucket bucketb2 Response response = omdbInsightEndpoint.getOpenKeyInfo(20, "", "/volb/bucketb2", true, true); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); String entity = (String) response.getEntity(); assertTrue(entity.contains("No keys matched the search prefix"), "Expected a message indicating no keys were found"); } @Test public void testSearchWithPrevKeyOnly() throws IOException { String prevKey = "/volb/bucketb1/fileb1"; // Key exists in volb/bucketb1 Response response = omdbInsightEndpoint.getOpenKeyInfo(4, prevKey, "", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(4, result.getNonFSOKeyInfoList().size(), "Expected 4 remaining keys after 'fileb1'"); assertEquals("/volb/bucketb1/fileb5", result.getLastKey(), "Expected last key to be 'fileb5'"); } @Test public void testSearchWithEmptyPrevKeyAndStartPrefix() throws IOException { Response response = omdbInsightEndpoint.getOpenKeyInfo(-1, "", "", true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); // Assert all the keys are returned assertEquals(12, result.getNonFSOKeyInfoList().size(), "Expected all keys to be returned"); } @Test public void testSearchWithStartPrefixOnly() throws IOException { String startPrefix = "/volb/bucketb1/"; Response response = omdbInsightEndpoint.getOpenKeyInfo(10, "", startPrefix, true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(5, result.getNonFSOKeyInfoList().size(), "Expected 5 keys starting with 'fileb1'"); assertEquals("/volb/bucketb1/fileb5", result.getLastKey(), "Expected last key to be 'fileb5'"); } @Test public void testSearchWithPrevKeyAndStartPrefix() throws IOException { String startPrefix = "/volb/bucketb1/"; String prevKey = "/volb/bucketb1/fileb1"; Response response = omdbInsightEndpoint.getOpenKeyInfo(10, prevKey, startPrefix, true, true); assertEquals(200, response.getStatus()); KeyInsightInfoResponse result = (KeyInsightInfoResponse) response.getEntity(); assertEquals(4, result.getNonFSOKeyInfoList().size(), "Expected 4 keys after 'fileb1'"); assertEquals("/volb/bucketb1/fileb5", result.getLastKey(), "Expected last key to be 'fileb5'"); } /** * Tests the NSSummaryEndpoint for a given volume, bucket, and directory structure. * The test setup mimics the following filesystem structure with specified sizes: * * root (Total Size: 15000KB) * ├── vola (Total Size: 10000KB) * │ ├── bucketa1 (FSO) Total Size: 5000KB * │ │ ├── filea1 (Size: 1000KB) * │ │ ├── filea2 (Size: 1000KB) * │ │ ├── dira1 (Total Size: 1000KB) * │ │ ├── dira2 (Total Size: 1000KB) * │ │ └── dira3 (Total Size: 1000KB) * │ │ ├── dira31 (Total Size: 1000KB) * │ │ ├── dira32 (Total Size: 1000KB) * │ │ └── dira33 (Total Size: 1000KB) * │ ├── bucketa2 (FSO) Total Size: 5000KB * │ │ ├── filea3 (Size: 1000KB) * │ │ ├── filea4 (Size: 1000KB) * │ │ ├── dira4 (Total Size: 1000KB) * │ │ ├── dira5 (Total Size: 1000KB) * │ │ └── dira6 (Total Size: 1000KB) * └── volb (Total Size: 5000KB) * ├── bucketb1 (OBS) Total Size: 5000KB * │ ├── fileb1 (Size: 1000KB) * │ ├── fileb2 (Size: 1000KB) * │ ├── fileb3 (Size: 1000KB) * │ ├── fileb4 (Size: 1000KB) * │ └── fileb5 (Size: 1000KB) * └── bucketb2 (OBS) Total Size: 0KB (Empty Bucket) * └── volc (Total Size: 7000KB) * └── bucketc1 (LEGACY) Total Size: 7000KB * ├── filec1 (Size: 1000KB) * ├── filec2 (Size: 1000KB) * ├── filec3 (Size: 1000KB) * ├── dirc1/ (Total Size: 2000KB) * └── dirc2/ (Total Size: 2000KB) * * @throws Exception */ private void populateOMDB() throws Exception { // Create Volumes long volaObjectId = createVolume("vola"); createVolume("volb"); createVolume("volc"); // Create Buckets in vola long bucketa1ObjectId = createBucket("vola", "bucketa1", 1000 + 1000 + 1000 + 1000 + 1000, getFSOBucketLayout()); long bucketa2ObjectId = createBucket("vola", "bucketa2", 1000 + 1000 + 1000 + 1000 + 1000, getFSOBucketLayout()); // Create Bucket in volb createBucket("volb", "bucketb1", 1000 + 1000 + 1000 + 1000 + 1000, getOBSBucketLayout()); createBucket("volb", "bucketb2", 0, getOBSBucketLayout()); // Empty Bucket // Create Bucket in volc createBucket("volc", "bucketc1", 7000, getLegacyBucketLayout()); // Create Directories and Files under bucketa1 long dira1ObjectId = createDirectory(bucketa1ObjectId, bucketa1ObjectId, volaObjectId, "dira1"); long dira2ObjectId = createDirectory(bucketa1ObjectId, bucketa1ObjectId, volaObjectId, "dira2"); long dira3ObjectId = createDirectory(bucketa1ObjectId, bucketa1ObjectId, volaObjectId, "dira3"); // Create nested directories under dira3 long dira31ObjectId = createDirectory(dira3ObjectId, bucketa1ObjectId, volaObjectId, "dira31"); long dira32ObjectId = createDirectory(dira31ObjectId, bucketa1ObjectId, volaObjectId, "dira32"); long dira33ObjectId = createDirectory(dira32ObjectId, bucketa1ObjectId, volaObjectId, "dira33"); // Files directly under bucketa1 createOpenFile("filea1", "bucketa1", "vola", "filea1", bucketa1ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("filea2", "bucketa1", "vola", "filea2", bucketa1ObjectId, bucketa1ObjectId, volaObjectId, 1000); // Files under dira3 createOpenFile("dira3/file3_1", "bucketa1", "vola", "file3_1", dira3ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira3/file3_2", "bucketa1", "vola", "file3_2", dira3ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira3/file3_3", "bucketa1", "vola", "file3_3", dira3ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira3/file3_4", "bucketa1", "vola", "file3_4", dira3ObjectId, bucketa1ObjectId, volaObjectId, 1000); // Files under dira31 createOpenFile("dira3/dira31/file31_1", "bucketa1", "vola", "file31_1", dira31ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira3/dira31/file31_2", "bucketa1", "vola", "file31_2", dira31ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira3/dira31/file31_3", "bucketa1", "vola", "file31_3", dira31ObjectId, bucketa1ObjectId, volaObjectId, 1000); // Files under dira32 createOpenFile("dira3/dira31/dira32/file32_1", "bucketa1", "vola", "file32_1", dira32ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira3/dira31/dira32/file32_2", "bucketa1", "vola", "file32_2", dira32ObjectId, bucketa1ObjectId, volaObjectId, 1000); // Files under dira33 createOpenFile("dira3/dira31/dira32/dira33/file33_1", "bucketa1", "vola", "file33_1", dira33ObjectId, bucketa1ObjectId, volaObjectId, 1000); // Create Directories and Files under bucketa2 long dira4ObjectId = createDirectory(bucketa2ObjectId, bucketa2ObjectId, volaObjectId, "dira4"); long dira5ObjectId = createDirectory(bucketa2ObjectId, bucketa2ObjectId, volaObjectId, "dira5"); long dira6ObjectId = createDirectory(bucketa2ObjectId, bucketa2ObjectId, volaObjectId, "dira6"); // Files directly under bucketa2 createOpenFile("filea3", "bucketa2", "vola", "filea3", bucketa2ObjectId, bucketa2ObjectId, volaObjectId, 1000); createOpenFile("filea4", "bucketa2", "vola", "filea4", bucketa2ObjectId, bucketa2ObjectId, volaObjectId, 1000); // Files directly under bucketb1 createOpenKey("fileb1", "bucketb1", "volb", 1000); createOpenKey("fileb2", "bucketb1", "volb", 1000); createOpenKey("fileb3", "bucketb1", "volb", 1000); createOpenKey("fileb4", "bucketb1", "volb", 1000); createOpenKey("fileb5", "bucketb1", "volb", 1000); // Create Inner files under directories createOpenFile("dira1/innerfile", "bucketa1", "vola", "innerfile", dira1ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira2/innerfile", "bucketa1", "vola", "innerfile", dira2ObjectId, bucketa1ObjectId, volaObjectId, 1000); createOpenFile("dira4/innerfile", "bucketa2", "vola", "innerfile", dira4ObjectId, bucketa2ObjectId, volaObjectId, 1000); createOpenFile("dira5/innerfile", "bucketa2", "vola", "innerfile", dira5ObjectId, bucketa2ObjectId, volaObjectId, 1000); createOpenFile("dira6/innerfile", "bucketa2", "vola", "innerfile", dira6ObjectId, bucketa2ObjectId, volaObjectId, 1000); // Create Keys and Directories in bucketc1 (LEGACY layout) createOpenKey("filec1", "bucketc1", "volc", 1000); createOpenKey("filec2", "bucketc1", "volc", 1000); createOpenKey("filec3", "bucketc1", "volc", 1000); createOpenKey("dirc1/", "bucketc1", "volc", 2000); // Directory indicated by trailing slash createOpenKey("dirc2/", "bucketc1", "volc", 2000); // Directory indicated by trailing slash createOpenKey("dirc1/innerfile", "bucketc1", "volc", 2000); // File in directory createOpenKey("dirc2/innerfile", "bucketc1", "volc", 2000); // File in directory } /** * Create a volume and add it to the Volume Table. * * @return volume Object ID * @throws IOException */ private long createVolume(String volumeName) throws Exception { String volumeKey = reconOMMetadataManager.getVolumeKey(volumeName); long volumeId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; // Generate positive ID OmVolumeArgs args = OmVolumeArgs.newBuilder() .setObjectID(volumeId) .setVolume(volumeName) .setAdminName(TEST_USER) .setOwnerName(TEST_USER) .build(); reconOMMetadataManager.getVolumeTable().put(volumeKey, args); return volumeId; } /** * Create a bucket and add it to the Bucket Table. * * @return bucket Object ID * @throws IOException */ private long createBucket(String volumeName, String bucketName, long dataSize, BucketLayout bucketLayout) throws Exception { String bucketKey = reconOMMetadataManager.getBucketKey(volumeName, bucketName); long bucketId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; // Generate positive ID OmBucketInfo bucketInfo = OmBucketInfo.newBuilder() .setVolumeName(volumeName) .setBucketName(bucketName) .setObjectID(bucketId) .setBucketLayout(bucketLayout) .setUsedBytes(dataSize) .build(); reconOMMetadataManager.getBucketTable().put(bucketKey, bucketInfo); return bucketId; } /** * Create a directory and add it to the Directory Table. * * @return directory Object ID * @throws IOException */ private long createDirectory(long parentObjectId, long bucketObjectId, long volumeObjectId, String dirName) throws IOException { long objectId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; // Ensure positive ID writeDirToOm(reconOMMetadataManager, objectId, parentObjectId, bucketObjectId, volumeObjectId, dirName); return objectId; } /** * Create a file and add it to the Open File Table. * * @return file Object ID * @throws IOException */ @SuppressWarnings("checkstyle:ParameterNumber") private long createOpenFile(String key, String bucket, String volume, String fileName, long parentObjectId, long bucketObjectId, long volumeObjectId, long dataSize) throws IOException { long objectId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; // Ensure positive ID writeOpenFileToOm(reconOMMetadataManager, key, bucket, volume, fileName, objectId, parentObjectId, bucketObjectId, volumeObjectId, null, dataSize); return objectId; } /** * Create a key and add it to the Open Key Table. * * @return key Object ID * @throws IOException */ private long createOpenKey(String key, String bucket, String volume, long dataSize) throws IOException { long objectId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; // Ensure positive ID writeOpenKeyToOm(reconOMMetadataManager, key, bucket, volume, null, dataSize); return objectId; } private static BucketLayout getFSOBucketLayout() { return BucketLayout.FILE_SYSTEM_OPTIMIZED; } private static BucketLayout getOBSBucketLayout() { return BucketLayout.OBJECT_STORE; } private static BucketLayout getLegacyBucketLayout() { return BucketLayout.LEGACY; } }
googleapis/google-cloud-java
37,774
java-oracledatabase/proto-google-cloud-oracledatabase-v1/src/main/java/com/google/cloud/oracledatabase/v1/AutonomousDbVersion.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/oracledatabase/v1/autonomous_db_version.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.oracledatabase.v1; /** * * * <pre> * Details of the Autonomous Database version. * https://docs.oracle.com/en-us/iaas/api/#/en/database/20160918/AutonomousDbVersionSummary/ * </pre> * * Protobuf type {@code google.cloud.oracledatabase.v1.AutonomousDbVersion} */ public final class AutonomousDbVersion extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.oracledatabase.v1.AutonomousDbVersion) AutonomousDbVersionOrBuilder { private static final long serialVersionUID = 0L; // Use AutonomousDbVersion.newBuilder() to construct. private AutonomousDbVersion(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AutonomousDbVersion() { name_ = ""; version_ = ""; dbWorkload_ = 0; workloadUri_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new AutonomousDbVersion(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.oracledatabase.v1.AutonomousDbVersionProto .internal_static_google_cloud_oracledatabase_v1_AutonomousDbVersion_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.oracledatabase.v1.AutonomousDbVersionProto .internal_static_google_cloud_oracledatabase_v1_AutonomousDbVersion_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.oracledatabase.v1.AutonomousDbVersion.class, com.google.cloud.oracledatabase.v1.AutonomousDbVersion.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERSION_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object version_ = ""; /** * * * <pre> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The bytes for version. */ @java.lang.Override public com.google.protobuf.ByteString getVersionBytes() { java.lang.Object ref = version_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); version_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DB_WORKLOAD_FIELD_NUMBER = 4; private int dbWorkload_ = 0; /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The enum numeric value on the wire for dbWorkload. */ @java.lang.Override public int getDbWorkloadValue() { return dbWorkload_; } /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The dbWorkload. */ @java.lang.Override public com.google.cloud.oracledatabase.v1.DBWorkload getDbWorkload() { com.google.cloud.oracledatabase.v1.DBWorkload result = com.google.cloud.oracledatabase.v1.DBWorkload.forNumber(dbWorkload_); return result == null ? com.google.cloud.oracledatabase.v1.DBWorkload.UNRECOGNIZED : result; } public static final int WORKLOAD_URI_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object workloadUri_ = ""; /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The workloadUri. */ @java.lang.Override public java.lang.String getWorkloadUri() { java.lang.Object ref = workloadUri_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workloadUri_ = s; return s; } } /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The bytes for workloadUri. */ @java.lang.Override public com.google.protobuf.ByteString getWorkloadUriBytes() { java.lang.Object ref = workloadUri_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workloadUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, version_); } if (dbWorkload_ != com.google.cloud.oracledatabase.v1.DBWorkload.DB_WORKLOAD_UNSPECIFIED.getNumber()) { output.writeEnum(4, dbWorkload_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(workloadUri_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, workloadUri_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, version_); } if (dbWorkload_ != com.google.cloud.oracledatabase.v1.DBWorkload.DB_WORKLOAD_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(4, dbWorkload_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(workloadUri_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, workloadUri_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.oracledatabase.v1.AutonomousDbVersion)) { return super.equals(obj); } com.google.cloud.oracledatabase.v1.AutonomousDbVersion other = (com.google.cloud.oracledatabase.v1.AutonomousDbVersion) obj; if (!getName().equals(other.getName())) return false; if (!getVersion().equals(other.getVersion())) return false; if (dbWorkload_ != other.dbWorkload_) return false; if (!getWorkloadUri().equals(other.getWorkloadUri())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion().hashCode(); hash = (37 * hash) + DB_WORKLOAD_FIELD_NUMBER; hash = (53 * hash) + dbWorkload_; hash = (37 * hash) + WORKLOAD_URI_FIELD_NUMBER; hash = (53 * hash) + getWorkloadUri().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.oracledatabase.v1.AutonomousDbVersion prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Details of the Autonomous Database version. * https://docs.oracle.com/en-us/iaas/api/#/en/database/20160918/AutonomousDbVersionSummary/ * </pre> * * Protobuf type {@code google.cloud.oracledatabase.v1.AutonomousDbVersion} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.oracledatabase.v1.AutonomousDbVersion) com.google.cloud.oracledatabase.v1.AutonomousDbVersionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.oracledatabase.v1.AutonomousDbVersionProto .internal_static_google_cloud_oracledatabase_v1_AutonomousDbVersion_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.oracledatabase.v1.AutonomousDbVersionProto .internal_static_google_cloud_oracledatabase_v1_AutonomousDbVersion_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.oracledatabase.v1.AutonomousDbVersion.class, com.google.cloud.oracledatabase.v1.AutonomousDbVersion.Builder.class); } // Construct using com.google.cloud.oracledatabase.v1.AutonomousDbVersion.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; version_ = ""; dbWorkload_ = 0; workloadUri_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.oracledatabase.v1.AutonomousDbVersionProto .internal_static_google_cloud_oracledatabase_v1_AutonomousDbVersion_descriptor; } @java.lang.Override public com.google.cloud.oracledatabase.v1.AutonomousDbVersion getDefaultInstanceForType() { return com.google.cloud.oracledatabase.v1.AutonomousDbVersion.getDefaultInstance(); } @java.lang.Override public com.google.cloud.oracledatabase.v1.AutonomousDbVersion build() { com.google.cloud.oracledatabase.v1.AutonomousDbVersion result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.oracledatabase.v1.AutonomousDbVersion buildPartial() { com.google.cloud.oracledatabase.v1.AutonomousDbVersion result = new com.google.cloud.oracledatabase.v1.AutonomousDbVersion(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.oracledatabase.v1.AutonomousDbVersion result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.version_ = version_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.dbWorkload_ = dbWorkload_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.workloadUri_ = workloadUri_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.oracledatabase.v1.AutonomousDbVersion) { return mergeFrom((com.google.cloud.oracledatabase.v1.AutonomousDbVersion) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.oracledatabase.v1.AutonomousDbVersion other) { if (other == com.google.cloud.oracledatabase.v1.AutonomousDbVersion.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getVersion().isEmpty()) { version_ = other.version_; bitField0_ |= 0x00000002; onChanged(); } if (other.dbWorkload_ != 0) { setDbWorkloadValue(other.getDbWorkloadValue()); } if (!other.getWorkloadUri().isEmpty()) { workloadUri_ = other.workloadUri_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { version_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 32: { dbWorkload_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 32 case 42: { workloadUri_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Identifier. The name of the Autonomous Database Version resource with the * format: * projects/{project}/locations/{region}/autonomousDbVersions/{autonomous_db_version} * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object version_ = ""; /** * * * <pre> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return This builder for chaining. */ public Builder clearVersion() { version_ = getDefaultInstance().getVersion(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Output only. An Oracle Database version for Autonomous Database. * </pre> * * <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The bytes for version to set. * @return This builder for chaining. */ public Builder setVersionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int dbWorkload_ = 0; /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The enum numeric value on the wire for dbWorkload. */ @java.lang.Override public int getDbWorkloadValue() { return dbWorkload_; } /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @param value The enum numeric value on the wire for dbWorkload to set. * @return This builder for chaining. */ public Builder setDbWorkloadValue(int value) { dbWorkload_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The dbWorkload. */ @java.lang.Override public com.google.cloud.oracledatabase.v1.DBWorkload getDbWorkload() { com.google.cloud.oracledatabase.v1.DBWorkload result = com.google.cloud.oracledatabase.v1.DBWorkload.forNumber(dbWorkload_); return result == null ? com.google.cloud.oracledatabase.v1.DBWorkload.UNRECOGNIZED : result; } /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @param value The dbWorkload to set. * @return This builder for chaining. */ public Builder setDbWorkload(com.google.cloud.oracledatabase.v1.DBWorkload value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; dbWorkload_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Output only. The Autonomous Database workload type. * </pre> * * <code> * .google.cloud.oracledatabase.v1.DBWorkload db_workload = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return This builder for chaining. */ public Builder clearDbWorkload() { bitField0_ = (bitField0_ & ~0x00000004); dbWorkload_ = 0; onChanged(); return this; } private java.lang.Object workloadUri_ = ""; /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The workloadUri. */ public java.lang.String getWorkloadUri() { java.lang.Object ref = workloadUri_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workloadUri_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The bytes for workloadUri. */ public com.google.protobuf.ByteString getWorkloadUriBytes() { java.lang.Object ref = workloadUri_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workloadUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The workloadUri to set. * @return This builder for chaining. */ public Builder setWorkloadUri(java.lang.String value) { if (value == null) { throw new NullPointerException(); } workloadUri_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return This builder for chaining. */ public Builder clearWorkloadUri() { workloadUri_ = getDefaultInstance().getWorkloadUri(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Output only. A URL that points to a detailed description of the Autonomous * Database version. * </pre> * * <code>string workload_uri = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The bytes for workloadUri to set. * @return This builder for chaining. */ public Builder setWorkloadUriBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); workloadUri_ = 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.oracledatabase.v1.AutonomousDbVersion) } // @@protoc_insertion_point(class_scope:google.cloud.oracledatabase.v1.AutonomousDbVersion) private static final com.google.cloud.oracledatabase.v1.AutonomousDbVersion DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.oracledatabase.v1.AutonomousDbVersion(); } public static com.google.cloud.oracledatabase.v1.AutonomousDbVersion getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AutonomousDbVersion> PARSER = new com.google.protobuf.AbstractParser<AutonomousDbVersion>() { @java.lang.Override public AutonomousDbVersion 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<AutonomousDbVersion> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AutonomousDbVersion> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.oracledatabase.v1.AutonomousDbVersion getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/falcon
38,049
falcon-regression/merlin-core/src/main/java/org/apache/falcon/regression/core/util/OozieUtil.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.falcon.regression.core.util; import org.apache.falcon.entity.v0.EntityType; import org.apache.falcon.regression.core.helpers.ColoHelper; import org.apache.falcon.regression.core.helpers.entity.AbstractEntityHelper; import org.apache.hadoop.conf.Configuration; import org.apache.oozie.client.AuthOozieClient; import org.apache.oozie.client.BundleJob; import org.apache.oozie.client.OozieClient; import org.apache.oozie.client.OozieClientException; import org.apache.oozie.client.Job; import org.apache.oozie.client.CoordinatorAction; import org.apache.oozie.client.CoordinatorJob; import org.apache.oozie.client.WorkflowAction; import org.apache.oozie.client.WorkflowJob; import org.joda.time.DateTime; import org.apache.log4j.Logger; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONException; import org.testng.Assert; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * helper methods for oozie . */ public final class OozieUtil { public static final String FAIL_MSG = "NO_such_workflow_exists"; private OozieUtil() { throw new AssertionError("Instantiating utility class..."); } private static final Logger LOGGER = Logger.getLogger(OozieUtil.class); public static AuthOozieClient getClient(String url) { return new AuthOozieClient(url); } public static List<BundleJob> getBundles(OozieClient client, String filter, int start, int len) throws OozieClientException { LOGGER.info("Connecting to oozie: " + client.getOozieUrl()); return client.getBundleJobsInfo(filter, start, len); } public static List<String> getBundleIds(List<BundleJob> bundles) { List<String> ids = new ArrayList<>(); for (BundleJob bundle : bundles) { LOGGER.info("Bundle Id: " + bundle.getId()); ids.add(bundle.getId()); } return ids; } public static List<Job.Status> getBundleStatuses(List<BundleJob> bundles) { List<Job.Status> statuses = new ArrayList<>(); for (BundleJob bundle : bundles) { LOGGER.info("bundle: " + bundle); statuses.add(bundle.getStatus()); } return statuses; } public static String getMaxId(List<String> ids) { String oozieId = ids.get(0); int maxInt = Integer.valueOf(oozieId.split("-")[0]); for (int i = 1; i < ids.size(); i++) { String currentId = ids.get(i); int currInt = Integer.valueOf(currentId.split("-")[0]); if (currInt > maxInt) { oozieId = currentId; } } return oozieId; } public static String getMinId(List<String> ids) { String oozieId = ids.get(0); int minInt = Integer.valueOf(oozieId.split("-")[0]); for (int i = 1; i < ids.size(); i++) { String currentId = ids.get(i); int currInt = Integer.valueOf(currentId.split("-")[0]); if (currInt < minInt) { oozieId = currentId; } } return oozieId; } /** * @param bundleID bundle number * @param oozieClient oozie client * @return list of action ids of the succeeded retention workflow * @throws OozieClientException */ public static List<String> waitForRetentionWorkflowToSucceed(String bundleID, OozieClient oozieClient) throws OozieClientException { LOGGER.info("Connecting to oozie: " + oozieClient.getOozieUrl()); List<String> jobIds = new ArrayList<>(); LOGGER.info("using bundleId:" + bundleID); waitForCoordinatorJobCreation(oozieClient, bundleID); final String coordinatorId = oozieClient.getBundleJobInfo(bundleID).getCoordinators().get(0).getId(); LOGGER.info("using coordinatorId: " + coordinatorId); for (int i = 0; i < 120 && oozieClient.getCoordJobInfo(coordinatorId).getActions().isEmpty(); ++i) { TimeUtil.sleepSeconds(4); } Assert.assertFalse(oozieClient.getCoordJobInfo(coordinatorId).getActions().isEmpty(), "Coordinator actions should have got created by now."); CoordinatorAction action = oozieClient.getCoordJobInfo(coordinatorId).getActions().get(0); for (int i = 0; i < 180; ++i) { CoordinatorAction actionInfo = oozieClient.getCoordActionInfo(action.getId()); LOGGER.info("actionInfo: " + actionInfo); if (EnumSet.of(CoordinatorAction.Status.SUCCEEDED, CoordinatorAction.Status.KILLED, CoordinatorAction.Status.FAILED).contains(actionInfo.getStatus())) { break; } TimeUtil.sleepSeconds(10); } Assert.assertEquals( oozieClient.getCoordActionInfo(action.getId()).getStatus(), CoordinatorAction.Status.SUCCEEDED, "Action did not succeed."); jobIds.add(action.getId()); return jobIds; } public static void waitForCoordinatorJobCreation(OozieClient oozieClient, String bundleID) throws OozieClientException { LOGGER.info("Connecting to oozie: " + oozieClient.getOozieUrl()); for (int i = 0; i < 60 && oozieClient.getBundleJobInfo(bundleID).getCoordinators().isEmpty(); ++i) { TimeUtil.sleepSeconds(2); } Assert.assertFalse(oozieClient.getBundleJobInfo(bundleID).getCoordinators().isEmpty(), "Coordinator job should have got created by now."); } public static Job.Status getOozieJobStatus(OozieClient client, String processName, EntityType entityType) throws OozieClientException { String filter = String.format("name=FALCON_%s_%s", entityType, processName); List<Job.Status> statuses = getBundleStatuses(getBundles(client, filter, 0, 10)); if (statuses.isEmpty()) { return null; } else { return statuses.get(0); } } public static List<String> getBundles(OozieClient client, String entityName, EntityType entityType) throws OozieClientException { String filter = "name=FALCON_" + entityType + "_" + entityName; return getBundleIds(getBundles(client, filter, 0, 10)); } public static List<DateTime> getStartTimeForRunningCoordinators(ColoHelper prismHelper, String bundleID) throws OozieClientException { List<DateTime> startTimes = new ArrayList<>(); OozieClient oozieClient = prismHelper.getClusterHelper().getOozieClient(); BundleJob bundleJob = oozieClient.getBundleJobInfo(bundleID); CoordinatorJob jobInfo; for (CoordinatorJob job : bundleJob.getCoordinators()) { if (job.getAppName().contains("DEFAULT")) { jobInfo = oozieClient.getCoordJobInfo(job.getId()); for (CoordinatorAction action : jobInfo.getActions()) { DateTime temp = new DateTime(action.getCreatedTime(), DateTimeZone.UTC); LOGGER.info(temp); startTimes.add(temp); } } Collections.sort(startTimes); if (!(startTimes.isEmpty())) { return startTimes; } } return null; } public static boolean verifyOozieJobStatus(OozieClient client, String processName, EntityType entityType, Job.Status expectedStatus) throws OozieClientException { for (int seconds = 0; seconds < 100; seconds+=5) { Job.Status status = getOozieJobStatus(client, processName, entityType); LOGGER.info("Current status: " + status); if (status == expectedStatus) { return true; } TimeUtil.sleepSeconds(5); } return false; } public static List<String> getMissingDependencies(OozieClient oozieClient, String bundleID) throws OozieClientException { CoordinatorJob jobInfo; jobInfo = null; BundleJob bundleJob = oozieClient.getBundleJobInfo(bundleID); List<CoordinatorJob> coordinatorJobList = bundleJob.getCoordinators(); if (coordinatorJobList.size() > 1) { for (CoordinatorJob coord : bundleJob.getCoordinators()) { LOGGER.info("Appname is : " + coord.getAppName()); if ((coord.getAppName().contains("DEFAULT") && coord.getAppName().contains("PROCESS")) || (coord.getAppName().contains("REPLICATION") && coord.getAppName().contains("FEED"))) { jobInfo = oozieClient.getCoordJobInfo(coord.getId()); } else { LOGGER.info("Desired coord does not exists on " + oozieClient.getOozieUrl()); } } } else { jobInfo = oozieClient.getCoordJobInfo(bundleJob.getCoordinators().get(0).getId()); } LOGGER.info("Coordinator id : " + jobInfo); List<CoordinatorAction> actions = null; if (jobInfo != null) { actions = jobInfo.getActions(); } if (actions != null) { if (actions.size() < 1) { return null; } } if (actions != null) { LOGGER.info("conf from event: " + actions.get(0).getMissingDependencies()); } String[] missingDependencies = new String[0]; if (actions != null) { missingDependencies = actions.get(0).getMissingDependencies().split("#"); } return new ArrayList<>(Arrays.asList(missingDependencies)); } public static List<String> getWorkflowJobs(OozieClient oozieClient, String bundleID) throws OozieClientException { waitForCoordinatorJobCreation(oozieClient, bundleID); List<String> workflowIds = new ArrayList<>(); List<CoordinatorJob> coordJobs = oozieClient.getBundleJobInfo(bundleID).getCoordinators(); CoordinatorJob coordJobInfo = oozieClient.getCoordJobInfo(coordJobs.get(0).getId()); for (CoordinatorAction action : coordJobInfo.getActions()) { workflowIds.add(action.getExternalId()); } return workflowIds; } public static List<String> getWorkflow(OozieClient oozieClient, String bundleID) throws OozieClientException { waitForCoordinatorJobCreation(oozieClient, bundleID); List<String> workflowIds = new ArrayList<>(); String coordId = getDefaultCoordIDFromBundle(oozieClient, bundleID); CoordinatorJob coordJobInfo = oozieClient.getCoordJobInfo(coordId); for (CoordinatorAction action : coordJobInfo.getActions()) { if (action.getStatus().name().equals("RUNNING") || action.getStatus().name().equals("SUCCEEDED")) { workflowIds.add(action.getExternalId()); } if (action.getStatus().name().equals("KILLED") || action.getStatus().name().equals("WAITING")) { Assert.assertNull(action.getExternalId()); } } return workflowIds; } public static Date getNominalTime(OozieClient oozieClient, String bundleID) throws OozieClientException { BundleJob bundleJob = oozieClient.getBundleJobInfo(bundleID); CoordinatorJob jobInfo = oozieClient.getCoordJobInfo(bundleJob.getCoordinators().get(0).getId()); List<CoordinatorAction> actions = jobInfo.getActions(); return actions.get(0).getNominalTime(); } public static CoordinatorJob getDefaultOozieCoord(OozieClient oozieClient, String bundleId, EntityType type) throws OozieClientException { BundleJob bundlejob = oozieClient.getBundleJobInfo(bundleId); for (CoordinatorJob coord : bundlejob.getCoordinators()) { if ((coord.getAppName().contains("DEFAULT") && EntityType.PROCESS == type) || (coord.getAppName().contains("REPLICATION") && EntityType.FEED == type)) { return oozieClient.getCoordJobInfo(coord.getId()); } else { LOGGER.info("Desired coord does not exists on " + oozieClient.getOozieUrl()); } } return null; } public static int getNumberOfWorkflowInstances(OozieClient oozieClient, String bundleId) throws OozieClientException { return getDefaultOozieCoord(oozieClient, bundleId, EntityType.PROCESS).getActions().size(); } public static List<String> getActionsNominalTime(OozieClient oozieClient, String bundleId, EntityType type) throws OozieClientException { Map<Date, CoordinatorAction.Status> actions = getActionsNominalTimeAndStatus(oozieClient, bundleId, type); List<String> nominalTime = new ArrayList<>(); for (Date date : actions.keySet()) { nominalTime.add(date.toString()); } return nominalTime; } public static Map<Date, CoordinatorAction.Status> getActionsNominalTimeAndStatus(OozieClient oozieClient, String bundleId, EntityType type) throws OozieClientException { Map<Date, CoordinatorAction.Status> result = new TreeMap<>(); List<CoordinatorAction> actions = getDefaultOozieCoord(oozieClient, bundleId, type).getActions(); for (CoordinatorAction action : actions) { result.put(action.getNominalTime(), action.getStatus()); } return result; } public static boolean isBundleOver(ColoHelper coloHelper, String bundleId) throws OozieClientException { OozieClient client = coloHelper.getClusterHelper().getOozieClient(); BundleJob bundleJob = client.getBundleJobInfo(bundleId); if (EnumSet.of(BundleJob.Status.DONEWITHERROR, BundleJob.Status.FAILED, BundleJob.Status.SUCCEEDED, BundleJob.Status.KILLED).contains(bundleJob.getStatus())) { return true; } TimeUtil.sleepSeconds(20); return false; } public static void verifyNewBundleCreation(OozieClient oozieClient, String originalBundleId, List<String> initialNominalTimes, String entity, boolean shouldBeCreated, boolean matchInstances) throws OozieClientException { String entityName = Util.readEntityName(entity); EntityType entityType = Util.getEntityType(entity); String newBundleId = getLatestBundleID(oozieClient, entityName, entityType); if (shouldBeCreated) { Assert.assertTrue(!newBundleId.equalsIgnoreCase(originalBundleId), "eeks! new bundle is not getting created!!!!"); LOGGER.info("old bundleId=" + originalBundleId + " on oozie: " + oozieClient); LOGGER.info("new bundleId=" + newBundleId + " on oozie: " + oozieClient); if (matchInstances) { validateNumberOfWorkflowInstances(oozieClient, initialNominalTimes, originalBundleId, newBundleId, entityType); } } else { Assert.assertEquals(newBundleId, originalBundleId, "eeks! new bundle is getting created!!!!"); } } private static void validateNumberOfWorkflowInstances(OozieClient oozieClient, List<String> initialNominalTimes, String originalBundleId, String newBundleId, EntityType type) throws OozieClientException { List<String> nominalTimesOriginalAndNew = getActionsNominalTime(oozieClient, originalBundleId, type); nominalTimesOriginalAndNew.addAll(getActionsNominalTime(oozieClient, newBundleId, type)); initialNominalTimes.removeAll(nominalTimesOriginalAndNew); if (initialNominalTimes.size() != 0) { LOGGER.info("Missing instance are : " + initialNominalTimes); LOGGER.debug("Original Bundle ID : " + originalBundleId); LOGGER.debug("New Bundle ID : " + newBundleId); Assert.fail("some instances have gone missing after update"); } } public static String getCoordStartTime(OozieClient oozieClient, String entity, int bundleNo) throws OozieClientException { String bundleID = getSequenceBundleID(oozieClient, Util.readEntityName(entity), Util.getEntityType(entity), bundleNo); CoordinatorJob coord = getDefaultOozieCoord(oozieClient, bundleID, Util.getEntityType(entity)); return TimeUtil.dateToOozieDate(coord.getStartTime()); } public static DateTimeFormatter getOozieDateTimeFormatter() { return DateTimeFormat.forPattern("yyyy'-'MM'-'dd'T'HH':'mm'Z'"); } public static int getNumberOfBundle(OozieClient oozieClient, EntityType type, String entityName) throws OozieClientException { return OozieUtil.getBundles(oozieClient, entityName, type).size(); } public static void createMissingDependencies(ColoHelper helper, EntityType type, String entityName, int bundleNumber, int instanceNumber) throws OozieClientException, IOException { final OozieClient oozieClient = helper.getClusterHelper().getOozieClient(); String bundleID = getSequenceBundleID(oozieClient, entityName, type, bundleNumber); List<CoordinatorJob> coords = oozieClient.getBundleJobInfo(bundleID).getCoordinators(); final List<String> missingDependencies = getMissingDependenciesForInstance(oozieClient, coords, instanceNumber); HadoopUtil.createFolders(helper.getClusterHelper().getHadoopFS(), helper.getPrefix(), missingDependencies); } private static List<String> getMissingDependenciesForInstance(OozieClient oozieClient, List<CoordinatorJob> coords, int instanceNumber) throws OozieClientException { ArrayList<String> missingPaths = new ArrayList<>(); for (CoordinatorJob coord : coords) { CoordinatorJob temp = oozieClient.getCoordJobInfo(coord.getId()); CoordinatorAction instance = temp.getActions().get(instanceNumber); missingPaths.addAll(Arrays.asList(instance.getMissingDependencies().split("#"))); } return missingPaths; } public static List<List<String>> createMissingDependencies(ColoHelper helper, EntityType type, String entityName, int bundleNumber) throws OozieClientException, IOException { final OozieClient oozieClient = helper.getClusterHelper().getOozieClient(); String bundleID = getSequenceBundleID(oozieClient, entityName, type, bundleNumber); return createMissingDependenciesForBundle(helper, bundleID); } public static List<List<String>> createMissingDependenciesForBundle(ColoHelper helper, String bundleId) throws OozieClientException, IOException { OozieClient oozieClient = helper.getClusterHelper().getOozieClient(); List<CoordinatorJob> coords = oozieClient.getBundleJobInfo(bundleId).getCoordinators(); List<List<String>> missingDependencies = getMissingDependenciesForBundle(oozieClient, coords); for (List<String> missingDependencyPerInstance : missingDependencies) { HadoopUtil.createFolders(helper.getClusterHelper().getHadoopFS(), helper.getPrefix(), missingDependencyPerInstance); } return missingDependencies; } private static List<List<String>> getMissingDependenciesForBundle(OozieClient oozieClient, List<CoordinatorJob> coords) throws OozieClientException, IOException { List<List<String>> missingDependencies = new ArrayList<>(); for (CoordinatorJob coord : coords) { CoordinatorJob temp = oozieClient.getCoordJobInfo(coord.getId()); for (int instanceNumber = 0; instanceNumber < temp.getActions().size(); instanceNumber++) { CoordinatorAction instance = temp.getActions().get(instanceNumber); missingDependencies.add(Arrays.asList(instance.getMissingDependencies().split("#"))); } } return missingDependencies; } public static void validateRetryAttempts(OozieClient oozieClient, String bundleId, EntityType type, int attempts) throws OozieClientException { CoordinatorJob coord = getDefaultOozieCoord(oozieClient, bundleId, type); int actualRun = oozieClient.getJobInfo(coord.getActions().get(0).getExternalId()).getRun(); LOGGER.info("Actual run count: " + actualRun); // wrt 0 Assert.assertEquals(actualRun, attempts, "Rerun attempts did not match"); } /** * Try to find feed coordinators of given type. */ public static int checkIfFeedCoordExist(OozieClient oozieClient, String feedName, String coordType) throws OozieClientException { return checkIfFeedCoordExist(oozieClient, feedName, coordType, 5); } /** * Try to find feed coordinators of given type given number of times. */ public static int checkIfFeedCoordExist(OozieClient oozieClient, String feedName, String coordType, int numberOfRetries) throws OozieClientException { LOGGER.info("feedName: " + feedName); for (int retryAttempt = 0; retryAttempt < numberOfRetries; retryAttempt++) { int numberOfCoord = 0; List<String> bundleIds = getBundles(oozieClient, feedName, EntityType.FEED); if (bundleIds.size() == 0) { TimeUtil.sleepSeconds(4); continue; } LOGGER.info("bundleIds: " + bundleIds); for (String aBundleId : bundleIds) { LOGGER.info("aBundleId: " + aBundleId); waitForCoordinatorJobCreation(oozieClient, aBundleId); List<CoordinatorJob> coords = getBundleCoordinators(oozieClient, aBundleId); LOGGER.info("coords: " + coords); for (CoordinatorJob coord : coords) { if (coord.getAppName().contains(coordType)) { numberOfCoord++; } } } if (numberOfCoord > 0) { return numberOfCoord; } TimeUtil.sleepSeconds(4); } return 0; } /** * Retrieves replication coordinatorID from bundle of coordinators. */ public static List<String> getReplicationCoordID(String bundleId, AbstractEntityHelper helper) throws OozieClientException { final OozieClient oozieClient = helper.getOozieClient(); List<CoordinatorJob> coords = getBundleCoordinators(oozieClient, bundleId); List<String> replicationCoordID = new ArrayList<>(); for (CoordinatorJob coord : coords) { if (coord.getAppName().contains("FEED_REPLICATION")) { replicationCoordID.add(coord.getId()); } } return replicationCoordID; } /** * Retrieves ID of bundle related to some process/feed using its ordinal number. * * @param entityName - name of entity bundle is related to * @param entityType - feed or process * @param bundleNumber - ordinal number of bundle * @return bundle ID * @throws org.apache.oozie.client.OozieClientException */ public static String getSequenceBundleID(OozieClient oozieClient, String entityName, EntityType entityType, int bundleNumber) throws OozieClientException { //sequence start from 0 List<String> bundleIds = getBundles(oozieClient, entityName, entityType); Collections.sort(bundleIds); if (bundleNumber < bundleIds.size()) { return bundleIds.get(bundleNumber); } return null; } /** * Retrieves the latest bundle ID. * * @param oozieClient where job is running * @param entityName name of entity job is related to * @param entityType type of entity - feed or process expected * @return latest bundle ID * @throws org.apache.oozie.client.OozieClientException */ public static String getLatestBundleID(OozieClient oozieClient, String entityName, EntityType entityType) throws OozieClientException { List<String> bundleIds = getBundles(oozieClient, entityName, entityType); String max = "0"; int maxID = -1; for (String strID : bundleIds) { if (maxID < Integer.parseInt(strID.substring(0, strID.indexOf('-')))) { maxID = Integer.parseInt(strID.substring(0, strID.indexOf('-'))); max = strID; } } return max; } /** * Retrieves all coordinators of bundle. * * @param oozieClient Oozie client to use for fetching info. * @param bundleID specific bundle ID * @return list of bundle coordinators * @throws org.apache.oozie.client.OozieClientException */ public static List<CoordinatorJob> getBundleCoordinators(OozieClient oozieClient, String bundleID) throws OozieClientException { BundleJob bundleInfo = oozieClient.getBundleJobInfo(bundleID); return bundleInfo.getCoordinators(); } public static Job.Status getDefaultCoordinatorStatus(OozieClient oozieClient, String processName, int bundleNumber) throws OozieClientException { String bundleID = getSequenceBundleID(oozieClient, processName, EntityType.PROCESS, bundleNumber); String coordId = getDefaultCoordIDFromBundle(oozieClient, bundleID); return oozieClient.getCoordJobInfo(coordId).getStatus(); } public static String getDefaultCoordIDFromBundle(OozieClient oozieClient, String bundleId) throws OozieClientException { waitForCoordinatorJobCreation(oozieClient, bundleId); BundleJob bundleInfo = oozieClient.getBundleJobInfo(bundleId); List<CoordinatorJob> coords = bundleInfo.getCoordinators(); int min = 100000; String minString = ""; for (CoordinatorJob coord : coords) { String strID = coord.getId(); if (min > Integer.parseInt(strID.substring(0, strID.indexOf('-')))) { min = Integer.parseInt(strID.substring(0, strID.indexOf('-'))); minString = coord.getId(); } } LOGGER.info("function getDefaultCoordIDFromBundle: minString: " + minString); return minString; } public static String getLatestCoordinatorID(OozieClient oozieClient, String processName, EntityType entityType) throws OozieClientException { final String latestBundleID = getLatestBundleID(oozieClient, processName, entityType); return getDefaultCoordIDFromBundle(oozieClient, latestBundleID); } /** * Waits till bundle job will reach expected status. * Generates time according to expected status. * * @param oozieClient oozieClient of cluster job is running on * @param processName name of process which job is being analyzed * @param expectedStatus job status we are waiting for * @throws org.apache.oozie.client.OozieClientException */ public static void waitForBundleToReachState(OozieClient oozieClient, String processName, Job.Status expectedStatus) throws OozieClientException { int totalMinutesToWait = getMinutesToWait(expectedStatus); waitForBundleToReachState(oozieClient, processName, expectedStatus, totalMinutesToWait); } /** * Waits till bundle job will reach expected status during specific time. * Use it directly in test cases when timeouts are different from trivial, in other cases use * waitForBundleToReachState(OozieClient, String, Status) * * @param oozieClient oozie client of cluster job is running on * @param processName name of process which job is being analyzed * @param expectedStatus job status we are waiting for * @param totalMinutesToWait specific time to wait expected state * @throws org.apache.oozie.client.OozieClientException */ public static void waitForBundleToReachState(OozieClient oozieClient, String processName, Job.Status expectedStatus, int totalMinutesToWait) throws OozieClientException { int sleep = totalMinutesToWait * 60 / 20; for (int sleepCount = 0; sleepCount < sleep; sleepCount++) { String bundleID = getLatestBundleID(oozieClient, processName, EntityType.PROCESS); BundleJob j = oozieClient.getBundleJobInfo(bundleID); LOGGER.info(sleepCount + ". Current status: " + j.getStatus() + "; expected: " + expectedStatus); if (j.getStatus() == expectedStatus) { return; } TimeUtil.sleepSeconds(20); } Assert.fail("State " + expectedStatus + " wasn't reached in " + totalMinutesToWait + " mins"); } /** * Generates time which is presumably needed for bundle job to reach particular state. * * @param expectedStatus status which we are expect to get from bundle job * @return minutes to wait for expected status */ private static int getMinutesToWait(Job.Status expectedStatus) { switch (expectedStatus) { case DONEWITHERROR: case SUCCEEDED: return OSUtil.IS_WINDOWS ? 40 : 20; case KILLED: return OSUtil.IS_WINDOWS ? 30 : 15; default: return OSUtil.IS_WINDOWS ? 60 : 30; } } public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if (wf.getName().contains(actionName)) { return wf.getExternalStatus(); } } return ""; } public static String getWorkflowActionStatus(OozieClient oozieClient, String bundleId, String actionName) throws OozieClientException { List<String> workflowIds = getWorkflowJobs(oozieClient, bundleId); if (workflowIds.get(0).isEmpty()) { return FAIL_MSG; } return getActionStatus(oozieClient, workflowIds.get(0), actionName); } public static String getSubWorkflowActionStatus(OozieClient oozieClient, String bundleId, String actionName, String subAction) throws OozieClientException { List<String> workflowIds = getWorkflowJobs(oozieClient, bundleId); if (workflowIds.get(0).isEmpty()) { return FAIL_MSG; } String wid=""; List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowIds.get(0)).getActions(); for (WorkflowAction wf : wfAction) { if (wf.getName().contains(actionName)) { wid = wf.getExternalId(); } } if (!wid.isEmpty()) { return getActionStatus(oozieClient, wid, subAction); } return FAIL_MSG; } /** * Returns configuration object of a given bundleID for a given instanceTime. * * @param oozieClient oozie client of cluster job is running on * @param bundleID bundleID of given cluster * @param time instanceTime * @throws org.apache.oozie.client.OozieClientException * @throws org.json.JSONException */ public static Configuration getProcessConf(OozieClient oozieClient, String bundleID, String time) throws OozieClientException, JSONException { waitForCoordinatorJobCreation(oozieClient, bundleID); List<CoordinatorJob> coordJobs = oozieClient.getBundleJobInfo(bundleID).getCoordinators(); CoordinatorJob coordJobInfo = oozieClient.getCoordJobInfo(coordJobs.get(0).getId()); Configuration conf = new Configuration(); for (CoordinatorAction action : coordJobInfo.getActions()) { String dateStr = (new DateTime(action.getNominalTime(), DateTimeZone.UTC)).toString(); if (!dateStr.isEmpty() && dateStr.contains(time.replace("Z", ""))) { conf.addResource(new ByteArrayInputStream(oozieClient.getJobInfo(action.getExternalId()). getConf().getBytes())); } } return conf; } /** * Method retrieves and parses replication coordinator action workflow definition and checks whether specific * properties are present in list of workflow args or not. * @param workflowDefinition workflow definition * @param actionName action within workflow, e.g pre-processing, replication etc. * @param propMap specific properties which are expected to be in arg list * @return true if all keys and values are present, false otherwise */ public static boolean propsArePresentInWorkflow(String workflowDefinition, String actionName, HashMap<String, String> propMap) { //get action definition Document definition = Util.convertStringToDocument(workflowDefinition); Assert.assertNotNull(definition, "Workflow definition shouldn't be null."); NodeList actions = definition.getElementsByTagName("action"); Element action = null; for (int i = 0; i < actions.getLength(); i++) { Node node = actions.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { action = (Element) node; if (action.getAttribute("name").equals(actionName)) { break; } action = null; } } Assert.assertNotNull(action, actionName + " action not found."); //retrieve and checks whether properties are present in workflow args Element javaElement = (Element) action.getElementsByTagName("java").item(0); NodeList args = javaElement.getElementsByTagName("arg"); int counter = 0; String key = null; for (int i = 0; i < args.getLength(); i++) { Node node = args.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { String argKey = node.getTextContent().replace("-", ""); if (key != null && propMap.get(key).equals(argKey)) { counter++; key = null; } else if (key == null && propMap.containsKey(argKey)) { key = argKey; } } } return counter == propMap.size(); } /** * Returns configuration object of a given bundleID for a given retentionFeed. * * @param oozieClient oozie client of cluster job is running on * @param bundleID bundleID of given cluster * @throws OozieClientException */ public static Configuration getRetentionConfiguration(OozieClient oozieClient, String bundleID) throws OozieClientException { waitForCoordinatorJobCreation(oozieClient, bundleID); CoordinatorJob coord = null; List<CoordinatorJob> coordJobs = oozieClient.getBundleJobInfo(bundleID).getCoordinators(); for (CoordinatorJob coordinatorJob : coordJobs) { if (coordinatorJob.getAppName().startsWith("FALCON_FEED_RETENTION")) { coord = oozieClient.getCoordJobInfo(coordinatorJob.getId()); } } Configuration configuration = new Configuration(); if (coord != null) { WorkflowJob wid = oozieClient.getJobInfo(coord.getActions().get(0).getExternalId()); configuration.addResource(new ByteArrayInputStream(wid.getConf().getBytes())); } else { configuration = null; } return configuration; } }
google/j2objc
37,901
jre_emul/android/platform/libcore/jsr166-tests/src/test/java/jsr166/ConcurrentHashMap8Test.java
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package jsr166; import static java.util.Spliterator.CONCURRENT; import static java.util.Spliterator.DISTINCT; import static java.util.Spliterator.NONNULL; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder; import java.util.function.BiFunction; import junit.framework.Test; import junit.framework.TestSuite; public class ConcurrentHashMap8Test extends JSR166TestCase { // android-note: Removed because the CTS runner does a bad job of // retrying tests that have suite() declarations. // // public static void main(String[] args) { // main(suite(), args); // } // public static Test suite() { // return new TestSuite(ConcurrentHashMap8Test.class); // } /** * Returns a new map from Integers 1-5 to Strings "A"-"E". */ private static ConcurrentHashMap map5() { ConcurrentHashMap map = new ConcurrentHashMap(5); assertTrue(map.isEmpty()); map.put(one, "A"); map.put(two, "B"); map.put(three, "C"); map.put(four, "D"); map.put(five, "E"); assertFalse(map.isEmpty()); assertEquals(5, map.size()); return map; } /** * getOrDefault returns value if present, else default */ public void testGetOrDefault() { ConcurrentHashMap map = map5(); assertEquals(map.getOrDefault(one, "Z"), "A"); assertEquals(map.getOrDefault(six, "Z"), "Z"); } /** * computeIfAbsent adds when the given key is not present */ public void testComputeIfAbsent() { ConcurrentHashMap map = map5(); map.computeIfAbsent(six, (x) -> "Z"); assertTrue(map.containsKey(six)); } /** * computeIfAbsent does not replace if the key is already present */ public void testComputeIfAbsent2() { ConcurrentHashMap map = map5(); assertEquals("A", map.computeIfAbsent(one, (x) -> "Z")); } /** * computeIfAbsent does not add if function returns null */ public void testComputeIfAbsent3() { ConcurrentHashMap map = map5(); map.computeIfAbsent(six, (x) -> null); assertFalse(map.containsKey(six)); } /** * computeIfPresent does not replace if the key is already present */ public void testComputeIfPresent() { ConcurrentHashMap map = map5(); map.computeIfPresent(six, (x, y) -> "Z"); assertFalse(map.containsKey(six)); } /** * computeIfPresent adds when the given key is not present */ public void testComputeIfPresent2() { ConcurrentHashMap map = map5(); assertEquals("Z", map.computeIfPresent(one, (x, y) -> "Z")); } /** * compute does not replace if the function returns null */ public void testCompute() { ConcurrentHashMap map = map5(); map.compute(six, (x, y) -> null); assertFalse(map.containsKey(six)); } /** * compute adds when the given key is not present */ public void testCompute2() { ConcurrentHashMap map = map5(); assertEquals("Z", map.compute(six, (x, y) -> "Z")); } /** * compute replaces when the given key is present */ public void testCompute3() { ConcurrentHashMap map = map5(); assertEquals("Z", map.compute(one, (x, y) -> "Z")); } /** * compute removes when the given key is present and function returns null */ public void testCompute4() { ConcurrentHashMap map = map5(); map.compute(one, (x, y) -> null); assertFalse(map.containsKey(one)); } /** * merge adds when the given key is not present */ public void testMerge1() { ConcurrentHashMap map = map5(); assertEquals("Y", map.merge(six, "Y", (x, y) -> "Z")); } /** * merge replaces when the given key is present */ public void testMerge2() { ConcurrentHashMap map = map5(); assertEquals("Z", map.merge(one, "Y", (x, y) -> "Z")); } /** * merge removes when the given key is present and function returns null */ public void testMerge3() { ConcurrentHashMap map = map5(); map.merge(one, "Y", (x, y) -> null); assertFalse(map.containsKey(one)); } static Set<Integer> populatedSet(int n) { Set<Integer> a = ConcurrentHashMap.<Integer>newKeySet(); assertTrue(a.isEmpty()); for (int i = 0; i < n; i++) assertTrue(a.add(i)); assertEquals(n == 0, a.isEmpty()); assertEquals(n, a.size()); return a; } static Set populatedSet(Integer[] elements) { Set<Integer> a = ConcurrentHashMap.<Integer>newKeySet(); assertTrue(a.isEmpty()); for (int i = 0; i < elements.length; i++) assertTrue(a.add(elements[i])); assertFalse(a.isEmpty()); assertEquals(elements.length, a.size()); return a; } /** * replaceAll replaces all matching values. */ public void testReplaceAll() { ConcurrentHashMap<Integer, String> map = map5(); map.replaceAll((x, y) -> { return x > 3 ? "Z" : y; }); assertEquals("A", map.get(one)); assertEquals("B", map.get(two)); assertEquals("C", map.get(three)); assertEquals("Z", map.get(four)); assertEquals("Z", map.get(five)); } /** * Default-constructed set is empty */ public void testNewKeySet() { Set a = ConcurrentHashMap.newKeySet(); assertTrue(a.isEmpty()); } /** * keySet.add adds the key with the established value to the map; * remove removes it. */ public void testKeySetAddRemove() { ConcurrentHashMap map = map5(); Set set1 = map.keySet(); Set set2 = map.keySet(true); set2.add(six); assertTrue(((ConcurrentHashMap.KeySetView)set2).getMap() == map); assertTrue(((ConcurrentHashMap.KeySetView)set1).getMap() == map); assertEquals(set2.size(), map.size()); assertEquals(set1.size(), map.size()); assertTrue((Boolean)map.get(six)); assertTrue(set1.contains(six)); assertTrue(set2.contains(six)); set2.remove(six); assertNull(map.get(six)); assertFalse(set1.contains(six)); assertFalse(set2.contains(six)); } /** * keySet.addAll adds each element from the given collection */ public void testAddAll() { Set full = populatedSet(3); assertTrue(full.addAll(Arrays.asList(three, four, five))); assertEquals(6, full.size()); assertFalse(full.addAll(Arrays.asList(three, four, five))); assertEquals(6, full.size()); } /** * keySet.addAll adds each element from the given collection that did not * already exist in the set */ public void testAddAll2() { Set full = populatedSet(3); // "one" is duplicate and will not be added assertTrue(full.addAll(Arrays.asList(three, four, one))); assertEquals(5, full.size()); assertFalse(full.addAll(Arrays.asList(three, four, one))); assertEquals(5, full.size()); } /** * keySet.add will not add the element if it already exists in the set */ public void testAdd2() { Set full = populatedSet(3); assertFalse(full.add(one)); assertEquals(3, full.size()); } /** * keySet.add adds the element when it does not exist in the set */ public void testAdd3() { Set full = populatedSet(3); assertTrue(full.add(three)); assertTrue(full.contains(three)); assertFalse(full.add(three)); assertTrue(full.contains(three)); } /** * keySet.add throws UnsupportedOperationException if no default * mapped value */ public void testAdd4() { Set full = map5().keySet(); try { full.add(three); shouldThrow(); } catch (UnsupportedOperationException success) {} } /** * keySet.add throws NullPointerException if the specified key is * null */ public void testAdd5() { Set full = populatedSet(3); try { full.add(null); shouldThrow(); } catch (NullPointerException success) {} } /** * KeySetView.getMappedValue returns the map's mapped value */ public void testGetMappedValue() { ConcurrentHashMap map = map5(); assertNull(((ConcurrentHashMap.KeySetView) map.keySet()).getMappedValue()); try { map.keySet(null); shouldThrow(); } catch (NullPointerException success) {} ConcurrentHashMap.KeySetView set = map.keySet(one); assertFalse(set.add(one)); assertTrue(set.add(six)); assertTrue(set.add(seven)); assertTrue(set.getMappedValue() == one); assertTrue(map.get(one) != one); assertTrue(map.get(six) == one); assertTrue(map.get(seven) == one); } void checkSpliteratorCharacteristics(Spliterator<?> sp, int requiredCharacteristics) { assertEquals(requiredCharacteristics, requiredCharacteristics & sp.characteristics()); } /** * KeySetView.spliterator returns spliterator over the elements in this set */ public void testKeySetSpliterator() { LongAdder adder = new LongAdder(); ConcurrentHashMap map = map5(); Set set = map.keySet(); Spliterator<Integer> sp = set.spliterator(); checkSpliteratorCharacteristics(sp, CONCURRENT | DISTINCT | NONNULL); assertEquals(sp.estimateSize(), map.size()); Spliterator<Integer> sp2 = sp.trySplit(); sp.forEachRemaining((Integer x) -> adder.add(x.longValue())); long v = adder.sumThenReset(); sp2.forEachRemaining((Integer x) -> adder.add(x.longValue())); long v2 = adder.sum(); assertEquals(v + v2, 15); } /** * keyset.clear removes all elements from the set */ public void testClear() { Set full = populatedSet(3); full.clear(); assertEquals(0, full.size()); } /** * keyset.contains returns true for added elements */ public void testContains() { Set full = populatedSet(3); assertTrue(full.contains(one)); assertFalse(full.contains(five)); } /** * KeySets with equal elements are equal */ public void testEquals() { Set a = populatedSet(3); Set b = populatedSet(3); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); a.add(m1); assertFalse(a.equals(b)); assertFalse(b.equals(a)); b.add(m1); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); } /** * KeySet.containsAll returns true for collections with subset of elements */ public void testContainsAll() { Collection full = populatedSet(3); assertTrue(full.containsAll(Arrays.asList())); assertTrue(full.containsAll(Arrays.asList(one))); assertTrue(full.containsAll(Arrays.asList(one, two))); assertFalse(full.containsAll(Arrays.asList(one, two, six))); assertFalse(full.containsAll(Arrays.asList(six))); } /** * KeySet.isEmpty is true when empty, else false */ public void testIsEmpty() { assertTrue(populatedSet(0).isEmpty()); assertFalse(populatedSet(3).isEmpty()); } /** * KeySet.iterator() returns an iterator containing the elements of the * set */ public void testIterator() { Collection empty = ConcurrentHashMap.newKeySet(); int size = 20; assertFalse(empty.iterator().hasNext()); try { empty.iterator().next(); shouldThrow(); } catch (NoSuchElementException success) {} Integer[] elements = new Integer[size]; for (int i = 0; i < size; i++) elements[i] = i; Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); Iterator it = full.iterator(); for (int j = 0; j < size; j++) { assertTrue(it.hasNext()); it.next(); } assertIteratorExhausted(it); } /** * iterator of empty collections has no elements */ public void testEmptyIterator() { assertIteratorExhausted(ConcurrentHashMap.newKeySet().iterator()); assertIteratorExhausted(new ConcurrentHashMap().entrySet().iterator()); assertIteratorExhausted(new ConcurrentHashMap().values().iterator()); assertIteratorExhausted(new ConcurrentHashMap().keySet().iterator()); } /** * KeySet.iterator.remove removes current element */ public void testIteratorRemove() { Set q = populatedSet(3); Iterator it = q.iterator(); Object removed = it.next(); it.remove(); it = q.iterator(); assertFalse(it.next().equals(removed)); assertFalse(it.next().equals(removed)); assertFalse(it.hasNext()); } /** * KeySet.toString holds toString of elements */ public void testToString() { assertEquals("[]", ConcurrentHashMap.newKeySet().toString()); Set full = populatedSet(3); String s = full.toString(); for (int i = 0; i < 3; ++i) assertTrue(s.contains(String.valueOf(i))); } /** * KeySet.removeAll removes all elements from the given collection */ public void testRemoveAll() { Set full = populatedSet(3); assertTrue(full.removeAll(Arrays.asList(one, two))); assertEquals(1, full.size()); assertFalse(full.removeAll(Arrays.asList(one, two))); assertEquals(1, full.size()); } /** * KeySet.remove removes an element */ public void testRemove() { Set full = populatedSet(3); full.remove(one); assertFalse(full.contains(one)); assertEquals(2, full.size()); } /** * keySet.size returns the number of elements */ public void testSize() { Set empty = ConcurrentHashMap.newKeySet(); Set full = populatedSet(3); assertEquals(3, full.size()); assertEquals(0, empty.size()); } /** * KeySet.toArray() returns an Object array containing all elements from * the set */ public void testToArray() { Object[] a = ConcurrentHashMap.newKeySet().toArray(); assertTrue(Arrays.equals(new Object[0], a)); assertSame(Object[].class, a.getClass()); int size = 20; Integer[] elements = new Integer[size]; for (int i = 0; i < size; i++) elements[i] = i; Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray()))); assertTrue(full.containsAll(Arrays.asList(full.toArray()))); assertSame(Object[].class, full.toArray().getClass()); } /** * toArray(Integer array) returns an Integer array containing all * elements from the set */ public void testToArray2() { Collection empty = ConcurrentHashMap.newKeySet(); Integer[] a; int size = 20; a = new Integer[0]; assertSame(a, empty.toArray(a)); a = new Integer[size / 2]; Arrays.fill(a, 42); assertSame(a, empty.toArray(a)); assertNull(a[0]); for (int i = 1; i < a.length; i++) assertEquals(42, (int) a[i]); Integer[] elements = new Integer[size]; for (int i = 0; i < size; i++) elements[i] = i; Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); Arrays.fill(a, 42); assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray(a)))); for (int i = 0; i < a.length; i++) assertEquals(42, (int) a[i]); assertSame(Integer[].class, full.toArray(a).getClass()); a = new Integer[size]; Arrays.fill(a, 42); assertSame(a, full.toArray(a)); assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray(a)))); } /** * A deserialized serialized set is equal */ public void testSerialization() throws Exception { int size = 20; Set x = populatedSet(size); Set y = serialClone(x); assertNotSame(x, y); assertEquals(x.size(), y.size()); assertEquals(x, y); assertEquals(y, x); } static final int SIZE = 10000; static ConcurrentHashMap<Long, Long> longMap; static ConcurrentHashMap<Long, Long> longMap() { if (longMap == null) { longMap = new ConcurrentHashMap<Long, Long>(SIZE); for (int i = 0; i < SIZE; ++i) longMap.put(Long.valueOf(i), Long.valueOf(2 *i)); } return longMap; } // explicit function class to avoid type inference problems static class AddKeys implements BiFunction<Map.Entry<Long,Long>, Map.Entry<Long,Long>, Map.Entry<Long,Long>> { public Map.Entry<Long,Long> apply(Map.Entry<Long,Long> x, Map.Entry<Long,Long> y) { return new AbstractMap.SimpleEntry<Long,Long> (Long.valueOf(x.getKey().longValue() + y.getKey().longValue()), Long.valueOf(1L)); } } /** * forEachKeySequentially traverses all keys */ public void testForEachKeySequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachKey(Long.MAX_VALUE, (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), SIZE * (SIZE - 1) / 2); } /** * forEachValueSequentially traverses all values */ public void testForEachValueSequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachValue(Long.MAX_VALUE, (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), SIZE * (SIZE - 1)); } /** * forEachSequentially traverses all mappings */ public void testForEachSequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(Long.MAX_VALUE, (Long x, Long y) -> adder.add(x.longValue() + y.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * forEachEntrySequentially traverses all entries */ public void testForEachEntrySequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachEntry(Long.MAX_VALUE, (Map.Entry<Long,Long> e) -> adder.add(e.getKey().longValue() + e.getValue().longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * forEachKeyInParallel traverses all keys */ public void testForEachKeyInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachKey(1L, (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), SIZE * (SIZE - 1) / 2); } /** * forEachValueInParallel traverses all values */ public void testForEachValueInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachValue(1L, (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), SIZE * (SIZE - 1)); } /** * forEachInParallel traverses all mappings */ public void testForEachInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(1L, (Long x, Long y) -> adder.add(x.longValue() + y.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * forEachEntryInParallel traverses all entries */ public void testForEachEntryInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachEntry(1L, (Map.Entry<Long,Long> e) -> adder.add(e.getKey().longValue() + e.getValue().longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * Mapped forEachKeySequentially traverses the given * transformations of all keys */ public void testMappedForEachKeySequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachKey(Long.MAX_VALUE, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 4 * SIZE * (SIZE - 1) / 2); } /** * Mapped forEachValueSequentially traverses the given * transformations of all values */ public void testMappedForEachValueSequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachValue(Long.MAX_VALUE, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 4 * SIZE * (SIZE - 1)); } /** * Mapped forEachSequentially traverses the given * transformations of all mappings */ public void testMappedForEachSequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(Long.MAX_VALUE, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * Mapped forEachEntrySequentially traverses the given * transformations of all entries */ public void testMappedForEachEntrySequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachEntry(Long.MAX_VALUE, (Map.Entry<Long,Long> e) -> Long.valueOf(e.getKey().longValue() + e.getValue().longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * Mapped forEachKeyInParallel traverses the given * transformations of all keys */ public void testMappedForEachKeyInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachKey(1L, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 4 * SIZE * (SIZE - 1) / 2); } /** * Mapped forEachValueInParallel traverses the given * transformations of all values */ public void testMappedForEachValueInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachValue(1L, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 4 * SIZE * (SIZE - 1)); } /** * Mapped forEachInParallel traverses the given * transformations of all mappings */ public void testMappedForEachInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(1L, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * Mapped forEachEntryInParallel traverses the given * transformations of all entries */ public void testMappedForEachEntryInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEachEntry(1L, (Map.Entry<Long,Long> e) -> Long.valueOf(e.getKey().longValue() + e.getValue().longValue()), (Long x) -> adder.add(x.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); } /** * reduceKeysSequentially accumulates across all keys, */ public void testReduceKeysSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.reduceKeys(Long.MAX_VALUE, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)SIZE * (SIZE - 1) / 2); } /** * reduceValuesSequentially accumulates across all values */ public void testReduceValuesSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.reduceKeys(Long.MAX_VALUE, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)SIZE * (SIZE - 1) / 2); } /** * reduceEntriesSequentially accumulates across all entries */ public void testReduceEntriesSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Map.Entry<Long,Long> r; r = m.reduceEntries(Long.MAX_VALUE, new AddKeys()); assertEquals(r.getKey().longValue(), (long)SIZE * (SIZE - 1) / 2); } /** * reduceKeysInParallel accumulates across all keys */ public void testReduceKeysInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.reduceKeys(1L, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)SIZE * (SIZE - 1) / 2); } /** * reduceValuesInParallel accumulates across all values */ public void testReduceValuesInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.reduceValues(1L, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)SIZE * (SIZE - 1)); } /** * reduceEntriesInParallel accumulate across all entries */ public void testReduceEntriesInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Map.Entry<Long,Long> r; r = m.reduceEntries(1L, new AddKeys()); assertEquals(r.getKey().longValue(), (long)SIZE * (SIZE - 1) / 2); } /** * Mapped reduceKeysSequentially accumulates mapped keys */ public void testMapReduceKeysSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r = m.reduceKeys(Long.MAX_VALUE, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)4 * SIZE * (SIZE - 1) / 2); } /** * Mapped reduceValuesSequentially accumulates mapped values */ public void testMapReduceValuesSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r = m.reduceValues(Long.MAX_VALUE, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)4 * SIZE * (SIZE - 1)); } /** * reduceSequentially accumulates across all transformed mappings */ public void testMappedReduceSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r = m.reduce(Long.MAX_VALUE, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue()), (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)3 * SIZE * (SIZE - 1) / 2); } /** * Mapped reduceKeysInParallel, accumulates mapped keys */ public void testMapReduceKeysInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r = m.reduceKeys(1L, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)4 * SIZE * (SIZE - 1) / 2); } /** * Mapped reduceValuesInParallel accumulates mapped values */ public void testMapReduceValuesInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r = m.reduceValues(1L, (Long x) -> Long.valueOf(4 * x.longValue()), (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)4 * SIZE * (SIZE - 1)); } /** * reduceInParallel accumulate across all transformed mappings */ public void testMappedReduceInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.reduce(1L, (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue()), (Long x, Long y) -> Long.valueOf(x.longValue() + y.longValue())); assertEquals((long)r, (long)3 * SIZE * (SIZE - 1) / 2); } /** * reduceKeysToLongSequentially accumulates mapped keys */ public void testReduceKeysToLongSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); long lr = m.reduceKeysToLong(Long.MAX_VALUE, (Long x) -> x.longValue(), 0L, Long::sum); assertEquals(lr, (long)SIZE * (SIZE - 1) / 2); } /** * reduceKeysToIntSequentially accumulates mapped keys */ public void testReduceKeysToIntSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); int ir = m.reduceKeysToInt(Long.MAX_VALUE, (Long x) -> x.intValue(), 0, Integer::sum); assertEquals(ir, SIZE * (SIZE - 1) / 2); } /** * reduceKeysToDoubleSequentially accumulates mapped keys */ public void testReduceKeysToDoubleSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); double dr = m.reduceKeysToDouble(Long.MAX_VALUE, (Long x) -> x.doubleValue(), 0.0, Double::sum); assertEquals(dr, (double)SIZE * (SIZE - 1) / 2); } /** * reduceValuesToLongSequentially accumulates mapped values */ public void testReduceValuesToLongSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); long lr = m.reduceValuesToLong(Long.MAX_VALUE, (Long x) -> x.longValue(), 0L, Long::sum); assertEquals(lr, (long)SIZE * (SIZE - 1)); } /** * reduceValuesToIntSequentially accumulates mapped values */ public void testReduceValuesToIntSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); int ir = m.reduceValuesToInt(Long.MAX_VALUE, (Long x) -> x.intValue(), 0, Integer::sum); assertEquals(ir, SIZE * (SIZE - 1)); } /** * reduceValuesToDoubleSequentially accumulates mapped values */ public void testReduceValuesToDoubleSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); double dr = m.reduceValuesToDouble(Long.MAX_VALUE, (Long x) -> x.doubleValue(), 0.0, Double::sum); assertEquals(dr, (double)SIZE * (SIZE - 1)); } /** * reduceKeysToLongInParallel accumulates mapped keys */ public void testReduceKeysToLongInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); long lr = m.reduceKeysToLong(1L, (Long x) -> x.longValue(), 0L, Long::sum); assertEquals(lr, (long)SIZE * (SIZE - 1) / 2); } /** * reduceKeysToIntInParallel accumulates mapped keys */ public void testReduceKeysToIntInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); int ir = m.reduceKeysToInt(1L, (Long x) -> x.intValue(), 0, Integer::sum); assertEquals(ir, SIZE * (SIZE - 1) / 2); } /** * reduceKeysToDoubleInParallel accumulates mapped values */ public void testReduceKeysToDoubleInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); double dr = m.reduceKeysToDouble(1L, (Long x) -> x.doubleValue(), 0.0, Double::sum); assertEquals(dr, (double)SIZE * (SIZE - 1) / 2); } /** * reduceValuesToLongInParallel accumulates mapped values */ public void testReduceValuesToLongInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); long lr = m.reduceValuesToLong(1L, (Long x) -> x.longValue(), 0L, Long::sum); assertEquals(lr, (long)SIZE * (SIZE - 1)); } /** * reduceValuesToIntInParallel accumulates mapped values */ public void testReduceValuesToIntInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); int ir = m.reduceValuesToInt(1L, (Long x) -> x.intValue(), 0, Integer::sum); assertEquals(ir, SIZE * (SIZE - 1)); } /** * reduceValuesToDoubleInParallel accumulates mapped values */ public void testReduceValuesToDoubleInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); double dr = m.reduceValuesToDouble(1L, (Long x) -> x.doubleValue(), 0.0, Double::sum); assertEquals(dr, (double)SIZE * (SIZE - 1)); } /** * searchKeysSequentially returns a non-null result of search * function, or null if none */ public void testSearchKeysSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.searchKeys(Long.MAX_VALUE, (Long x) -> x.longValue() == (long)(SIZE/2) ? x : null); assertEquals((long)r, (long)(SIZE/2)); r = m.searchKeys(Long.MAX_VALUE, (Long x) -> x.longValue() < 0L ? x : null); assertNull(r); } /** * searchValuesSequentially returns a non-null result of search * function, or null if none */ public void testSearchValuesSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.searchValues(Long.MAX_VALUE, (Long x) -> (x.longValue() == (long)(SIZE/2)) ? x : null); assertEquals((long)r, (long)(SIZE/2)); r = m.searchValues(Long.MAX_VALUE, (Long x) -> (x.longValue() < 0L) ? x : null); assertNull(r); } /** * searchSequentially returns a non-null result of search * function, or null if none */ public void testSearchSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.search(Long.MAX_VALUE, (Long x, Long y) -> x.longValue() == (long)(SIZE/2) ? x : null); assertEquals((long)r, (long)(SIZE/2)); r = m.search(Long.MAX_VALUE, (Long x, Long y) -> x.longValue() < 0L ? x : null); assertNull(r); } /** * searchEntriesSequentially returns a non-null result of search * function, or null if none */ public void testSearchEntriesSequentially() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.searchEntries(Long.MAX_VALUE, (Map.Entry<Long,Long> e) -> e.getKey().longValue() == (long)(SIZE/2) ? e.getKey() : null); assertEquals((long)r, (long)(SIZE/2)); r = m.searchEntries(Long.MAX_VALUE, (Map.Entry<Long,Long> e) -> e.getKey().longValue() < 0L ? e.getKey() : null); assertNull(r); } /** * searchKeysInParallel returns a non-null result of search * function, or null if none */ public void testSearchKeysInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.searchKeys(1L, (Long x) -> x.longValue() == (long)(SIZE/2) ? x : null); assertEquals((long)r, (long)(SIZE/2)); r = m.searchKeys(1L, (Long x) -> x.longValue() < 0L ? x : null); assertNull(r); } /** * searchValuesInParallel returns a non-null result of search * function, or null if none */ public void testSearchValuesInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.searchValues(1L, (Long x) -> x.longValue() == (long)(SIZE/2) ? x : null); assertEquals((long)r, (long)(SIZE/2)); r = m.searchValues(1L, (Long x) -> x.longValue() < 0L ? x : null); assertNull(r); } /** * searchInParallel returns a non-null result of search function, * or null if none */ public void testSearchInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.search(1L, (Long x, Long y) -> x.longValue() == (long)(SIZE/2) ? x : null); assertEquals((long)r, (long)(SIZE/2)); r = m.search(1L, (Long x, Long y) -> x.longValue() < 0L ? x : null); assertNull(r); } /** * searchEntriesInParallel returns a non-null result of search * function, or null if none */ public void testSearchEntriesInParallel() { ConcurrentHashMap<Long, Long> m = longMap(); Long r; r = m.searchEntries(1L, (Map.Entry<Long,Long> e) -> e.getKey().longValue() == (long)(SIZE/2) ? e.getKey() : null); assertEquals((long)r, (long)(SIZE/2)); r = m.searchEntries(1L, (Map.Entry<Long,Long> e) -> e.getKey().longValue() < 0L ? e.getKey() : null); assertNull(r); } }
oracle/graal
37,888
truffle/src/com.oracle.truffle.api.test/src/com/oracle/truffle/api/test/IteratorTest.java
/* * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.api.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.function.Function; import java.util.logging.Handler; import java.util.logging.LogRecord; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.PolyglotException; import org.graalvm.polyglot.TypeLiteral; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyArray; import org.graalvm.polyglot.proxy.ProxyExecutable; import org.graalvm.polyglot.proxy.ProxyIterable; import org.graalvm.polyglot.proxy.ProxyIterator; import org.graalvm.polyglot.proxy.ProxyObject; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.oracle.truffle.api.Assumption; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.TruffleLanguage; import com.oracle.truffle.api.TruffleLogger; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeField; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.exception.AbstractTruffleException; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlotKind; import com.oracle.truffle.api.frame.FrameSlotTypeException; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.InvalidArrayIndexException; import com.oracle.truffle.api.interop.StopIterationException; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.interop.UnsupportedMessageException; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest; import com.oracle.truffle.api.test.polyglot.ProxyLanguage; import com.oracle.truffle.tck.tests.TruffleTestAssumptions; public class IteratorTest extends AbstractPolyglotTest { private static final TypeLiteral<Function<Object, Object>> FUNCTION_OBJECT_OBJECT = new TypeLiteral<>() { }; private static final TypeLiteral<Iterable<Value>> ITERABLE_VALUE = new TypeLiteral<>() { }; @BeforeClass public static void runWithWeakEncapsulationOnly() { TruffleTestAssumptions.assumeWeakEncapsulation(); } private VerifyingHandler verifyingHandler; @Before public void setUp() { verifyingHandler = new VerifyingHandler(); } @Test public void testIterable() { testImpl((items) -> new SimpleIterable(items)); } @Test public void testArray() { testImpl((items) -> new Array(items)); } private void testImpl(Function<Object[], Object> factory) { String[] items = {"one", "two", "three", "four"}; setupEnv(createContext(verifyingHandler), new ProxyLanguage() { @Override protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception { return createAST(languageInstance, factory.apply(items)); } }); verifyingHandler.expect(items); context.eval(ProxyLanguage.ID, "Test"); } @Test public void testArrayWithUnreadableElements() { String[] items = new String[10]; String[] expected = new String[items.length / 2]; for (int i = 0; i < items.length; i++) { items[i] = Integer.toString(i); if (i < expected.length) { expected[i] = items[i]; } } setupEnv(createContext(verifyingHandler), new ProxyLanguage() { @Override protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception { return createAST(languageInstance, new Array(items, expected.length, Array.UNLIMITED)); } }); verifyingHandler.expect(expected); assertFails(() -> context.eval(ProxyLanguage.ID, "Test"), PolyglotException.class, (pe) -> { assertEquals(NonReadableElementError.MESSAGE, pe.getMessage()); assertTrue(pe.isGuestException()); assertFalse(pe.isInternalError()); }); } @Test public void testValues() { String[] values = {"a", "b"}; setupEnv(Context.create()); Value iterable = context.asValue(new SimpleIterable((Object[]) values)); verifyIterable(iterable, values, false); } @Test public void testValuesWithUnreadableElements() { Object[] items = new String[10]; Object[] expected = new String[items.length / 2]; for (int i = 0; i < items.length; i++) { items[i] = Integer.toString(i); if (i < expected.length) { expected[i] = items[i]; } } setupEnv(Context.create()); Value iterable = context.asValue(new Array(items, expected.length, Array.UNLIMITED)); verifyIterable(iterable, expected, true); iterable = context.asValue(new ExecutableProxyIterableImpl(items, expected.length)); verifyIterable(iterable, expected, true); } @Test public void testHostObjectArray() { Object[] values = {"a", "b"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value array = context.asValue(values); verifyIterable(array, values, false); } @Test public void testHostObjectList() { Object[] values = {"a", "b"}; List<Object> valuesList = Arrays.asList(values); setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value list = context.asValue(new ArrayList<>(valuesList)); verifyIterable(list, values, false); } @Test public void testHostObjectIterable() { Object[] values = {"a", "b"}; List<Object> valuesList = Arrays.asList(values); setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterable = context.asValue(new Iterable<>() { private final List<Object> elements = new ArrayList<>(valuesList); @Override public Iterator<Object> iterator() { return elements.iterator(); } }); verifyIterable(iterable, values, false); } @Test public void testHostObjectIterator() { Object[] values = {"a", "b"}; List<Object> valuesList = Arrays.asList(values); setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterator = context.asValue(valuesList.iterator()); verifyIterator(iterator, values, false); iterator = context.asValue(valuesList.iterator()); verifyIterator(iterator.as(Iterator.class), values, false); } @Test public void testProxyArray() { Object[] values = {"a", "b"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value array = context.asValue(ProxyArray.fromArray(values)); verifyIterable(array, values, false); } @Test public void testProxyList() { Object[] values = {"a", "b"}; List<Object> valuesList = new ArrayList<>(); Collections.addAll(valuesList, values); setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value array = context.asValue(ProxyArray.fromList(valuesList)); verifyIterable(array, values, false); } @Test public void testProxyIterable() { Object[] values = {"a", "b"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterable = context.asValue(ProxyIterable.from(Arrays.asList(values))); verifyIterable(iterable, values, false); iterable = context.asValue(new ProxyIterable() { @Override public Object getIterator() { return Arrays.asList(values).iterator(); } }); verifyIterable(iterable, values, false); iterable = context.asValue(new ProxyIterable() { @Override public Object getIterator() { return ProxyIterator.from(Arrays.asList(values).iterator()); } }); verifyIterable(iterable, values, false); iterable = context.asValue(new ProxyIterable() { @Override public Object getIterator() { return new SimpleIterator(values); } }); verifyIterable(iterable, values, false); Value invalidIterable = context.asValue(new ProxyIterable() { @Override public Object getIterator() { return ProxyObject.fromMap(Collections.emptyMap()); } }); assertFails(() -> invalidIterable.getIterator(), PolyglotException.class, (pe) -> assertTrue(pe.asHostException() instanceof IllegalStateException)); } @Test public void testProxyIterableList() { String[] values = {"a", "b"}; List<Object> valuesList = new ArrayList<>(); Collections.addAll(valuesList, values); setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterable = context.asValue(ProxyIterable.from(valuesList)); verifyIterable(iterable, values, false); } @Test public void testExecutableProxyIterable() { String[] values = {"a", "b"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterable = context.asValue(new ExecutableProxyIterableImpl(values)); verifyIterable(iterable, values, false); assertTrue(iterable.canExecute()); assertEquals(42, iterable.execute(42).asInt()); assertEquals(42, iterable.as(FUNCTION_OBJECT_OBJECT).apply(42)); verifyIterator(iterable.as(ITERABLE_VALUE).iterator(), Arrays.stream(values).map(context::asValue).toArray(), false); } @Test public void testProxyIterableIteratorHasMembers() { String[] values = {"a", "b"}; List<Object> valuesList = new ArrayList<>(); Collections.addAll(valuesList, values); setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterable = context.asValue((ProxyIterable) () -> new ProxyIteratorWithMembersImpl(valuesList.iterator())); verifyIterable(iterable, values, false); verifyIterator(iterable.as(ITERABLE_VALUE).iterator(), Arrays.stream(values).map(context::asValue).toArray(), false); } @Test public void testIterator() { String[] values = {"a", "b", "c", "d"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterator = context.asValue(new GuestLanguageIteratorImpl(values)); verifyIterator(iterator, values, false); values = new String[0]; iterator = context.asValue(new GuestLanguageIteratorImpl(values)); verifyIterator(iterator, values, false); } @Test public void testProxyIterator() { Object[] values = {"a", "b"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterator = context.asValue(ProxyIterator.from(Arrays.asList(values).iterator())); verifyIterator(iterator, values, false); iterator = context.asValue(ProxyIterator.from(Arrays.asList(values).iterator())); verifyIterator(iterator.as(Iterator.class), values, false); } @Test public void testExecutableProxyIterator() { Object[] values = {"a", "b"}; setupEnv(Context.newBuilder().allowAllAccess(true).build()); Value iterator = context.asValue(new ExecutableProxyIteratorImpl(values)); verifyIterator(iterator, values, false); assertTrue(iterator.canExecute()); assertEquals(42, iterator.execute(42).asInt()); iterator = context.asValue(new ExecutableProxyIteratorImpl(values)); verifyIterator(iterator.as(Iterator.class), values, false); assertEquals(42, iterator.as(FUNCTION_OBJECT_OBJECT).apply(42)); } @Test public void testConcurrentModifications() { setupEnv(Context.newBuilder().allowAllAccess(true).build()); Object[] values = {"1", "2", "3"}; Array array = new Array(values, Array.UNLIMITED, 1); Value iterable = context.asValue(array); Value iterator = iterable.getIterator(); assertTrue(iterator.hasIteratorNextElement()); assertEquals(values[0], iterator.getIteratorNextElement().asString()); assertFalse(iterator.hasIteratorNextElement()); array.setLimit(Array.UNLIMITED); assertTrue(iterator.hasIteratorNextElement()); assertEquals(values[1], iterator.getIteratorNextElement().asString()); assertTrue(iterator.hasIteratorNextElement()); assertEquals(values[2], iterator.getIteratorNextElement().asString()); assertFalse(iterator.hasIteratorNextElement()); array.setLimit(1); Iterator<?> javaIterator = iterable.getIterator().as(Iterator.class); assertTrue(javaIterator.hasNext()); assertEquals(values[0], javaIterator.next()); assertFalse(javaIterator.hasNext()); array.setLimit(Array.UNLIMITED); assertFails(() -> javaIterator.next(), ConcurrentModificationException.class); assertFalse(javaIterator.hasNext()); assertFails(() -> javaIterator.next(), ConcurrentModificationException.class); assertFalse(javaIterator.hasNext()); array.setLimit(1); Iterator<?> javaIterator2 = iterable.getIterator().as(Iterator.class); assertTrue(javaIterator2.hasNext()); assertEquals(values[0], javaIterator2.next()); array.setLimit(Array.UNLIMITED); assertTrue(javaIterator2.hasNext()); assertEquals(values[1], javaIterator2.next()); assertTrue(javaIterator2.hasNext()); assertEquals(values[2], javaIterator2.next()); assertFails(() -> javaIterator2.next(), NoSuchElementException.class); assertFalse(javaIterator2.hasNext()); assertFails(() -> javaIterator2.next(), NoSuchElementException.class); array.setLimit(Array.UNLIMITED); Iterator<?> javaIterator3 = iterable.getIterator().as(Iterator.class); assertTrue(javaIterator3.hasNext()); assertEquals(values[0], javaIterator3.next()); array.setLimit(1); assertFalse(javaIterator3.hasNext()); assertFails(() -> javaIterator3.next(), NoSuchElementException.class); array.setLimit(Array.UNLIMITED); Iterator<?> javaIterator4 = iterable.getIterator().as(Iterator.class); assertTrue(javaIterator4.hasNext()); assertEquals(values[0], javaIterator4.next()); assertTrue(javaIterator4.hasNext()); array.setLimit(1); assertFails(() -> javaIterator4.next(), ConcurrentModificationException.class); assertFalse(javaIterator4.hasNext()); assertFails(() -> javaIterator4.next(), ConcurrentModificationException.class); List<Object> javaList = new ArrayList<>(Arrays.asList("1", "2", "3")); iterable = context.asValue(javaList); Value iterator2 = iterable.getIterator(); javaList.add("4"); assertFails(() -> iterator2.getIteratorNextElement(), PolyglotException.class); Iterator<?> javaIterator5 = iterable.getIterator().as(Iterator.class); javaList.add("5"); assertFails(() -> javaIterator5.next(), ConcurrentModificationException.class); iterable = context.asValue(ProxyArray.fromList(javaList)); Value iterator3 = iterable.getIterator(); javaList.add("6"); assertFails(() -> iterator3.getIteratorNextElement(), PolyglotException.class); Iterator<?> javaIterator6 = iterable.getIterator().as(Iterator.class); javaList.add("7"); assertFails(() -> javaIterator6.next(), PolyglotException.class); } private static void verifyIterable(Value iterable, Object[] values, boolean endsWithUnreadableElement) { assertTrue(iterable.hasIterator()); assertFalse(iterable.isIterator()); verifyIterator(iterable.getIterator(), values, endsWithUnreadableElement); verifyIterator(iterable.getIterator().as(Iterator.class), values, endsWithUnreadableElement); verifyIterator(iterable.as(Iterable.class).iterator(), values, endsWithUnreadableElement); } private static void verifyIterator(Value iterator, Object[] values, boolean endsWithUnreadableElement) { assertFalse(iterator.hasIterator()); assertTrue(iterator.isIterator()); for (int i = 0; i < values.length; i++) { assertTrue(iterator.hasIteratorNextElement()); assertTrue(iterator.hasIteratorNextElement()); try { Value element = iterator.getIteratorNextElement(); assertNotNull("Iterator should not have an element.", values[i]); assertEquals(values[i], element.asString()); } catch (UnsupportedOperationException uoe) { assertNull("Iterator should have an element.", values[i]); } } if (endsWithUnreadableElement) { assertTrue(iterator.hasIteratorNextElement()); assertFails(() -> iterator.getIteratorNextElement(), UnsupportedOperationException.class); } else { assertFalse(iterator.hasIteratorNextElement()); assertFails(() -> iterator.getIteratorNextElement(), NoSuchElementException.class); } } private static void verifyIterator(Iterator<?> iterator, Object[] values, boolean endsWithUnreadableElement) { for (int i = 0; i < values.length; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.hasNext()); try { Object element = iterator.next(); assertNotNull("Iterator should not have an element.", values[i]); assertEquals(values[i], element); } catch (UnsupportedOperationException uoe) { assertNull("Iterator should have an element.", values[i]); } } if (endsWithUnreadableElement) { assertTrue(iterator.hasNext()); assertFails(() -> iterator.next(), UnsupportedOperationException.class); } else { assertFalse(iterator.hasNext()); assertFails(() -> iterator.next(), NoSuchElementException.class); } } private static CallTarget createAST(TruffleLanguage<?> lang, Object iterable) { FrameDescriptor.Builder builder = FrameDescriptor.newBuilder(); int iterableSlot = builder.addSlot(FrameSlotKind.Object, "iterable", null); int itemSlot = builder.addSlot(FrameSlotKind.Object, "item", null); FrameDescriptor fd = builder.build(); StatementNode log = new LogStatement(IteratorTestFactory.ReadVariableNodeGen.create(itemSlot)); StatementNode main = new BlockStatement( new ExpressionStatement(IteratorTestFactory.WriteVariableNodeGen.create(new ConstantNode(iterable), iterableSlot)), new ForEachStatement(iterableSlot, itemSlot, log)); return new TestRootNode(lang, fd, main).getCallTarget(); } private static Context createContext(VerifyingHandler handler) { return Context.newBuilder().option(String.format("log.%s.level", handler.loggerName), "FINE").logHandler(handler).build(); } @ExportLibrary(InteropLibrary.class) static class SimpleIterable implements TruffleObject { private final Object[] items; SimpleIterable(Object... items) { this.items = items; } @ExportMessage boolean hasIterator() { return true; } @ExportMessage Object getIterator() { return new SimpleIterator(items); } } @ExportLibrary(InteropLibrary.class) static class SimpleIterator implements TruffleObject { private final Object[] items; private int index; SimpleIterator(Object[] items) { this.items = items; this.index = 0; } @ExportMessage boolean isIterator() { return true; } @ExportMessage boolean hasIteratorNextElement() { return index < items.length; } @ExportMessage Object getIteratorNextElement() throws StopIterationException { if (!hasIteratorNextElement()) { throw StopIterationException.create(); } return items[index++]; } } private static final class ExecutableProxyIterableImpl implements ProxyIterable, ProxyExecutable { static final int UNLIMITED = -1; private final Object[] storage; private final int unreadableElementIndex; ExecutableProxyIterableImpl(Object[] data) { this(data, UNLIMITED); } ExecutableProxyIterableImpl(Object[] data, int unreadableElementIndex) { this.storage = data; this.unreadableElementIndex = unreadableElementIndex; } @Override public Object getIterator() { return new ExecutableProxyIteratorImpl(storage, unreadableElementIndex); } @Override public Object execute(Value... arguments) { if (arguments.length != 1) { throw new UnsupportedOperationException(); } return arguments[0]; } } private static final class ExecutableProxyIteratorImpl implements ProxyIterator, ProxyExecutable { private final Object[] storage; private final int unreadableElementIndex; private int index; ExecutableProxyIteratorImpl(Object[] data) { this(data, ExecutableProxyIterableImpl.UNLIMITED); } ExecutableProxyIteratorImpl(Object[] data, int unreadableElementIndex) { this.storage = data; this.unreadableElementIndex = unreadableElementIndex; this.index = 0; } @Override public boolean hasNext() { return index < storage.length; } @Override public Object getNext() { if (index >= storage.length) { throw new NoSuchElementException(); } if (index == unreadableElementIndex) { throw new UnsupportedOperationException(); } else { return storage[index++]; } } @Override public Object execute(Value... arguments) { if (arguments.length != 1) { throw new UnsupportedOperationException(); } return arguments[0]; } } private static final class ProxyIteratorWithMembersImpl implements ProxyIterator, ProxyObject { private Iterator<Object> iterator; ProxyIteratorWithMembersImpl(Iterator<Object> iterator) { this.iterator = iterator; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Object getNext() throws NoSuchElementException, UnsupportedOperationException { return iterator.next(); } @Override public Object getMemberKeys() { return ProxyArray.fromArray("hasNext", "next"); } @Override public Object getMember(String key) { switch (key) { case "hasNext": return (ProxyExecutable) (a) -> hasNext(); case "next": return (ProxyExecutable) (a) -> getNext(); default: return null; } } @Override public boolean hasMember(String key) { switch (key) { case "hasNext": return true; case "next": return true; default: return false; } } @Override public void putMember(String key, Value value) { throw new UnsupportedOperationException(); } } @ExportLibrary(InteropLibrary.class) abstract static class InteropIterator implements TruffleObject { @SuppressWarnings("serial") public static final class Stop extends AbstractTruffleException { } private static final Object STOP = new Object(); private Object next; protected InteropIterator() { } protected abstract Object next() throws Stop; @ExportMessage @SuppressWarnings("static-method") boolean isIterator() { return true; } @ExportMessage boolean hasIteratorNextElement() { fetchNext(); return next != STOP; } @ExportMessage Object getIteratorNextElement() throws StopIterationException { fetchNext(); Object res = next; if (res == STOP) { throw StopIterationException.create(); } else { next = null; } return res; } private void fetchNext() { if (next == null) { try { next = next(); } catch (Stop stop) { next = STOP; } } } } private static final class GuestLanguageIteratorImpl extends InteropIterator { private final Object[] values; private int index; GuestLanguageIteratorImpl(Object[] values) { this.values = values; } @Override public Object next() throws Stop { if (index < values.length) { return values[index++]; } else { throw new Stop(); } } } @ExportLibrary(InteropLibrary.class) static class Array implements TruffleObject { static final int UNLIMITED = -1; private final Object[] items; private final int unreadableElementIndex; @CompilationFinal private int limit; @CompilationFinal private Assumption limitValid; Array(Object[] items) { this(items, UNLIMITED, UNLIMITED); } Array(Object[] items, int unreadableElementIndex, int limit) { this.items = items; this.unreadableElementIndex = unreadableElementIndex; this.limit = limit; this.limitValid = Truffle.getRuntime().createAssumption(); } void setLimit(int newLimit) { if (newLimit < UNLIMITED || newLimit > items.length) { throw new IllegalArgumentException(String.valueOf(newLimit)); } this.limit = newLimit; Assumption oldAssumption = limitValid; limitValid = Truffle.getRuntime().createAssumption(); oldAssumption.invalidate(); } @ExportMessage boolean hasArrayElements() { return true; } @ExportMessage long getArraySize() { if (!limitValid.isValid()) { CompilerDirectives.transferToInterpreterAndInvalidate(); } return limit == UNLIMITED ? items.length : limit; } @ExportMessage boolean isArrayElementReadable(long index) { return index >= 0 && index < getArraySize() && unreadableElementIndex != index; } @ExportMessage Object readArrayElement(long index) throws InvalidArrayIndexException { if (!isArrayElementReadable(index)) { throw InvalidArrayIndexException.create(index); } return items[(int) index]; } } @SuppressWarnings("serial") static final class TypeError extends AbstractTruffleException { @TruffleBoundary TypeError(String expected, Node location) { super("Type error, expected: " + expected, location); } } @SuppressWarnings("serial") static final class NonReadableElementError extends AbstractTruffleException { static final String MESSAGE = "Cannot read iterator next element."; NonReadableElementError(Node location) { super(MESSAGE, location); } } static class TestRootNode extends RootNode { private @Child StatementNode body; TestRootNode(TruffleLanguage<?> lang, FrameDescriptor fd, StatementNode body) { super(lang, fd); this.body = body; } @Override public Object execute(VirtualFrame frame) { body.executeVoid(frame); return true; } } abstract static class ExpressionNode extends Node { abstract Object execute(VirtualFrame frame); } static class ConstantNode extends ExpressionNode { private final Object constant; ConstantNode(Object constant) { this.constant = constant; } @Override Object execute(VirtualFrame frame) { return constant; } } @NodeField(name = "slot", type = int.class) abstract static class ReadVariableNode extends ExpressionNode { protected abstract int getSlot(); @Specialization protected Object readObject(VirtualFrame frame) { try { return frame.getObject(getSlot()); } catch (FrameSlotTypeException e) { throw CompilerDirectives.shouldNotReachHere(e); } } } @NodeChild("valueNode") @NodeField(name = "slot", type = int.class) abstract static class WriteVariableNode extends ExpressionNode { protected abstract int getSlot(); @Specialization protected Object write(VirtualFrame frame, Object value) { frame.getFrameDescriptor().setSlotKind(getSlot(), FrameSlotKind.Object); frame.setObject(getSlot(), value); return value; } } abstract static class StatementNode extends Node { abstract void executeVoid(VirtualFrame frame); } private static class BlockStatement extends StatementNode { @Children StatementNode[] statements; BlockStatement(StatementNode... statements) { this.statements = statements; } @Override @ExplodeLoop void executeVoid(VirtualFrame frame) { for (StatementNode statement : statements) { statement.executeVoid(frame); } } } private static class ExpressionStatement extends StatementNode { private @Child ExpressionNode expression; ExpressionStatement(ExpressionNode expression) { this.expression = expression; } @Override void executeVoid(VirtualFrame frame) { this.expression.execute(frame); } } private static class LogStatement extends StatementNode { private static final TruffleLogger LOG = TruffleLogger.getLogger(ProxyLanguage.ID, IteratorTest.class); private @Child ExpressionNode valueNode; private @Child InteropLibrary strings; LogStatement(ExpressionNode valueNode) { this.valueNode = valueNode; this.strings = InteropLibrary.getFactory().createDispatched(5); } @Override void executeVoid(VirtualFrame frame) { try { LOG.fine(strings.asString(valueNode.execute(frame))); } catch (UnsupportedMessageException ume) { CompilerDirectives.shouldNotReachHere(ume); } } } private static class IterateNode extends Node { private @Child WriteVariableNode setLocal; private @Child StatementNode repeat; private @Child InteropLibrary iterators; IterateNode(int localVariable, StatementNode repeat) { this.setLocal = IteratorTestFactory.WriteVariableNodeGen.create(null, localVariable); this.repeat = repeat; this.iterators = InteropLibrary.getFactory().createDispatched(1); } void execute(VirtualFrame frame, Object iterator) throws UnsupportedMessageException, StopIterationException { if (!iterators.isIterator(iterator)) { throw new TypeError("iterator", this); } while (iterators.hasIteratorNextElement(iterator)) { try { Object item = iterators.getIteratorNextElement(iterator); setLocal.write(frame, item); repeat.executeVoid(frame); } catch (UnsupportedMessageException e) { throw new NonReadableElementError(this); } } } } private static class ForEachStatement extends StatementNode { private @Child ReadVariableNode readIterable; private @Child IterateNode iterate; private @Child InteropLibrary iterables; ForEachStatement(int iterableVariable, int localVariable, StatementNode repeat) { this.readIterable = IteratorTestFactory.ReadVariableNodeGen.create(iterableVariable); this.iterate = new IterateNode(localVariable, repeat); this.iterables = InteropLibrary.getFactory().createDispatched(1); } @Override void executeVoid(VirtualFrame frame) { Object iterable = readIterable.execute(frame); if (!iterables.hasIterator(iterable)) { throw new TypeError("iterable", this); } try { iterate.execute(frame, iterables.getIterator(iterable)); } catch (UnsupportedMessageException | StopIterationException e) { throw CompilerDirectives.shouldNotReachHere(e); } } } private static final class VerifyingHandler extends Handler { final String loggerName; private Queue<String> expected = new ArrayDeque<>(); VerifyingHandler() { loggerName = String.format("%s.%s", ProxyLanguage.ID, IteratorTest.class.getName()); } void expect(String... messages) { Collections.addAll(expected, messages); } @Override public void publish(LogRecord lr) { if (loggerName.equals(lr.getLoggerName())) { String head = expected.remove(); assertEquals(head, lr.getMessage()); } } @Override public void flush() { } @Override public void close() { assertTrue("All expected events must be consumed. Remaining events: " + String.join(", ", expected), expected.isEmpty()); } } }
googleapis/google-cloud-java
37,720
java-enterpriseknowledgegraph/proto-google-cloud-enterpriseknowledgegraph-v1/src/main/java/com/google/cloud/enterpriseknowledgegraph/v1/LookupRequest.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/enterpriseknowledgegraph/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.enterpriseknowledgegraph.v1; /** * * * <pre> * Request message for * [EnterpriseKnowledgeGraphService.Lookup][google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService.Lookup]. * </pre> * * Protobuf type {@code google.cloud.enterpriseknowledgegraph.v1.LookupRequest} */ public final class LookupRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.enterpriseknowledgegraph.v1.LookupRequest) LookupRequestOrBuilder { private static final long serialVersionUID = 0L; // Use LookupRequest.newBuilder() to construct. private LookupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LookupRequest() { parent_ = ""; ids_ = com.google.protobuf.LazyStringArrayList.emptyList(); languages_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new LookupRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.enterpriseknowledgegraph.v1.ServiceProto .internal_static_google_cloud_enterpriseknowledgegraph_v1_LookupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.enterpriseknowledgegraph.v1.ServiceProto .internal_static_google_cloud_enterpriseknowledgegraph_v1_LookupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.class, com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IDS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList ids_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return A list containing the ids. */ public com.google.protobuf.ProtocolStringList getIdsList() { return ids_; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The count of ids. */ public int getIdsCount() { return ids_.size(); } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param index The index of the element to return. * @return The ids at the given index. */ public java.lang.String getIds(int index) { return ids_.get(index); } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param index The index of the value to return. * @return The bytes of the ids at the given index. */ public com.google.protobuf.ByteString getIdsBytes(int index) { return ids_.getByteString(index); } public static final int LANGUAGES_FIELD_NUMBER = 3; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList languages_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @return A list containing the languages. */ public com.google.protobuf.ProtocolStringList getLanguagesList() { return languages_; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @return The count of languages. */ public int getLanguagesCount() { return languages_.size(); } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param index The index of the element to return. * @return The languages at the given index. */ public java.lang.String getLanguages(int index) { return languages_.get(index); } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param index The index of the value to return. * @return The bytes of the languages at the given index. */ public com.google.protobuf.ByteString getLanguagesBytes(int index) { return languages_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } for (int i = 0; i < ids_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, ids_.getRaw(i)); } for (int i = 0; i < languages_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, languages_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } { int dataSize = 0; for (int i = 0; i < ids_.size(); i++) { dataSize += computeStringSizeNoTag(ids_.getRaw(i)); } size += dataSize; size += 1 * getIdsList().size(); } { int dataSize = 0; for (int i = 0; i < languages_.size(); i++) { dataSize += computeStringSizeNoTag(languages_.getRaw(i)); } size += dataSize; size += 1 * getLanguagesList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest)) { return super.equals(obj); } com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest other = (com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getIdsList().equals(other.getIdsList())) return false; if (!getLanguagesList().equals(other.getLanguagesList())) 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 (getIdsCount() > 0) { hash = (37 * hash) + IDS_FIELD_NUMBER; hash = (53 * hash) + getIdsList().hashCode(); } if (getLanguagesCount() > 0) { hash = (37 * hash) + LANGUAGES_FIELD_NUMBER; hash = (53 * hash) + getLanguagesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest 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.enterpriseknowledgegraph.v1.LookupRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest 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.enterpriseknowledgegraph.v1.LookupRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest 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.enterpriseknowledgegraph.v1.LookupRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest 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.enterpriseknowledgegraph.v1.LookupRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest 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.enterpriseknowledgegraph.v1.LookupRequest 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 * [EnterpriseKnowledgeGraphService.Lookup][google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService.Lookup]. * </pre> * * Protobuf type {@code google.cloud.enterpriseknowledgegraph.v1.LookupRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.enterpriseknowledgegraph.v1.LookupRequest) com.google.cloud.enterpriseknowledgegraph.v1.LookupRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.enterpriseknowledgegraph.v1.ServiceProto .internal_static_google_cloud_enterpriseknowledgegraph_v1_LookupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.enterpriseknowledgegraph.v1.ServiceProto .internal_static_google_cloud_enterpriseknowledgegraph_v1_LookupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.class, com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.Builder.class); } // Construct using com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; ids_ = com.google.protobuf.LazyStringArrayList.emptyList(); languages_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.enterpriseknowledgegraph.v1.ServiceProto .internal_static_google_cloud_enterpriseknowledgegraph_v1_LookupRequest_descriptor; } @java.lang.Override public com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest getDefaultInstanceForType() { return com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest build() { com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest buildPartial() { com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest result = new com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { ids_.makeImmutable(); result.ids_ = ids_; } if (((from_bitField0_ & 0x00000004) != 0)) { languages_.makeImmutable(); result.languages_ = languages_; } } @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.enterpriseknowledgegraph.v1.LookupRequest) { return mergeFrom((com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest other) { if (other == com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.ids_.isEmpty()) { if (ids_.isEmpty()) { ids_ = other.ids_; bitField0_ |= 0x00000002; } else { ensureIdsIsMutable(); ids_.addAll(other.ids_); } onChanged(); } if (!other.languages_.isEmpty()) { if (languages_.isEmpty()) { languages_ = other.languages_; bitField0_ |= 0x00000004; } else { ensureLanguagesIsMutable(); languages_.addAll(other.languages_); } 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: { java.lang.String s = input.readStringRequireUtf8(); ensureIdsIsMutable(); ids_.add(s); break; } // case 18 case 26: { java.lang.String s = input.readStringRequireUtf8(); ensureLanguagesIsMutable(); languages_.add(s); break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the Entity's parent resource. * Format: * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList ids_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureIdsIsMutable() { if (!ids_.isModifiable()) { ids_ = new com.google.protobuf.LazyStringArrayList(ids_); } bitField0_ |= 0x00000002; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return A list containing the ids. */ public com.google.protobuf.ProtocolStringList getIdsList() { ids_.makeImmutable(); return ids_; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The count of ids. */ public int getIdsCount() { return ids_.size(); } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param index The index of the element to return. * @return The ids at the given index. */ public java.lang.String getIds(int index) { return ids_.get(index); } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param index The index of the value to return. * @return The bytes of the ids at the given index. */ public com.google.protobuf.ByteString getIdsBytes(int index) { return ids_.getByteString(index); } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param index The index to set the value at. * @param value The ids to set. * @return This builder for chaining. */ public Builder setIds(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIdsIsMutable(); ids_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The ids to add. * @return This builder for chaining. */ public Builder addIds(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIdsIsMutable(); ids_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param values The ids to add. * @return This builder for chaining. */ public Builder addAllIds(java.lang.Iterable<java.lang.String> values) { ensureIdsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, ids_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearIds() { ids_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * Required. The list of entity ids to be used for lookup. * </pre> * * <code>repeated string ids = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes of the ids to add. * @return This builder for chaining. */ public Builder addIdsBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureIdsIsMutable(); ids_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList languages_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureLanguagesIsMutable() { if (!languages_.isModifiable()) { languages_ = new com.google.protobuf.LazyStringArrayList(languages_); } bitField0_ |= 0x00000004; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @return A list containing the languages. */ public com.google.protobuf.ProtocolStringList getLanguagesList() { languages_.makeImmutable(); return languages_; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @return The count of languages. */ public int getLanguagesCount() { return languages_.size(); } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param index The index of the element to return. * @return The languages at the given index. */ public java.lang.String getLanguages(int index) { return languages_.get(index); } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param index The index of the value to return. * @return The bytes of the languages at the given index. */ public com.google.protobuf.ByteString getLanguagesBytes(int index) { return languages_.getByteString(index); } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param index The index to set the value at. * @param value The languages to set. * @return This builder for chaining. */ public Builder setLanguages(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLanguagesIsMutable(); languages_.set(index, value); bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param value The languages to add. * @return This builder for chaining. */ public Builder addLanguages(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureLanguagesIsMutable(); languages_.add(value); bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param values The languages to add. * @return This builder for chaining. */ public Builder addAllLanguages(java.lang.Iterable<java.lang.String> values) { ensureLanguagesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, languages_); bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @return This builder for chaining. */ public Builder clearLanguages() { languages_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); ; onChanged(); return this; } /** * * * <pre> * The list of language codes (defined in ISO 693) to run the query with, * e.g. 'en'. * </pre> * * <code>repeated string languages = 3;</code> * * @param value The bytes of the languages to add. * @return This builder for chaining. */ public Builder addLanguagesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureLanguagesIsMutable(); languages_.add(value); bitField0_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.enterpriseknowledgegraph.v1.LookupRequest) } // @@protoc_insertion_point(class_scope:google.cloud.enterpriseknowledgegraph.v1.LookupRequest) private static final com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest(); } public static com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LookupRequest> PARSER = new com.google.protobuf.AbstractParser<LookupRequest>() { @java.lang.Override public LookupRequest 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<LookupRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LookupRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,779
java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/ListConversationsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2beta1/conversation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The request message for * [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListConversationsRequest} */ public final class ListConversationsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.ListConversationsRequest) ListConversationsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListConversationsRequest.newBuilder() to construct. private ListConversationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListConversationsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListConversationsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.ConversationProto .internal_static_google_cloud_dialogflow_v2beta1_ListConversationsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.ConversationProto .internal_static_google_cloud_dialogflow_v2beta1_ListConversationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.class, com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </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. The next_page_token value returned from a previous list request. * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.ListConversationsRequest)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.ListConversationsRequest other = (com.google.cloud.dialogflow.v2beta1.ListConversationsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.v2beta1.ListConversationsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request message for * [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListConversationsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.ListConversationsRequest) com.google.cloud.dialogflow.v2beta1.ListConversationsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.ConversationProto .internal_static_google_cloud_dialogflow_v2beta1_ListConversationsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.ConversationProto .internal_static_google_cloud_dialogflow_v2beta1_ListConversationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.class, com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.ConversationProto .internal_static_google_cloud_dialogflow_v2beta1_ListConversationsRequest_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListConversationsRequest getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListConversationsRequest build() { com.google.cloud.dialogflow.v2beta1.ListConversationsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListConversationsRequest buildPartial() { com.google.cloud.dialogflow.v2beta1.ListConversationsRequest result = new com.google.cloud.dialogflow.v2beta1.ListConversationsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dialogflow.v2beta1.ListConversationsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2beta1.ListConversationsRequest) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.ListConversationsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.ListConversationsRequest other) { if (other == com.google.cloud.dialogflow.v2beta1.ListConversationsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The project from which to list all conversation. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </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. The next_page_token value returned from a previous list request. * </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. The next_page_token value returned from a previous list request. * </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. The next_page_token value returned from a previous list request. * </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. The next_page_token value returned from a previous list request. * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </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. A filter expression that filters conversations listed in the * response. Only `lifecycle_state` can be filtered on in this way. For * example, the following expression only returns `COMPLETED` conversations: * * `lifecycle_state = "COMPLETED"` * * For more information about filtering, see * [API Filtering](https://aip.dev/160). * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.ListConversationsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.ListConversationsRequest) private static final com.google.cloud.dialogflow.v2beta1.ListConversationsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.ListConversationsRequest(); } public static com.google.cloud.dialogflow.v2beta1.ListConversationsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListConversationsRequest> PARSER = new com.google.protobuf.AbstractParser<ListConversationsRequest>() { @java.lang.Override public ListConversationsRequest 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<ListConversationsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListConversationsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListConversationsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/jackrabbit-filevault
38,315
vault-validation/src/test/java/org/apache/jackrabbit/vault/validation/spi/impl/PackageTypeValidatorTest.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.vault.validation.spi.impl; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.spi.commons.name.NameConstants; import org.apache.jackrabbit.vault.fs.api.WorkspaceFilter; import org.apache.jackrabbit.vault.fs.config.ConfigurationException; import org.apache.jackrabbit.vault.fs.config.DefaultWorkspaceFilter; import org.apache.jackrabbit.vault.packaging.Dependency; import org.apache.jackrabbit.vault.packaging.PackageProperties; import org.apache.jackrabbit.vault.packaging.PackageType; import org.apache.jackrabbit.vault.util.DocViewNode2; import org.apache.jackrabbit.vault.util.DocViewProperty2; import org.apache.jackrabbit.vault.validation.AnyValidationViolationMessageMatcher; import org.apache.jackrabbit.vault.validation.ValidationExecutorTest; import org.apache.jackrabbit.vault.validation.spi.NodeContext; import org.apache.jackrabbit.vault.validation.spi.ValidationContext; import org.apache.jackrabbit.vault.validation.spi.ValidationMessage; import org.apache.jackrabbit.vault.validation.spi.ValidationMessageSeverity; import org.apache.jackrabbit.vault.validation.spi.util.NodeContextImpl; import org.hamcrest.MatcherAssert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; /** * @see <a href="https://issues.apache.org/jira/browse/JCRVLT-170">JCRVLT-170</a> */ @RunWith(MockitoJUnitRunner.class) public class PackageTypeValidatorTest { @Mock ValidationContext parentContainerContext; @Mock PackageProperties parentContainerProperties; @Mock WorkspaceFilter filter; @Mock PackageProperties properties; private PackageTypeValidator validator; @Before public void setUp() { Mockito.when(parentContainerContext.getProperties()).thenReturn(parentContainerProperties); Mockito.when(filter.covers(ArgumentMatchers.anyString())).thenReturn(Boolean.TRUE); } @Test public void testMixedPackageType() { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.ERROR, false, false, false, false, PackageType.MIXED, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/some/node", Paths.get(""), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(filter), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.WARN, PackageTypeValidator.MESSAGE_NO_PACKAGE_TYPE_SET)); // test mixed package type Mockito.when(properties.getPackageType()).thenReturn(PackageType.MIXED); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_LEGACY_TYPE, PackageType.MIXED.toString()))); // validate sling:OsgiConfig node MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/config/someconfigpid", Paths.get("apps", "config", "someconfigpid.xml"), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sub packages of type Content Mockito.when(parentContainerProperties.getPackageType()).thenReturn(PackageType.MIXED); PackageTypeValidator subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTENT, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTENT); MatcherAssert.assertThat(subPackageValidator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sub packages of type Application subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); MatcherAssert.assertThat(subPackageValidator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); } @Test public void testContentPackageType() throws IOException, ConfigurationException { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTENT, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/apps/some/node", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_APP_CONTENT, PackageType.CONTENT, "'apps' or 'libs'"))); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/apps", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_APP_CONTENT, PackageType.CONTENT, "'apps' or 'libs'"))); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/libs/some/node", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_APP_CONTENT, PackageType.CONTENT, "'apps' or 'libs'"))); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/libs", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_APP_CONTENT, PackageType.CONTENT, "'apps' or 'libs'"))); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/content/is/allowed", Paths.get(""), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/etc/packages/some/sub/package.zip", Paths.get("etc", "packages", "some", "sub", "package.zip"), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/apps/install/mybundle-123.jar", Paths.get("apps", "install", "mybundle-123.jar"), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_APP_CONTENT, PackageType.CONTENT, "'apps' or 'libs'")), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_OSGI_BUNDLE_OR_CONFIG_ALLOWED, PackageType.CONTENT, "/apps/install/mybundle-123.jar")) ); MatcherAssert.assertThat(validator.validate(filter), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTENT); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); Mockito.when(parentContainerProperties.getPackageType()).thenReturn(PackageType.CONTENT); // with filters outside mutable areas DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter(); try (InputStream input = this.getClass().getResourceAsStream("/filter-with-mutable-and-immutable-roots.xml")) { filter.load(input); } ValidationExecutorTest.assertViolation(validator.validate(filter), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_FILTER_CONTAINS_IMMUTABLE_ROOTS, PackageType.CONTENT, "/apps/test"))); // validate sub packages of type Content PackageTypeValidator subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTENT, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); MatcherAssert.assertThat(subPackageValidator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.done(), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sling:OsgiConfig node NodeContext context = new NodeContextImpl("/content/config/someconfigpid", Paths.get("content", "config", "someconfigpid.xml"), Paths.get("")); MatcherAssert.assertThat(validator.validate(context), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.validate( new DocViewNode2(NameConstants.JCR_ROOT, Collections.singleton(new DocViewProperty2(NameConstants.JCR_PRIMARYTYPE, "sling:OsgiConfig"))), context, true), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_OSGI_BUNDLE_OR_CONFIG_ALLOWED, PackageType.CONTENT))); // validate other type docview node below config folder MatcherAssert.assertThat(validator.validate( new DocViewNode2(NameConstants.JCR_ROOT, Collections.singleton(new DocViewProperty2(NameConstants.JCR_PRIMARYTYPE, "nt:unstructured"))), context, true), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.done(), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sub packages of type Application subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); ValidationExecutorTest.assertViolation(subPackageValidator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_UNSUPPORTED_SUB_PACKAGE_OF_TYPE, PackageType.CONTENT, PackageType.CONTENT, PackageType.APPLICATION))); } @Test public void testContainerPackageType() throws IOException, ConfigurationException { // regular nodes not allowed! validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTAINER, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/some/node", Paths.get("some", "file1"), Paths.get("base"))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/libs/some/node", Paths.get("some", "file2"), Paths.get("base"))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/content/some/node", Paths.get("some", "file3"), Paths.get("base"))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.done(), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_ONLY_OSGI_BUNDLE_OR_CONFIG_OR_SUBPACKAGE_ALLOWED, PackageType.CONTAINER), "/apps/some/node", Paths.get("some", "file1"), Paths.get("base"), null), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_ONLY_OSGI_BUNDLE_OR_CONFIG_OR_SUBPACKAGE_ALLOWED, PackageType.CONTAINER), "/libs/some/node", Paths.get("some", "file2"), Paths.get("base"), null), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_ONLY_OSGI_BUNDLE_OR_CONFIG_OR_SUBPACKAGE_ALLOWED, PackageType.CONTAINER), "/content/some/node", Paths.get("some", "file3"), Paths.get("base"), null) ); // empty folder should lead to validation error validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTAINER, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/install.runmode", Paths.get("runmode"), Paths.get("base"))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/install.runmode/somebundle.jar", Paths.get("apps", "install.runmode", "somebundle.jar"), Paths.get("base"))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/etc/packages/some/sub/package.zip", Paths.get(""), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // this node is outside the allowed parents MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/install.runmode2", Paths.get("apps", "install", "runmode2"), Paths.get("base"))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(filter), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.done(), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_ONLY_OSGI_BUNDLE_OR_CONFIG_OR_SUBPACKAGE_ALLOWED, PackageType.CONTAINER), "/apps/install.runmode2", Paths.get("apps", "install", "runmode2"), Paths.get("base"), null) ); validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTAINER, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTAINER); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); Mockito.when(parentContainerProperties.getPackageType()).thenReturn(PackageType.CONTAINER); // with filters outside mutable areas DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter(); try (InputStream input = this.getClass().getResourceAsStream("/filter-with-mutable-and-immutable-roots.xml")) { filter.load(input); } ValidationExecutorTest.assertViolation(validator.validate(filter), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_FILTER_CONTAINS_MUTABLE_ROOTS_OUTSIDE_PACKAGES, PackageType.CONTAINER, "/content/test"))); // validate sub packages of type Mixed Mockito.when(properties.getPackageType()).thenReturn(PackageType.MIXED); PackageTypeValidator subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.MIXED, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); ValidationExecutorTest.assertViolation(subPackageValidator.validate(properties), ValidationMessageSeverity.INFO, new ValidationMessage(ValidationMessageSeverity.INFO, String.format(PackageTypeValidator.MESSAGE_UNSUPPORTED_SUB_PACKAGE_OF_TYPE, PackageType.CONTAINER, StringUtils.join(new String[] {PackageType.APPLICATION.toString(),PackageType.CONTENT.toString(),PackageType.CONTAINER.toString()}, ", "), PackageType.MIXED)), new ValidationMessage(ValidationMessageSeverity.INFO, String.format(PackageTypeValidator.MESSAGE_LEGACY_TYPE, PackageType.MIXED)) ); // validate sub packages of type Content subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTENT, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTENT); MatcherAssert.assertThat(subPackageValidator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sub packages of type Container subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTAINER, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); MatcherAssert.assertThat(subPackageValidator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sub packages of type Application subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); MatcherAssert.assertThat(subPackageValidator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sling:OsgiConfig node NodeContext context = new NodeContextImpl("/apps/config/someconfigpid", Paths.get("apps", "config", "someconfigpid.xml"), Paths.get("")); MatcherAssert.assertThat(validator.validate(context), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate( new DocViewNode2(NameConstants.JCR_ROOT, Collections.singleton(new DocViewProperty2(NameConstants.JCR_PRIMARYTYPE, "sling:OsgiConfig"))), context, true), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate other type docview node below config folder MatcherAssert.assertThat(validator.validate( new DocViewNode2(NameConstants.JCR_ROOT, Collections.singleton(new DocViewProperty2(NameConstants.JCR_PRIMARYTYPE, "nt:unstructured"))), context, true), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.done(), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // make sure no dependencies Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTAINER); Mockito.when(properties.getDependencies()).thenReturn(new Dependency[] { Dependency.fromString("some/group:artifact:1.0.0") }); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_DEPENDENCY, PackageType.CONTAINER, "some/group:artifact:1.0.0"))); } @Test public void testApplicationPackageType() throws IOException, ConfigurationException { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/apps/some/script", Paths.get(""), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/libs", Paths.get(""), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/content/some/node", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_APP_CONTENT_FOUND, PackageType.APPLICATION, "'apps' or 'libs'"))); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/etc/something", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_APP_CONTENT_FOUND, PackageType.APPLICATION, "'apps' or 'libs'"))); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/conf/something", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_APP_CONTENT_FOUND, PackageType.APPLICATION, "'apps' or 'libs'"))); // no bundles/configurations ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/apps/install/mybundle.jar", Paths.get("apps", "install", "mybundle.jar"), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_OSGI_BUNDLE_OR_CONFIG_ALLOWED, PackageType.APPLICATION, "/apps/install/mybundle.jar"))); ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/apps/install/config.cfg", Paths.get("apps", "install", "config.cfg"), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_OSGI_BUNDLE_OR_CONFIG_ALLOWED, PackageType.APPLICATION, "/apps/install/config.cfg"))); // mutable node ValidationExecutorTest.assertViolation(validator.validate(new NodeContextImpl("/oak:index/testindex", Paths.get(""), Paths.get(""))), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_APP_CONTENT_FOUND, PackageType.APPLICATION, "'apps' or 'libs'"))); // no hooks Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validation of regular properties should not lead to issues MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // with hooks Map<String, String> hooks = Collections.singletonMap("key", "com.example.ExternalHook"); Mockito.when(properties.getExternalHooks()).thenReturn(hooks); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PACKAGE_HOOKS, PackageType.APPLICATION, hooks))); ValidationExecutorTest.assertViolation(validator.validateMetaInfPath(Paths.get("vault", "hooks", "myhook.jar"), Paths.get(""), false), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PACKAGE_HOOKS, PackageType.APPLICATION, Paths.get("vault", "hooks", "myhook.jar")))); // with regular filter DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter(); try (InputStream input = this.getClass().getResourceAsStream("/simple-filter.xml")) { filter.load(input); } MatcherAssert.assertThat(validator.validate(filter), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // with filters with include/exclude try (InputStream input = this.getClass().getResourceAsStream("/filter.xml")) { filter.load(input); } ValidationExecutorTest.assertViolation(validator.validate(filter), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_FILTER_HAS_INCLUDE_EXCLUDES, PackageType.APPLICATION))); // with filters outside immutable areas try (InputStream input = this.getClass().getResourceAsStream("/filter-with-mutable-and-immutable-roots.xml")) { filter.load(input); } ValidationExecutorTest.assertViolation(validator.validate(filter), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_FILTER_CONTAINS_MUTABLE_ROOTS, PackageType.APPLICATION, "/content/test"))); // validate sling:OsgiConfig node NodeContext context = new NodeContextImpl("/apps/config/someconfigpid", Paths.get("apps", "config", "someconfigpid.xml"), Paths.get("")); MatcherAssert.assertThat(validator.validate(context), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); ValidationExecutorTest.assertViolation(validator.validate( new DocViewNode2(NameConstants.JCR_ROOT, Collections.singleton(new DocViewProperty2(NameConstants.JCR_PRIMARYTYPE, "sling:OsgiConfig"))), context, true), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_NO_OSGI_BUNDLE_OR_CONFIG_ALLOWED, PackageType.APPLICATION))); // validate other type docview node below config folder MatcherAssert.assertThat(validator.validate( new DocViewNode2(NameConstants.JCR_ROOT, Collections.singleton(new DocViewProperty2(NameConstants.JCR_PRIMARYTYPE, "nt:unstructured"))), context, true), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); // validate sub packages of type Content Mockito.when(parentContainerProperties.getPackageType()).thenReturn(PackageType.APPLICATION); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTENT); PackageTypeValidator subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTENT, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); ValidationExecutorTest.assertViolation(subPackageValidator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_UNSUPPORTED_SUB_PACKAGE, PackageType.APPLICATION))); // validate sub packages of type Application subPackageValidator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.CONTENT, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, parentContainerContext); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); Mockito.when(properties.getExternalHooks()).thenReturn(Collections.emptyMap()); ValidationExecutorTest.assertViolation(subPackageValidator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_UNSUPPORTED_SUB_PACKAGE, PackageType.APPLICATION))); } @Test public void testApplicationPackageTypeWithAllowedOakIndex() throws IOException, ConfigurationException { Set<String> immutableRootNodeNames = new HashSet<>(Arrays.asList("oak:index")); validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, immutableRootNodeNames, null); MatcherAssert.assertThat(validator.validate(new NodeContextImpl("/oak:index/myindex", Paths.get(""), Paths.get(""))), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); } @Test public void testApplicationPackageTypeWithAllowedHook() throws IOException, ConfigurationException { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, false, true, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); // with hooks Map<String, String> hooks = Collections.singletonMap("key", "com.example.ExternalHook"); Mockito.when(properties.getExternalHooks()).thenReturn(hooks); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); MatcherAssert.assertThat(validator.validateMetaInfPath(Paths.get("vault", "hooks", "myhook.jar"), Paths.get(""), false), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); } @Test public void testApplicationPackageTypeWithAllowedComplexFilters() throws IOException, ConfigurationException { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.WARN, ValidationMessageSeverity.INFO, false, false, true, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter(); // with filters with include/exclude try (InputStream input = this.getClass().getResourceAsStream("/filter.xml")) { filter.load(input); } MatcherAssert.assertThat(validator.validate(filter), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); } @Test public void testMutableContentProhibited() { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.INFO, ValidationMessageSeverity.INFO, true, false, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); Mockito.when(properties.getPackageType()).thenReturn(PackageType.MIXED); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PROHIBITED_MUTABLE_PACKAGE_TYPE, PackageType.MIXED))); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTENT); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PROHIBITED_MUTABLE_PACKAGE_TYPE, PackageType.CONTENT))); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTAINER); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); } @Test public void testImmutableContentProhibited() { validator = new PackageTypeValidator(filter, ValidationMessageSeverity.ERROR, ValidationMessageSeverity.INFO, ValidationMessageSeverity.INFO, false, true, false, false, PackageType.APPLICATION, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_JCR_INSTALLER_ADDITIONAL_FILE_NODE_PATH_REGEX, PackageTypeValidatorFactory.DEFAULT_IMMUTABLE_ROOT_NODE_NAMES, null); Mockito.when(properties.getPackageType()).thenReturn(PackageType.MIXED); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PROHIBITED_IMMUTABLE_PACKAGE_TYPE, PackageType.MIXED))); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTENT); MatcherAssert.assertThat(validator.validate(properties), AnyValidationViolationMessageMatcher.noValidationViolationMessageInCollection()); Mockito.when(properties.getPackageType()).thenReturn(PackageType.APPLICATION); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PROHIBITED_IMMUTABLE_PACKAGE_TYPE, PackageType.APPLICATION))); Mockito.when(properties.getPackageType()).thenReturn(PackageType.CONTAINER); ValidationExecutorTest.assertViolation(validator.validate(properties), new ValidationMessage(ValidationMessageSeverity.ERROR, String.format(PackageTypeValidator.MESSAGE_PROHIBITED_IMMUTABLE_PACKAGE_TYPE, PackageType.CONTAINER))); } }
apache/kafka
38,113
streams/src/main/java/org/apache/kafka/streams/state/internals/metrics/RocksDBMetrics.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams.state.internals.metrics; import org.apache.kafka.common.metrics.Gauge; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.Sensor.RecordingLevel; import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl; import java.math.BigInteger; import java.util.Objects; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.AVG_SUFFIX; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.MAX_SUFFIX; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.MIN_SUFFIX; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.RATIO_SUFFIX; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.STATE_STORE_LEVEL_GROUP; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.addAvgAndSumMetricsToSensor; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.addRateOfSumAndSumMetricsToSensor; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.addRateOfSumMetricToSensor; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.addSumMetricToSensor; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.addValueMetricToSensor; public class RocksDBMetrics { private RocksDBMetrics() {} private static final String BYTES_WRITTEN_TO_DB = "bytes-written"; private static final String BYTES_READ_FROM_DB = "bytes-read"; private static final String MEMTABLE_BYTES_FLUSHED = "memtable-bytes-flushed"; private static final String MEMTABLE_HIT_RATIO = "memtable-hit" + RATIO_SUFFIX; private static final String MEMTABLE_FLUSH_TIME = "memtable-flush-time"; private static final String MEMTABLE_FLUSH_TIME_AVG = MEMTABLE_FLUSH_TIME + AVG_SUFFIX; private static final String MEMTABLE_FLUSH_TIME_MIN = MEMTABLE_FLUSH_TIME + MIN_SUFFIX; private static final String MEMTABLE_FLUSH_TIME_MAX = MEMTABLE_FLUSH_TIME + MAX_SUFFIX; private static final String WRITE_STALL_DURATION = "write-stall-duration"; private static final String BLOCK_CACHE_DATA_HIT_RATIO = "block-cache-data-hit" + RATIO_SUFFIX; private static final String BLOCK_CACHE_INDEX_HIT_RATIO = "block-cache-index-hit" + RATIO_SUFFIX; private static final String BLOCK_CACHE_FILTER_HIT_RATIO = "block-cache-filter-hit" + RATIO_SUFFIX; private static final String BYTES_READ_DURING_COMPACTION = "bytes-read-compaction"; private static final String BYTES_WRITTEN_DURING_COMPACTION = "bytes-written-compaction"; private static final String COMPACTION_TIME = "compaction-time"; private static final String COMPACTION_TIME_AVG = COMPACTION_TIME + AVG_SUFFIX; private static final String COMPACTION_TIME_MIN = COMPACTION_TIME + MIN_SUFFIX; private static final String COMPACTION_TIME_MAX = COMPACTION_TIME + MAX_SUFFIX; private static final String NUMBER_OF_OPEN_FILES = "number-open-files"; private static final String NUMBER_OF_FILE_ERRORS = "number-file-errors"; static final String NUMBER_OF_ENTRIES_ACTIVE_MEMTABLE = "num-entries-active-mem-table"; static final String NUMBER_OF_DELETES_ACTIVE_MEMTABLE = "num-deletes-active-mem-table"; static final String NUMBER_OF_ENTRIES_IMMUTABLE_MEMTABLES = "num-entries-imm-mem-tables"; static final String NUMBER_OF_DELETES_IMMUTABLE_MEMTABLES = "num-deletes-imm-mem-tables"; static final String NUMBER_OF_IMMUTABLE_MEMTABLES = "num-immutable-mem-table"; static final String CURRENT_SIZE_OF_ACTIVE_MEMTABLE = "cur-size-active-mem-table"; static final String CURRENT_SIZE_OF_ALL_MEMTABLES = "cur-size-all-mem-tables"; static final String SIZE_OF_ALL_MEMTABLES = "size-all-mem-tables"; static final String MEMTABLE_FLUSH_PENDING = "mem-table-flush-pending"; static final String NUMBER_OF_RUNNING_FLUSHES = "num-running-flushes"; static final String COMPACTION_PENDING = "compaction-pending"; static final String NUMBER_OF_RUNNING_COMPACTIONS = "num-running-compactions"; static final String ESTIMATED_BYTES_OF_PENDING_COMPACTION = "estimate-pending-compaction-bytes"; static final String TOTAL_SST_FILES_SIZE = "total-sst-files-size"; static final String LIVE_SST_FILES_SIZE = "live-sst-files-size"; static final String NUMBER_OF_LIVE_VERSIONS = "num-live-versions"; static final String CAPACITY_OF_BLOCK_CACHE = "block-cache-capacity"; static final String USAGE_OF_BLOCK_CACHE = "block-cache-usage"; static final String PINNED_USAGE_OF_BLOCK_CACHE = "block-cache-pinned-usage"; static final String ESTIMATED_NUMBER_OF_KEYS = "estimate-num-keys"; static final String ESTIMATED_MEMORY_OF_TABLE_READERS = "estimate-table-readers-mem"; static final String NUMBER_OF_BACKGROUND_ERRORS = "background-errors"; private static final String BYTES_WRITTEN_TO_DB_RATE_DESCRIPTION = "Average number of bytes written per second to the RocksDB state store"; private static final String BYTES_WRITTEN_TO_DB_TOTAL_DESCRIPTION = "Total number of bytes written to the RocksDB state store"; private static final String BYTES_READ_FROM_DB_RATE_DESCRIPTION = "Average number of bytes read per second from the RocksDB state store"; private static final String BYTES_READ_FROM_DB_TOTAL_DESCRIPTION = "Total number of bytes read from the RocksDB state store"; private static final String MEMTABLE_BYTES_FLUSHED_RATE_DESCRIPTION = "Average number of bytes flushed per second from the memtable to disk"; private static final String MEMTABLE_BYTES_FLUSHED_TOTAL_DESCRIPTION = "Total number of bytes flushed from the memtable to disk"; private static final String MEMTABLE_HIT_RATIO_DESCRIPTION = "Ratio of memtable hits relative to all lookups to the memtable"; private static final String MEMTABLE_FLUSH_TIME_AVG_DESCRIPTION = "Average time spent on flushing the memtable to disk in ms"; private static final String MEMTABLE_FLUSH_TIME_MIN_DESCRIPTION = "Minimum time spent on flushing the memtable to disk in ms"; private static final String MEMTABLE_FLUSH_TIME_MAX_DESCRIPTION = "Maximum time spent on flushing the memtable to disk in ms"; private static final String WRITE_STALL_DURATION_AVG_DESCRIPTION = "Average duration of write stalls in ms"; private static final String WRITE_STALL_DURATION_TOTAL_DESCRIPTION = "Total duration of write stalls in ms"; private static final String BLOCK_CACHE_DATA_HIT_RATIO_DESCRIPTION = "Ratio of block cache hits for data relative to all lookups for data to the block cache"; private static final String BLOCK_CACHE_INDEX_HIT_RATIO_DESCRIPTION = "Ratio of block cache hits for indexes relative to all lookups for indexes to the block cache"; private static final String BLOCK_CACHE_FILTER_HIT_RATIO_DESCRIPTION = "Ratio of block cache hits for filters relative to all lookups for filters to the block cache"; private static final String BYTES_READ_DURING_COMPACTION_DESCRIPTION = "Average number of bytes read per second during compaction"; private static final String BYTES_WRITTEN_DURING_COMPACTION_DESCRIPTION = "Average number of bytes written per second during compaction"; private static final String COMPACTION_TIME_AVG_DESCRIPTION = "Average time spent on compaction in ms"; private static final String COMPACTION_TIME_MIN_DESCRIPTION = "Minimum time spent on compaction in ms"; private static final String COMPACTION_TIME_MAX_DESCRIPTION = "Maximum time spent on compaction in ms"; private static final String NUMBER_OF_OPEN_FILES_DESCRIPTION = "Number of currently open files"; private static final String NUMBER_OF_FILE_ERRORS_DESCRIPTION = "Total number of file errors occurred"; private static final String NUMBER_OF_ENTRIES_ACTIVE_MEMTABLE_DESCRIPTION = "Total number of entries in the active memtable"; private static final String NUMBER_OF_DELETES_ACTIVE_MEMTABLES_DESCRIPTION = "Total number of delete entries in the active memtable"; private static final String NUMBER_OF_ENTRIES_IMMUTABLE_MEMTABLES_DESCRIPTION = "Total number of entries in the unflushed immutable memtables"; private static final String NUMBER_OF_DELETES_IMMUTABLE_MEMTABLES_DESCRIPTION = "Total number of delete entries in the unflushed immutable memtables"; private static final String NUMBER_OF_IMMUTABLE_MEMTABLES_DESCRIPTION = "Number of immutable memtables that have not yet been flushed"; private static final String CURRENT_SIZE_OF_ACTIVE_MEMTABLE_DESCRIPTION = "Approximate size of active memtable in bytes"; private static final String CURRENT_SIZE_OF_ALL_MEMTABLES_DESCRIPTION = "Approximate size of active and unflushed immutable memtables in bytes"; private static final String SIZE_OF_ALL_MEMTABLES_DESCRIPTION = "Approximate size of active, unflushed immutable, and pinned immutable memtables in bytes"; private static final String MEMTABLE_FLUSH_PENDING_DESCRIPTION = "Reports 1 if a memtable flush is pending, otherwise it reports 0"; private static final String NUMBER_OF_RUNNING_FLUSHES_DESCRIPTION = "Number of currently running flushes"; private static final String COMPACTION_PENDING_DESCRIPTION = "Reports 1 if at least one compaction is pending, otherwise it reports 0"; private static final String NUMBER_OF_RUNNING_COMPACTIONS_DESCRIPTION = "Number of currently running compactions"; private static final String ESTIMATED_BYTES_OF_PENDING_COMPACTION_DESCRIPTION = "Estimated total number of bytes a compaction needs to rewrite on disk to get all levels down to under target size"; private static final String TOTAL_SST_FILE_SIZE_DESCRIPTION = "Total size in bytes of all SST files"; private static final String LIVE_SST_FILES_SIZE_DESCRIPTION = "Total size in bytes of all SST files that belong to the latest LSM tree"; private static final String NUMBER_OF_LIVE_VERSIONS_DESCRIPTION = "Number of live versions of the LSM tree"; private static final String CAPACITY_OF_BLOCK_CACHE_DESCRIPTION = "Capacity of the block cache in bytes"; private static final String USAGE_OF_BLOCK_CACHE_DESCRIPTION = "Memory size of the entries residing in block cache in bytes"; private static final String PINNED_USAGE_OF_BLOCK_CACHE_DESCRIPTION = "Memory size for the entries being pinned in the block cache in bytes"; private static final String ESTIMATED_NUMBER_OF_KEYS_DESCRIPTION = "Estimated number of keys in the active and unflushed immutable memtables and storage"; private static final String ESTIMATED_MEMORY_OF_TABLE_READERS_DESCRIPTION = "Estimated memory in bytes used for reading SST tables, excluding memory used in block cache"; private static final String TOTAL_NUMBER_OF_BACKGROUND_ERRORS_DESCRIPTION = "Total number of background errors"; public static class RocksDBMetricContext { private final String taskName; private final String metricsScope; private final String storeName; public RocksDBMetricContext(final String taskName, final String metricsScope, final String storeName) { this.taskName = taskName; this.metricsScope = metricsScope; this.storeName = storeName; } public String taskName() { return taskName; } public String metricsScope() { return metricsScope; } public String storeName() { return storeName; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RocksDBMetricContext that = (RocksDBMetricContext) o; return Objects.equals(taskName, that.taskName) && Objects.equals(metricsScope, that.metricsScope) && Objects.equals(storeName, that.storeName); } @Override public int hashCode() { return Objects.hash(taskName, metricsScope, storeName); } } public static Sensor bytesWrittenToDatabaseSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BYTES_WRITTEN_TO_DB); addRateOfSumAndSumMetricsToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BYTES_WRITTEN_TO_DB, BYTES_WRITTEN_TO_DB_RATE_DESCRIPTION, BYTES_WRITTEN_TO_DB_TOTAL_DESCRIPTION ); return sensor; } public static Sensor bytesReadFromDatabaseSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BYTES_READ_FROM_DB); addRateOfSumAndSumMetricsToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BYTES_READ_FROM_DB, BYTES_READ_FROM_DB_RATE_DESCRIPTION, BYTES_READ_FROM_DB_TOTAL_DESCRIPTION ); return sensor; } public static Sensor memtableBytesFlushedSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, MEMTABLE_BYTES_FLUSHED); addRateOfSumAndSumMetricsToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), MEMTABLE_BYTES_FLUSHED, MEMTABLE_BYTES_FLUSHED_RATE_DESCRIPTION, MEMTABLE_BYTES_FLUSHED_TOTAL_DESCRIPTION ); return sensor; } public static Sensor memtableHitRatioSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, MEMTABLE_HIT_RATIO); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), MEMTABLE_HIT_RATIO, MEMTABLE_HIT_RATIO_DESCRIPTION ); return sensor; } public static Sensor memtableAvgFlushTimeSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, MEMTABLE_FLUSH_TIME_AVG); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), MEMTABLE_FLUSH_TIME_AVG, MEMTABLE_FLUSH_TIME_AVG_DESCRIPTION ); return sensor; } public static Sensor memtableMinFlushTimeSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, MEMTABLE_FLUSH_TIME_MIN); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), MEMTABLE_FLUSH_TIME_MIN, MEMTABLE_FLUSH_TIME_MIN_DESCRIPTION ); return sensor; } public static Sensor memtableMaxFlushTimeSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, MEMTABLE_FLUSH_TIME_MAX); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), MEMTABLE_FLUSH_TIME_MAX, MEMTABLE_FLUSH_TIME_MAX_DESCRIPTION ); return sensor; } public static Sensor writeStallDurationSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, WRITE_STALL_DURATION); addAvgAndSumMetricsToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), WRITE_STALL_DURATION, WRITE_STALL_DURATION_AVG_DESCRIPTION, WRITE_STALL_DURATION_TOTAL_DESCRIPTION ); return sensor; } public static Sensor blockCacheDataHitRatioSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BLOCK_CACHE_DATA_HIT_RATIO); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BLOCK_CACHE_DATA_HIT_RATIO, BLOCK_CACHE_DATA_HIT_RATIO_DESCRIPTION ); return sensor; } public static Sensor blockCacheIndexHitRatioSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BLOCK_CACHE_INDEX_HIT_RATIO); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BLOCK_CACHE_INDEX_HIT_RATIO, BLOCK_CACHE_INDEX_HIT_RATIO_DESCRIPTION ); return sensor; } public static Sensor blockCacheFilterHitRatioSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BLOCK_CACHE_FILTER_HIT_RATIO); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BLOCK_CACHE_FILTER_HIT_RATIO, BLOCK_CACHE_FILTER_HIT_RATIO_DESCRIPTION ); return sensor; } public static Sensor bytesReadDuringCompactionSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BYTES_READ_DURING_COMPACTION); addRateOfSumMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BYTES_READ_DURING_COMPACTION, BYTES_READ_DURING_COMPACTION_DESCRIPTION ); return sensor; } public static Sensor bytesWrittenDuringCompactionSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, BYTES_WRITTEN_DURING_COMPACTION); addRateOfSumMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), BYTES_WRITTEN_DURING_COMPACTION, BYTES_WRITTEN_DURING_COMPACTION_DESCRIPTION ); return sensor; } public static Sensor compactionTimeAvgSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, COMPACTION_TIME_AVG); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), COMPACTION_TIME_AVG, COMPACTION_TIME_AVG_DESCRIPTION ); return sensor; } public static Sensor compactionTimeMinSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, COMPACTION_TIME_MIN); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), COMPACTION_TIME_MIN, COMPACTION_TIME_MIN_DESCRIPTION ); return sensor; } public static Sensor compactionTimeMaxSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, COMPACTION_TIME_MAX); addValueMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), COMPACTION_TIME_MAX, COMPACTION_TIME_MAX_DESCRIPTION ); return sensor; } public static Sensor numberOfOpenFilesSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, NUMBER_OF_OPEN_FILES); addSumMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), NUMBER_OF_OPEN_FILES, false, NUMBER_OF_OPEN_FILES_DESCRIPTION ); return sensor; } public static Sensor numberOfFileErrorsSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext) { final Sensor sensor = createSensor(streamsMetrics, metricContext, NUMBER_OF_FILE_ERRORS); addSumMetricToSensor( sensor, STATE_STORE_LEVEL_GROUP, streamsMetrics.storeLevelTagMap( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName() ), NUMBER_OF_FILE_ERRORS, NUMBER_OF_FILE_ERRORS_DESCRIPTION ); return sensor; } public static void addNumEntriesActiveMemTableMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_ENTRIES_ACTIVE_MEMTABLE, NUMBER_OF_ENTRIES_ACTIVE_MEMTABLE_DESCRIPTION ); } public static void addNumEntriesImmMemTablesMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_ENTRIES_IMMUTABLE_MEMTABLES, NUMBER_OF_ENTRIES_IMMUTABLE_MEMTABLES_DESCRIPTION ); } public static void addNumDeletesImmMemTablesMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_DELETES_IMMUTABLE_MEMTABLES, NUMBER_OF_DELETES_IMMUTABLE_MEMTABLES_DESCRIPTION ); } public static void addNumDeletesActiveMemTableMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_DELETES_ACTIVE_MEMTABLE, NUMBER_OF_DELETES_ACTIVE_MEMTABLES_DESCRIPTION ); } public static void addNumImmutableMemTableMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_IMMUTABLE_MEMTABLES, NUMBER_OF_IMMUTABLE_MEMTABLES_DESCRIPTION ); } public static void addCurSizeActiveMemTable(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, CURRENT_SIZE_OF_ACTIVE_MEMTABLE, CURRENT_SIZE_OF_ACTIVE_MEMTABLE_DESCRIPTION ); } public static void addCurSizeAllMemTables(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, CURRENT_SIZE_OF_ALL_MEMTABLES, CURRENT_SIZE_OF_ALL_MEMTABLES_DESCRIPTION ); } public static void addSizeAllMemTables(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, SIZE_OF_ALL_MEMTABLES, SIZE_OF_ALL_MEMTABLES_DESCRIPTION ); } public static void addMemTableFlushPending(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, MEMTABLE_FLUSH_PENDING, MEMTABLE_FLUSH_PENDING_DESCRIPTION ); } public static void addNumRunningFlushesMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_RUNNING_FLUSHES, NUMBER_OF_RUNNING_FLUSHES_DESCRIPTION ); } public static void addCompactionPendingMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, COMPACTION_PENDING, COMPACTION_PENDING_DESCRIPTION ); } public static void addNumRunningCompactionsMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_RUNNING_COMPACTIONS, NUMBER_OF_RUNNING_COMPACTIONS_DESCRIPTION ); } public static void addEstimatePendingCompactionBytesMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, ESTIMATED_BYTES_OF_PENDING_COMPACTION, ESTIMATED_BYTES_OF_PENDING_COMPACTION_DESCRIPTION ); } public static void addTotalSstFilesSizeMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, TOTAL_SST_FILES_SIZE, TOTAL_SST_FILE_SIZE_DESCRIPTION ); } public static void addLiveSstFilesSizeMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, LIVE_SST_FILES_SIZE, LIVE_SST_FILES_SIZE_DESCRIPTION ); } public static void addNumLiveVersionMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_LIVE_VERSIONS, NUMBER_OF_LIVE_VERSIONS_DESCRIPTION ); } public static void addBlockCacheCapacityMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, CAPACITY_OF_BLOCK_CACHE, CAPACITY_OF_BLOCK_CACHE_DESCRIPTION ); } public static void addBlockCacheUsageMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, USAGE_OF_BLOCK_CACHE, USAGE_OF_BLOCK_CACHE_DESCRIPTION ); } public static void addBlockCachePinnedUsageMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, PINNED_USAGE_OF_BLOCK_CACHE, PINNED_USAGE_OF_BLOCK_CACHE_DESCRIPTION ); } public static void addEstimateNumKeysMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, ESTIMATED_NUMBER_OF_KEYS, ESTIMATED_NUMBER_OF_KEYS_DESCRIPTION ); } public static void addEstimateTableReadersMemMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, ESTIMATED_MEMORY_OF_TABLE_READERS, ESTIMATED_MEMORY_OF_TABLE_READERS_DESCRIPTION ); } public static void addBackgroundErrorsMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider) { addMutableMetric( streamsMetrics, metricContext, valueProvider, NUMBER_OF_BACKGROUND_ERRORS, TOTAL_NUMBER_OF_BACKGROUND_ERRORS_DESCRIPTION ); } private static void addMutableMetric(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final Gauge<BigInteger> valueProvider, final String name, final String description) { streamsMetrics.addStoreLevelMutableMetric( metricContext.taskName(), metricContext.metricsScope(), metricContext.storeName(), name, description, RecordingLevel.INFO, valueProvider ); } private static Sensor createSensor(final StreamsMetricsImpl streamsMetrics, final RocksDBMetricContext metricContext, final String sensorSuffix) { return streamsMetrics.storeLevelSensor( metricContext.taskName(), metricContext.storeName(), sensorSuffix, RecordingLevel.DEBUG); } }
apache/solr
36,503
solr/core/src/test/org/apache/solr/highlight/TestUnifiedSolrHighlighter.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.solr.highlight; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.schema.IndexSchema; import org.junit.AfterClass; import org.junit.BeforeClass; /** Tests for the UnifiedHighlighter Solr plugin * */ public class TestUnifiedSolrHighlighter extends SolrTestCaseJ4 { @BeforeClass public static void beforeClass() throws Exception { System.setProperty("filterCache.enabled", "false"); System.setProperty("queryResultCache.enabled", "false"); System.setProperty( "documentCache.enabled", "true"); // this is why we use this particular solrconfig initCore("solrconfig-cache-enable-disable.xml", "schema-unifiedhighlight.xml"); // test our config is sane, just to be sure: // 'text' and 'text3' should have offsets, 'text2' should not IndexSchema schema = h.getCore().getLatestSchema(); assertTrue(schema.getField("text").storeOffsetsWithPositions()); assertTrue(schema.getField("text3").storeOffsetsWithPositions()); assertFalse(schema.getField("text2").storeOffsetsWithPositions()); } @AfterClass public static void afterClass() { System.clearProperty("filterCache.enabled"); System.clearProperty("queryResultCache.enabled"); System.clearProperty("documentCache.enabled"); System.clearProperty("solr.tests.id.stored"); System.clearProperty("solr.tests.id.docValues"); } @Override public void setUp() throws Exception { super.setUp(); clearIndex(); assertU( adoc( "text", "document one", "text2", "document one", "text3", "crappy document", "id", "101")); assertU( adoc( "text", "second document", "text2", "second document", "text3", "crappier document", "id", "102")); assertU(commit()); } public static SolrQueryRequest req(String... params) { return SolrTestCaseJ4.req(params, "hl.method", "unified"); } public void testSimple() { assertQ( "simplest test", req("q", "text:document", "sort", "id asc", "hl", "true"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'"); } public void testImpossibleOffsetSource() { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> { h.query( req( "q", "text2:document", "hl.offsetSource", "postings", "hl.fl", "text2", "sort", "id asc", "hl", "true")); }); assertTrue("Should warn no offsets", e.getMessage().contains("indexed without offsets")); } public void testMultipleSnippetsReturned() { clearIndex(); assertU( adoc( "text", "Document snippet one. Intermediate sentence. Document snippet two.", "text2", "document one", "text3", "crappy document", "id", "101")); assertU(commit()); assertQ( "multiple snippets test", req( "q", "text:document", "sort", "id asc", "hl", "true", "hl.snippets", "2", "hl.bs.type", "SENTENCE", "hl.fragsize", "-1"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr/str[1]='<em>Document</em> snippet one. '", "//lst[@name='highlighting']/lst[@name='101']/arr/str[2]='<em>Document</em> snippet two.'"); } public void testStrictPhrasesEnabledByDefault() { clearIndex(); assertU( adoc( "text", "Strict phrases should be enabled for phrases", "text2", "document one", "text3", "crappy document", "id", "101")); assertU(commit()); assertQ( "strict phrase handling", req("q", "text:\"strict phrases\"", "sort", "id asc", "hl", "true"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=1", "//lst[@name='highlighting']/lst[@name='101']/arr/str[1]='<em>Strict phrases</em> should be enabled for phrases'"); } public void testStrictPhrasesCanBeDisabled() { clearIndex(); assertU( adoc( "text", "Strict phrases should be disabled for phrases", "text2", "document one", "text3", "crappy document", "id", "101")); assertU(commit()); assertQ( "strict phrase handling", req( "q", "text:\"strict phrases\"", "sort", "id asc", "hl", "true", "hl.usePhraseHighlighter", "false"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=1", "//lst[@name='highlighting']/lst[@name='101']/arr/str[1]='<em>Strict</em> <em>phrases</em> should be disabled for <em>phrases</em>'"); } public void testMultiTermQueryEnabledByDefault() { clearIndex(); assertU( adoc( "text", "Aviary Avenue document", "text2", "document one", "text3", "crappy document", "id", "101")); assertU(commit()); assertQ( "multi term query handling", req("q", "text:av*", "sort", "id asc", "hl", "true"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=1", "//lst[@name='highlighting']/lst[@name='101']/arr/str[1]='<em>Aviary</em> <em>Avenue</em> document'"); } public void testMultiTermQueryCanBeDisabled() { clearIndex(); assertU( adoc( "text", "Aviary Avenue document", "text2", "document one", "text3", "crappy document", "id", "101")); assertU(commit()); assertQ( "multi term query handling", req("q", "text:av*", "sort", "id asc", "hl", "true", "hl.highlightMultiTerm", "false"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=0"); } public void testPagination() { assertQ( "pagination test", req("q", "text:document", "sort", "id asc", "hl", "true", "rows", "1", "start", "1"), "count(//lst[@name='highlighting']/*)=1", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'"); } public void testEmptySnippet() { assertQ( "null snippet test", req("q", "text:one OR *:*", "sort", "id asc", "hl", "true"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='document <em>one</em>'", "count(//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/*)=0"); } public void testDefaultSummary() { assertQ( "null snippet test", req("q", "text:one OR *:*", "sort", "id asc", "hl", "true", "hl.defaultSummary", "true"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='document <em>one</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second document'"); } public void testDifferentField() { assertQ( "highlighting text3", req("q", "text3:document", "sort", "id asc", "hl", "true", "hl.fl", "text3"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); } public void testTwoFields() { assertQ( "highlighting text and text3", req( "q", "text:document text3:document", "sort", "id asc", "hl", "true", "hl.fl", "text,text3"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); } // SOLR-5127 public void testMultipleFieldsViaWildcard() { assertQ( "highlighting text and text3*", req( "q", (random().nextBoolean() ? "text:document text3:document" : "text3:document text:document"), "sort", "id asc", "hl", "true", "hl.fl", (random().nextBoolean() ? "text,text3*" : "text3*,text")), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); } public void testTags() { assertQ( "different pre/post tags", req( "q", "text:document", "sort", "id asc", "hl", "true", "hl.tag.pre", "[", "hl.tag.post", "]"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='[document] one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second [document]'"); } public void testUsingSimplePrePostTags() { assertQ( "different pre/post tags", req( "q", "text:document", "sort", "id asc", "hl", "true", "hl.simple.pre", "[", "hl.simple.post", "]"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='[document] one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second [document]'"); } public void testUsingSimplePrePostTagsPerField() { assertQ( "different pre/post tags", req( "q", "text:document", "sort", "id asc", "hl", "true", "f.text.hl.simple.pre", "[", "f.text.hl.simple.post", "]"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='[document] one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second [document]'"); } public void testTagsPerField() { assertQ( "highlighting text and text3", req( "q", "text:document text3:document", "sort", "id asc", "hl", "true", "hl.fl", "text,text3", "f.text3.hl.tag.pre", "[", "f.text3.hl.tag.post", "]"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy [document]'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier [document]'"); } public void testBreakIteratorWord() { assertQ( "different breakiterator", req( "q", "text:document", "sort", "id asc", "hl", "true", "hl.bs.type", "WORD", "hl.fragsize", "-1"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='<em>document</em>'"); } public void testBreakIteratorWhole() { assertU( adoc( "text", "Document one has a first sentence. Document two has a second sentence.", "id", "103")); assertU(commit()); assertQ( "WHOLE breakiterator", req( "q", "text:document", "sort", "id asc", "hl", "true", "hl.bs.type", "WHOLE", "hl.fragsize", "-1"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='<em>Document</em> one has a first sentence. <em>Document</em> two has a second sentence.'"); assertQ( "hl.fragsize 0 is equivalent to WHOLE", req("q", "text:document", "sort", "id asc", "hl", "true", "hl.fragsize", "0"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='<em>Document</em> one has a first sentence. <em>Document</em> two has a second sentence.'"); } public void testBreakIteratorCustom() { assertU( adoc( "text", "This document contains # special characters, while the other document contains the same # special character.", "id", "103")); assertU( adoc( "text", "While the other document contains the same # special character.", "id", "104")); assertU(commit()); // Set hl.fragAlignRatio because this test was written when it had a middle default String[] defParams = { "q", "text:document", "sort", "id asc", "hl", "true", "hl.method", "unified", "hl.bs.type", "SEPARATOR", "hl.bs.separator", "#", "hl.fragAlignRatio", "0.5" }; assertQ( "CUSTOM breakiterator", req(defParams, "hl.fragsize", "-1"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='This <em>document</em> contains #'"); assertQ( "different breakiterator", req(defParams, "hl.fragsize", "-1"), "//lst[@name='highlighting']/lst[@name='104']/arr[@name='text']/str='While the other <em>document</em> contains the same #'"); assertQ( "CUSTOM breakiterator with fragsize 70 minimum", req(defParams, "hl.fragsize", "70", "hl.fragsizeIsMinimum", "true"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='This <em>document</em> contains # special characters, while the other <em>document</em> contains the same #'"); assertQ( "CUSTOM breakiterator with fragsize 70 avg", req(defParams, "hl.fragsize", "70", "hl.fragsizeIsMinimum", "false"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='This <em>document</em> contains #'"); assertQ( "CUSTOM breakiterator with fragsize 90 avg", req(defParams, "hl.fragsize", "90", "hl.fragsizeIsMinimum", "false"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='This <em>document</em> contains #'"); assertQ( "CUSTOM breakiterator with fragsize 100 avg", req(defParams, "hl.fragsize", "100", "hl.fragsizeIsMinimum", "false"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='This <em>document</em> contains # special characters, while the other <em>document</em> contains the same #'"); } public void testFragsize() { // test default is 70... so make a sentence that is a little less (closer to 70 than end of // text) clearIndex(); assertU( adoc( "id", "10", "text", "This is a sentence just under seventy chars in length blah blah. Next sentence is here.")); assertU(commit()); // Set hl.fragAlignRatio because this test was written when it had a middle default String[] defParams = { "q", "text:seventy", "hl", "true", "hl.method", "unified", "hl.fragAlignRatio", "0.5" }; assertQ( "default fragsize", req(defParams, "hl.fragsizeIsMinimum", "true"), "//lst[@name='highlighting']/lst[@name='10']/arr[@name='text']/str='This is a sentence just under <em>seventy</em> chars in length blah blah. Next sentence is here.'"); assertQ( "default fragsize", req(defParams, "hl.fragsizeIsMinimum", "true", "hl.fragsize", "60"), "//lst[@name='highlighting']/lst[@name='10']/arr[@name='text']/str='This is a sentence just under <em>seventy</em> chars in length blah blah. '"); assertQ( "smaller fragsize", req(defParams, "hl.fragsizeIsMinimum", "false"), "//lst[@name='highlighting']/lst[@name='10']/arr[@name='text']/str='This is a sentence just under <em>seventy</em> chars in length blah blah. '"); assertQ( "default fragsize", req(defParams, "hl.fragsize", "90", "hl.fragsizeIsMinimum", "false"), "//lst[@name='highlighting']/lst[@name='10']/arr[@name='text']/str='This is a sentence just under <em>seventy</em> chars in length blah blah. Next sentence is here.'"); } public void testEncoder() { assertU(adoc("text", "Document one has a first <i>sentence</i>.", "id", "103")); assertU(commit()); assertQ( "html escaped", req("q", "text:document", "sort", "id asc", "hl", "true", "hl.encoder", "html"), "//lst[@name='highlighting']/lst[@name='103']/arr[@name='text']/str='<em>Document</em> one has a first &lt;i&gt;sentence&lt;&#x2F;i&gt;.'"); } public void testRangeQuery() { assertQ( req("q", "id:101", "hl", "true", "hl.q", "text:[dob TO doe]"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=1"); } public void testRequireFieldMatch() { // We highlight on field text3 (hl.fl), but our query only references the "text" field. // Nonetheless, the query word "document" is found in all fields here. assertQ( req( "q", "id:101", "hl", "true", "hl.q", "text:document", "hl.fl", "text3"), // hl.requireFieldMatch is false by default "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/*)=1"); assertQ( req( "q", "id:101", "hl", "true", "hl.q", "text:document", "hl.fl", "text3", "hl.requireFieldMatch", "true"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/*)=0"); } public void testRequireFieldMatchWithQueryFieldPattern() { // without requiring of a field match assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text,text2,text3", "hl.queryFieldPattern", "text,text2,text3", "hl.requireFieldMatch", "false", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text2']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text2']/str='second <em>document</em>'", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> <em>document</em>'"); // with requiring of a field match assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text,text2,text3", "hl.queryFieldPattern", "text,text2,text3", "hl.requireFieldMatch", "true", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'", "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text2']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/arr[@name='text2']/*)=0", "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/*)=0", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> document'"); } public void testQueryFieldPatternIndexedNotStored() { // highlighting on text3 uses all query terms assertQ( req( "q", "text:document OR text2:crappy OR text2_indexed_not_stored:crappier", "hl", "true", "hl.fl", "text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> <em>document</em>'"); // hl.queryFieldPattern==text,text2 uses only some of the query terms assertQ( req( "q", "text:document OR text2:crappy OR text2_indexed_not_stored:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text,text2", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); // hl.queryFieldPattern==text,text2_indexed_not_stored uses only some of the query terms assertQ( req( "q", "text:document OR text2:crappy OR text2_indexed_not_stored:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text,text2_indexed_not_stored", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> <em>document</em>'"); // hl.queryFieldPattern==text2* uses only some of the query terms assertQ( req( "q", "text:document OR text2:crappy OR text2_indexed_not_stored:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text2*", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> document'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> document'"); } public void testQueryFieldPatternMinimal() { // highlighting on text3 uses all query terms assertQ( req( "q", "text:document OR text2:crappy OR text2:crappier", "hl", "true", "hl.fl", "text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> <em>document</em>'"); // hl.requireFieldMatch==true produces no highlights since text3 is not in the query assertQ( req( "q", "text:document OR text2:crappy OR text2:crappier", "hl", "true", "hl.fl", "text3", "hl.requireFieldMatch", "true", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); // hl.queryFieldPattern==text uses only some of the query terms assertQ( req( "q", "text:document OR text2:crappy OR text2:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); } public void testQueryFieldPatternComprehensive() { // searching on 'text' field and highlighting on 'text' field assertQ( req( "q", "text:document", "hl", "true", "hl.fl", "text", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'"); // searching on three fields ('text', 'text2', 'text3') but highlighting only on one of them assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'"); assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text2", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text2']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text2']/str='second <em>document</em>'"); assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> <em>document</em>'"); // searching on three fields ('text', 'text2', 'text3') but highlighting only on one of them, // requiring field match assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text", "hl.requireFieldMatch", "true", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/str='second <em>document</em>'"); assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text2", "hl.requireFieldMatch", "true", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text3", "hl.requireFieldMatch", "true", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='<em>crappier</em> document'"); // searching on three fields ('text', 'text2', 'text3') but highlighting only on one of them // field to match one of the three fields (not the one being highlighted on) // highlight text matching text2 assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text", "hl.queryFieldPattern", "text2", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); // highlight text matching text3 assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text", "hl.queryFieldPattern", "text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); // highlight text2 matching text assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text2", "hl.queryFieldPattern", "text", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text2']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text2']/str='second <em>document</em>'"); // highlight text2 matching text3 assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text2", "hl.queryFieldPattern", "text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); // highlight text3 matching text assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='crappy <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); // highlight text3 matching text2 assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text2", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> document'", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); // searching on three fields ('text', 'text2', 'text3') but highlighting only on one of them // field to match two of the three fields (not the one being highlighted on) assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text", "hl.queryFieldPattern", "text2,text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "count(//lst[@name='highlighting']/lst[@name='101']/*)=0", "count(//lst[@name='highlighting']/lst[@name='102']/*)=0"); assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text2", "hl.queryFieldPattern", "text,text3", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text2']/str='<em>document</em> one'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text2']/str='second <em>document</em>'"); assertQ( req( "q", "text:document OR text2:crappy OR text3:crappier", "hl", "true", "hl.fl", "text3", "hl.queryFieldPattern", "text,text2", "sort", "id asc"), "count(//lst[@name='highlighting']/*)=2", "//lst[@name='highlighting']/lst[@name='101']/arr[@name='text3']/str='<em>crappy</em> <em>document</em>'", "//lst[@name='highlighting']/lst[@name='102']/arr[@name='text3']/str='crappier <em>document</em>'"); } public void testWeightMatchesDisabled() { clearIndex(); assertU(adoc("text", "alpha bravo charlie", "id", "101")); assertU(commit()); assertQ( "weight matches disabled, phrase highlights separately", req("q", "text:\"alpha bravo\"", "hl", "true", "hl.weightMatches", "false"), "count(//lst[@name='highlighting']/lst[@name='101']/arr[@name='text']/*)=1", "//lst[@name='highlighting']/lst[@name='101']/arr/str[1]='<em>alpha</em> <em>bravo</em> charlie'"); } // LUCENE-8492 public void testSurroundQParser() { assertQ( req("q", "{!surround df=text}2w(second, document)", "hl", "true", "hl.fl", "text"), "count(//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/*)=1"); } // LUCENE-7757 public void testComplexPhraseQParser() { assertQ( req("q", "{!complexphrase df=text}(\"sec* doc*\")", "hl", "true", "hl.fl", "text"), "count(//lst[@name='highlighting']/lst[@name='102']/arr[@name='text']/*)=1"); } // SOLR-10321 public void testDontReturnEmptyHighlights() throws Exception { clearIndex(); // this doc has no value for field text2 assertU(adoc("text", "third document", "id", "103")); assertU(commit()); // query on text & text2. Assert we only highlight text; text2 shouldn't be present at all assertJQ( req( "q", "text:document OR text2:document", "hl", "true", "hl.fl", "text, text2", "sort", "id asc", "hl", "true"), "highlighting=={\n" + " '103':{\n" + " 'text':['third <em>document</em>']}}}"); } }
apache/druid
37,429
processing/src/test/java/org/apache/druid/query/groupby/GroupByLimitPushDownMultiNodeMergeTest.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.query.groupby; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.smile.SmileFactory; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.druid.data.input.InputRow; import org.apache.druid.data.input.MapBasedInputRow; import org.apache.druid.data.input.impl.DimensionSchema; import org.apache.druid.data.input.impl.DimensionsSpec; import org.apache.druid.data.input.impl.LongDimensionSchema; import org.apache.druid.data.input.impl.StringDimensionSchema; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.HumanReadableBytes; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.granularity.PeriodGranularity; import org.apache.druid.java.util.common.guava.Sequence; import org.apache.druid.java.util.common.guava.Sequences; import org.apache.druid.java.util.common.io.Closer; import org.apache.druid.math.expr.ExprMacroTable; import org.apache.druid.query.BySegmentQueryRunner; import org.apache.druid.query.DirectQueryProcessingPool; import org.apache.druid.query.DruidProcessingConfig; import org.apache.druid.query.FinalizeResultsQueryRunner; import org.apache.druid.query.Query; import org.apache.druid.query.QueryPlus; import org.apache.druid.query.QueryRunner; import org.apache.druid.query.QueryRunnerFactory; import org.apache.druid.query.QueryToolChest; import org.apache.druid.query.QueryWatcher; import org.apache.druid.query.TestBufferPool; import org.apache.druid.query.aggregation.CountAggregatorFactory; import org.apache.druid.query.aggregation.LongSumAggregatorFactory; import org.apache.druid.query.context.ResponseContext; import org.apache.druid.query.dimension.DefaultDimensionSpec; import org.apache.druid.query.dimension.ExtractionDimensionSpec; import org.apache.druid.query.expression.TestExprMacroTable; import org.apache.druid.query.extraction.TimeFormatExtractionFn; import org.apache.druid.query.groupby.orderby.DefaultLimitSpec; import org.apache.druid.query.groupby.orderby.OrderByColumnSpec; import org.apache.druid.query.ordering.StringComparators; import org.apache.druid.query.spec.MultipleIntervalSegmentSpec; import org.apache.druid.query.spec.QuerySegmentSpec; import org.apache.druid.segment.IndexIO; import org.apache.druid.segment.IndexMergerV9; import org.apache.druid.segment.IndexSpec; import org.apache.druid.segment.QueryableIndex; import org.apache.druid.segment.QueryableIndexSegment; import org.apache.druid.segment.Segment; import org.apache.druid.segment.TestHelper; import org.apache.druid.segment.column.ColumnConfig; import org.apache.druid.segment.column.ColumnHolder; 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.incremental.OnheapIncrementalIndex; import org.apache.druid.segment.virtual.ExpressionVirtualColumn; import org.apache.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory; import org.apache.druid.testing.InitializedNullHandlingTest; import org.apache.druid.timeline.SegmentId; import org.joda.time.DateTimeZone; import org.joda.time.Period; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; 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.concurrent.ExecutorService; import java.util.function.Function; public class GroupByLimitPushDownMultiNodeMergeTest extends InitializedNullHandlingTest { public static final ObjectMapper JSON_MAPPER; private static final IndexMergerV9 INDEX_MERGER_V9; private static final IndexIO INDEX_IO; private File tmpDir; private QueryRunnerFactory<ResultRow, GroupByQuery> groupByFactoryBroker; private QueryRunnerFactory<ResultRow, GroupByQuery> groupByFactoryHistorical; private QueryRunnerFactory<ResultRow, GroupByQuery> groupByFactoryHistorical2; private List<IncrementalIndex> incrementalIndices = new ArrayList<>(); private List<QueryableIndex> groupByIndices = new ArrayList<>(); private ExecutorService executorService; private Closer resourceCloser; static { JSON_MAPPER = new DefaultObjectMapper(); JSON_MAPPER.setInjectableValues( new InjectableValues.Std().addValue( ExprMacroTable.class, ExprMacroTable.nil() ) ); INDEX_IO = new IndexIO( JSON_MAPPER, new ColumnConfig() { } ); INDEX_MERGER_V9 = new IndexMergerV9(JSON_MAPPER, INDEX_IO, OffHeapMemorySegmentWriteOutMediumFactory.instance()); } private IncrementalIndex makeIncIndex(boolean withRollup) { return makeIncIndex(withRollup, Arrays.asList( new StringDimensionSchema("dimA"), new LongDimensionSchema("metA") )); } private IncrementalIndex makeIncIndex(boolean withRollup, List<DimensionSchema> dimensions) { return new OnheapIncrementalIndex.Builder() .setIndexSchema( new IncrementalIndexSchema.Builder() .withDimensionsSpec( new DimensionsSpec( Arrays.asList( new StringDimensionSchema("dimA"), new LongDimensionSchema("metA") ) ) ) .withRollup(withRollup) .build() ) .setMaxRowCount(1000) .build(); } @Before public void setup() throws Exception { tmpDir = FileUtils.createTempDir(); InputRow row; List<String> dimNames = Arrays.asList("dimA", "metA"); Map<String, Object> event; final IncrementalIndex indexA = makeIncIndex(false); incrementalIndices.add(indexA); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 2395L); row = new MapBasedInputRow(1505260888888L, dimNames, event); indexA.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 8L); row = new MapBasedInputRow(1505260800000L, dimNames, event); indexA.add(row); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 5028L); row = new MapBasedInputRow(1505264400000L, dimNames, event); indexA.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 7L); row = new MapBasedInputRow(1505264400400L, dimNames, event); indexA.add(row); final File fileA = INDEX_MERGER_V9.persist( indexA, new File(tmpDir, "A"), IndexSpec.getDefault(), null ); QueryableIndex qindexA = INDEX_IO.loadIndex(fileA); final IncrementalIndex indexB = makeIncIndex(false); incrementalIndices.add(indexB); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 4718L); row = new MapBasedInputRow(1505260800000L, dimNames, event); indexB.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 18L); row = new MapBasedInputRow(1505260800000L, dimNames, event); indexB.add(row); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 2698L); row = new MapBasedInputRow(1505264400000L, dimNames, event); indexB.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 3L); row = new MapBasedInputRow(1505264400000L, dimNames, event); indexB.add(row); final File fileB = INDEX_MERGER_V9.persist( indexB, new File(tmpDir, "B"), IndexSpec.getDefault(), null ); QueryableIndex qindexB = INDEX_IO.loadIndex(fileB); final IncrementalIndex indexC = makeIncIndex(false); incrementalIndices.add(indexC); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 2395L); row = new MapBasedInputRow(1505260800000L, dimNames, event); indexC.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 8L); row = new MapBasedInputRow(1605260800000L, dimNames, event); indexC.add(row); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 5028L); row = new MapBasedInputRow(1705264400000L, dimNames, event); indexC.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 7L); row = new MapBasedInputRow(1805264400000L, dimNames, event); indexC.add(row); final File fileC = INDEX_MERGER_V9.persist( indexC, new File(tmpDir, "C"), IndexSpec.getDefault(), null ); QueryableIndex qindexC = INDEX_IO.loadIndex(fileC); final IncrementalIndex indexD = makeIncIndex(false); incrementalIndices.add(indexD); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 4718L); row = new MapBasedInputRow(1505260800000L, dimNames, event); indexD.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 18L); row = new MapBasedInputRow(1605260800000L, dimNames, event); indexD.add(row); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("metA", 2698L); row = new MapBasedInputRow(1705264400000L, dimNames, event); indexD.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("metA", 3L); row = new MapBasedInputRow(1805264400000L, dimNames, event); indexD.add(row); final File fileD = INDEX_MERGER_V9.persist( indexD, new File(tmpDir, "D"), IndexSpec.getDefault(), null ); QueryableIndex qindexD = INDEX_IO.loadIndex(fileD); List<String> dimNames2 = Arrays.asList("dimA", "dimB", "metA"); List<DimensionSchema> dimensions = Arrays.asList( new StringDimensionSchema("dimA"), new StringDimensionSchema("dimB"), new LongDimensionSchema("metA") ); final IncrementalIndex indexE = makeIncIndex(false, dimensions); incrementalIndices.add(indexE); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("dimB", "raw"); event.put("metA", 5L); row = new MapBasedInputRow(1505260800000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("dimB", "ripe"); event.put("metA", 9L); row = new MapBasedInputRow(1605260800000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "pomegranate"); event.put("dimB", "raw"); event.put("metA", 3L); row = new MapBasedInputRow(1705264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "mango"); event.put("dimB", "ripe"); event.put("metA", 7L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "grape"); event.put("dimB", "raw"); event.put("metA", 5L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "apple"); event.put("dimB", "ripe"); event.put("metA", 3L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "apple"); event.put("dimB", "raw"); event.put("metA", 1L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "apple"); event.put("dimB", "ripe"); event.put("metA", 4L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "apple"); event.put("dimB", "raw"); event.put("metA", 1L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "banana"); event.put("dimB", "ripe"); event.put("metA", 4L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "orange"); event.put("dimB", "raw"); event.put("metA", 9L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "peach"); event.put("dimB", "ripe"); event.put("metA", 7L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "orange"); event.put("dimB", "raw"); event.put("metA", 2L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); event = new HashMap<>(); event.put("dimA", "strawberry"); event.put("dimB", "ripe"); event.put("metA", 10L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexE.add(row); final File fileE = INDEX_MERGER_V9.persist( indexE, new File(tmpDir, "E"), IndexSpec.getDefault(), null ); QueryableIndex qindexE = INDEX_IO.loadIndex(fileE); final IncrementalIndex indexF = makeIncIndex(false, dimensions); incrementalIndices.add(indexF); event = new HashMap<>(); event.put("dimA", "kiwi"); event.put("dimB", "raw"); event.put("metA", 7L); row = new MapBasedInputRow(1505260800000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "watermelon"); event.put("dimB", "ripe"); event.put("metA", 14L); row = new MapBasedInputRow(1605260800000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "kiwi"); event.put("dimB", "raw"); event.put("metA", 8L); row = new MapBasedInputRow(1705264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "kiwi"); event.put("dimB", "ripe"); event.put("metA", 8L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "lemon"); event.put("dimB", "raw"); event.put("metA", 3L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "cherry"); event.put("dimB", "ripe"); event.put("metA", 2L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "cherry"); event.put("dimB", "raw"); event.put("metA", 7L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "avocado"); event.put("dimB", "ripe"); event.put("metA", 12L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "cherry"); event.put("dimB", "raw"); event.put("metA", 3L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "plum"); event.put("dimB", "ripe"); event.put("metA", 5L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "plum"); event.put("dimB", "raw"); event.put("metA", 3L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); event = new HashMap<>(); event.put("dimA", "lime"); event.put("dimB", "ripe"); event.put("metA", 7L); row = new MapBasedInputRow(1805264400000L, dimNames2, event); indexF.add(row); final File fileF = INDEX_MERGER_V9.persist( indexF, new File(tmpDir, "F"), IndexSpec.getDefault(), null ); QueryableIndex qindexF = INDEX_IO.loadIndex(fileF); groupByIndices = Arrays.asList(qindexA, qindexB, qindexC, qindexD, qindexE, qindexF); resourceCloser = Closer.create(); setupGroupByFactory(); } private void setupGroupByFactory() { executorService = Execs.multiThreaded(3, "GroupByThreadPool[%d]"); final TestBufferPool bufferPool = TestBufferPool.offHeap(10_000_000, Integer.MAX_VALUE); final TestBufferPool mergePoolBroker = TestBufferPool.offHeap(10_000_000, 1); final TestBufferPool mergePoolHistorical = TestBufferPool.offHeap(10_000_000, 1); final TestBufferPool mergePoolHistorical2 = TestBufferPool.offHeap(10_000_000, 1); resourceCloser.register(() -> { // Verify that all objects have been returned to the pools. Assert.assertEquals(0, bufferPool.getOutstandingObjectCount()); Assert.assertEquals(0, mergePoolBroker.getOutstandingObjectCount()); Assert.assertEquals(0, mergePoolHistorical.getOutstandingObjectCount()); Assert.assertEquals(0, mergePoolHistorical2.getOutstandingObjectCount()); }); final GroupByQueryConfig config = new GroupByQueryConfig() { @Override public int getBufferGrouperInitialBuckets() { return -1; } @Override public HumanReadableBytes getMaxOnDiskStorage() { return HumanReadableBytes.valueOf(1_000_000_000L); } }; config.setSingleThreaded(false); DruidProcessingConfig druidProcessingConfig = new DruidProcessingConfig() { @Override public int getNumThreads() { // Used by "v2" strategy for concurrencyHint return 2; } @Override public String getFormatString() { return null; } }; final Supplier<GroupByQueryConfig> configSupplier = Suppliers.ofInstance(config); final GroupByStatsProvider groupByStatsProvider = new GroupByStatsProvider(); final GroupByResourcesReservationPool groupByResourcesReservationPoolBroker = new GroupByResourcesReservationPool(mergePoolBroker, config); final GroupByResourcesReservationPool groupByResourcesReservationPoolHistorical = new GroupByResourcesReservationPool(mergePoolHistorical, config); final GroupByResourcesReservationPool groupByResourcesReservationPoolHistorical2 = new GroupByResourcesReservationPool(mergePoolHistorical2, config); final GroupingEngine groupingEngineBroker = new GroupingEngine( druidProcessingConfig, configSupplier, groupByResourcesReservationPoolBroker, TestHelper.makeJsonMapper(), new ObjectMapper(new SmileFactory()), NOOP_QUERYWATCHER, groupByStatsProvider ); final GroupingEngine groupingEngineHistorical = new GroupingEngine( druidProcessingConfig, configSupplier, groupByResourcesReservationPoolHistorical, TestHelper.makeJsonMapper(), new ObjectMapper(new SmileFactory()), NOOP_QUERYWATCHER, groupByStatsProvider ); final GroupingEngine groupingEngineHistorical2 = new GroupingEngine( druidProcessingConfig, configSupplier, groupByResourcesReservationPoolHistorical2, TestHelper.makeJsonMapper(), new ObjectMapper(new SmileFactory()), NOOP_QUERYWATCHER, groupByStatsProvider ); groupByFactoryBroker = new GroupByQueryRunnerFactory( groupingEngineBroker, new GroupByQueryQueryToolChest(groupingEngineBroker, groupByResourcesReservationPoolBroker), bufferPool ); groupByFactoryHistorical = new GroupByQueryRunnerFactory( groupingEngineHistorical, new GroupByQueryQueryToolChest(groupingEngineHistorical, groupByResourcesReservationPoolHistorical), bufferPool ); groupByFactoryHistorical2 = new GroupByQueryRunnerFactory( groupingEngineHistorical2, new GroupByQueryQueryToolChest(groupingEngineHistorical2, groupByResourcesReservationPoolHistorical2), bufferPool ); } @After public void tearDown() throws Exception { for (IncrementalIndex incrementalIndex : incrementalIndices) { incrementalIndex.close(); } for (QueryableIndex queryableIndex : groupByIndices) { queryableIndex.close(); } resourceCloser.close(); if (tmpDir != null) { FileUtils.deleteDirectory(tmpDir); } } @Test public void testDescendingNumerics() { QueryToolChest<ResultRow, GroupByQuery> toolChestHistorical = groupByFactoryHistorical.getToolchest(); QueryRunner<ResultRow> theRunner = new FinalizeResultsQueryRunner<>( toolChestHistorical.mergeResults( groupByFactoryHistorical.mergeRunners(DirectQueryProcessingPool.INSTANCE, getRunner1(2)), true ), (QueryToolChest) toolChestHistorical ); QueryToolChest<ResultRow, GroupByQuery> toolChestHistorical2 = groupByFactoryHistorical2.getToolchest(); QueryRunner<ResultRow> theRunner2 = new FinalizeResultsQueryRunner<>( toolChestHistorical2.mergeResults( groupByFactoryHistorical2.mergeRunners(DirectQueryProcessingPool.INSTANCE, getRunner2(3)), true ), (QueryToolChest) toolChestHistorical2 ); QueryToolChest<ResultRow, GroupByQuery> toolChestBroker = groupByFactoryHistorical.getToolchest(); QueryRunner<ResultRow> finalRunner = new FinalizeResultsQueryRunner<>( toolChestBroker.mergeResults( new QueryRunner<>() { @Override public Sequence<ResultRow> run(QueryPlus<ResultRow> queryPlus, ResponseContext responseContext) { return Sequences .simple( ImmutableList.of( theRunner.run(GroupByQueryRunnerTestHelper.populateResourceId(queryPlus), responseContext), theRunner2.run(GroupByQueryRunnerTestHelper.populateResourceId(queryPlus), responseContext) ) ) .flatMerge(Function.identity(), queryPlus.getQuery().getResultOrdering()); } }, false ), (QueryToolChest) toolChestBroker ); QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(Intervals.utc(1500000000000L, 1900000000000L)) ); DefaultLimitSpec ls2 = new DefaultLimitSpec( Arrays.asList( new OrderByColumnSpec("d0", OrderByColumnSpec.Direction.DESCENDING, StringComparators.NUMERIC), new OrderByColumnSpec("d1", OrderByColumnSpec.Direction.DESCENDING, StringComparators.NUMERIC), new OrderByColumnSpec("d2", OrderByColumnSpec.Direction.DESCENDING, StringComparators.NUMERIC) ), 100 ); GroupByQuery query = GroupByQuery .builder() .setDataSource("blah") .setQuerySegmentSpec(intervalSpec) .setVirtualColumns( new ExpressionVirtualColumn( "d0:v", "timestamp_extract(\"__time\",'YEAR','UTC')", ColumnType.LONG, TestExprMacroTable.INSTANCE ), new ExpressionVirtualColumn( "d1:v", "timestamp_extract(\"__time\",'MONTH','UTC')", ColumnType.LONG, TestExprMacroTable.INSTANCE ), new ExpressionVirtualColumn( "d2:v", "timestamp_extract(\"__time\",'DAY','UTC')", ColumnType.LONG, TestExprMacroTable.INSTANCE ) ) .setDimensions( new DefaultDimensionSpec("d0:v", "d0", ColumnType.LONG), new DefaultDimensionSpec("d1:v", "d1", ColumnType.LONG), new DefaultDimensionSpec("d2:v", "d2", ColumnType.LONG) ).setAggregatorSpecs(new CountAggregatorFactory("a0")) .setLimitSpec( ls2 ) .setContext( ImmutableMap.of( GroupByQueryConfig.CTX_KEY_APPLY_LIMIT_PUSH_DOWN, true ) ) .setGranularity(Granularities.ALL) .build(); Sequence<ResultRow> queryResult = finalRunner.run( QueryPlus.wrap(GroupByQueryRunnerTestHelper.populateResourceId(query)), ResponseContext.createEmpty() ); List<ResultRow> results = queryResult.toList(); ResultRow expectedRow0 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "d0", 2027L, "d1", 3L, "d2", 17L, "a0", 2L ); ResultRow expectedRow1 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "d0", 2024L, "d1", 1L, "d2", 14L, "a0", 2L ); ResultRow expectedRow2 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "d0", 2020L, "d1", 11L, "d2", 13L, "a0", 2L ); ResultRow expectedRow3 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "d0", 2017L, "d1", 9L, "d2", 13L, "a0", 2L ); System.out.println(results); Assert.assertEquals(4, results.size()); Assert.assertEquals(expectedRow0, results.get(0)); Assert.assertEquals(expectedRow1, results.get(1)); Assert.assertEquals(expectedRow2, results.get(2)); Assert.assertEquals(expectedRow3, results.get(3)); } @Test public void testPartialLimitPushDownMerge() { // one segment's results use limit push down, the other doesn't because of insufficient buffer capacity QueryToolChest<ResultRow, GroupByQuery> toolChestHistorical = groupByFactoryHistorical.getToolchest(); QueryRunner<ResultRow> theRunner = new FinalizeResultsQueryRunner<>( toolChestHistorical.mergeResults( groupByFactoryHistorical.mergeRunners(DirectQueryProcessingPool.INSTANCE, getRunner1(0)), true ), (QueryToolChest) toolChestHistorical ); QueryToolChest<ResultRow, GroupByQuery> toolChestHistorical2 = groupByFactoryHistorical2.getToolchest(); QueryRunner<ResultRow> theRunner2 = new FinalizeResultsQueryRunner<>( toolChestHistorical2.mergeResults( groupByFactoryHistorical2.mergeRunners(DirectQueryProcessingPool.INSTANCE, getRunner2(1)), true ), (QueryToolChest) toolChestHistorical2 ); QueryToolChest<ResultRow, GroupByQuery> toolchestBroker = groupByFactoryBroker.getToolchest(); QueryRunner<ResultRow> finalRunner = new FinalizeResultsQueryRunner<>( toolchestBroker.mergeResults( new QueryRunner<>() { @Override public Sequence<ResultRow> run(QueryPlus<ResultRow> queryPlus, ResponseContext responseContext) { return Sequences .simple( ImmutableList.of( theRunner.run(GroupByQueryRunnerTestHelper.populateResourceId(queryPlus), responseContext), theRunner2.run(GroupByQueryRunnerTestHelper.populateResourceId(queryPlus), responseContext) ) ) .flatMerge(Function.identity(), queryPlus.getQuery().getResultOrdering()); } }, false ), (QueryToolChest) toolchestBroker ); QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(Intervals.utc(1500000000000L, 1600000000000L)) ); GroupByQuery query = GroupByQuery .builder() .setDataSource("blah") .setQuerySegmentSpec(intervalSpec) .setDimensions( new DefaultDimensionSpec("dimA", "dimA"), new ExtractionDimensionSpec( ColumnHolder.TIME_COLUMN_NAME, "hour", ColumnType.LONG, new TimeFormatExtractionFn( null, null, null, new PeriodGranularity(new Period("PT1H"), null, DateTimeZone.UTC), true ) ) ) .setAggregatorSpecs(new LongSumAggregatorFactory("metASum", "metA")) .setLimitSpec( new DefaultLimitSpec( Arrays.asList( new OrderByColumnSpec("hour", OrderByColumnSpec.Direction.ASCENDING, StringComparators.NUMERIC), new OrderByColumnSpec("dimA", OrderByColumnSpec.Direction.ASCENDING) ), 1000 ) ) .setContext( ImmutableMap.of( GroupByQueryConfig.CTX_KEY_APPLY_LIMIT_PUSH_DOWN, true ) ) .setGranularity(Granularities.ALL) .build(); Sequence<ResultRow> queryResult = finalRunner.run( QueryPlus.wrap(GroupByQueryRunnerTestHelper.populateResourceId(query)), ResponseContext.createEmpty() ); List<ResultRow> results = queryResult.toList(); ResultRow expectedRow0 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "dimA", "mango", "hour", 1505260800000L, "metASum", 26L ); ResultRow expectedRow1 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "dimA", "pomegranate", "hour", 1505260800000L, "metASum", 7113L ); ResultRow expectedRow2 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "dimA", "mango", "hour", 1505264400000L, "metASum", 10L ); ResultRow expectedRow3 = GroupByQueryRunnerTestHelper.createExpectedRow( query, "2017-07-14T02:40:00.000Z", "dimA", "pomegranate", "hour", 1505264400000L, "metASum", 7726L ); Assert.assertEquals(4, results.size()); Assert.assertEquals(expectedRow0, results.get(0)); Assert.assertEquals(expectedRow1, results.get(1)); Assert.assertEquals(expectedRow2, results.get(2)); Assert.assertEquals(expectedRow3, results.get(3)); } @Test public void testForcePushLimitDownAccuracyWhenSortHasNonGroupingFields() { // The two testing segments have non overlapping groups, so the result should be 100% accurate even // forceLimitPushDown is applied List<ResultRow> resultsWithoutLimitPushDown = testForcePushLimitDownAccuracyWhenSortHasNonGroupingFieldsHelper(ImmutableMap.of()); List<ResultRow> resultsWithLimitPushDown = testForcePushLimitDownAccuracyWhenSortHasNonGroupingFieldsHelper(ImmutableMap.of( GroupByQueryConfig.CTX_KEY_APPLY_LIMIT_PUSH_DOWN, true, GroupByQueryConfig.CTX_KEY_FORCE_LIMIT_PUSH_DOWN, true )); List<ResultRow> expectedResults = ImmutableList.of( ResultRow.of("mango", "ripe", 16), ResultRow.of("kiwi", "raw", 15), ResultRow.of("watermelon", "ripe", 14), ResultRow.of("avocado", "ripe", 12), ResultRow.of("orange", "raw", 11) ); Assert.assertEquals(expectedResults.toString(), resultsWithoutLimitPushDown.toString()); Assert.assertEquals(expectedResults.toString(), resultsWithLimitPushDown.toString()); } private List<ResultRow> testForcePushLimitDownAccuracyWhenSortHasNonGroupingFieldsHelper(Map<String, Object> context) { QueryToolChest<ResultRow, GroupByQuery> toolChestHistorical = groupByFactoryHistorical.getToolchest(); QueryRunner<ResultRow> theRunner = new FinalizeResultsQueryRunner<>( toolChestHistorical.mergeResults( groupByFactoryHistorical.mergeRunners(DirectQueryProcessingPool.INSTANCE, getRunner1(4)), true ), (QueryToolChest) toolChestHistorical ); QueryToolChest<ResultRow, GroupByQuery> toolChestHistorical2 = groupByFactoryHistorical2.getToolchest(); QueryRunner<ResultRow> theRunner2 = new FinalizeResultsQueryRunner<>( toolChestHistorical2.mergeResults( groupByFactoryHistorical2.mergeRunners(DirectQueryProcessingPool.INSTANCE, getRunner2(5)), true ), (QueryToolChest) toolChestHistorical2 ); QueryToolChest<ResultRow, GroupByQuery> toolchestBroker = groupByFactoryBroker.getToolchest(); QueryRunner<ResultRow> finalRunner = new FinalizeResultsQueryRunner<>( toolchestBroker.mergeResults( new QueryRunner<>() { @Override public Sequence<ResultRow> run(QueryPlus<ResultRow> queryPlus, ResponseContext responseContext) { return Sequences .simple( ImmutableList.of( theRunner.run(GroupByQueryRunnerTestHelper.populateResourceId(queryPlus), responseContext), theRunner2.run(GroupByQueryRunnerTestHelper.populateResourceId(queryPlus), responseContext) ) ) .flatMerge(Function.identity(), queryPlus.getQuery().getResultOrdering()); } }, false ), (QueryToolChest) toolchestBroker ); QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(Intervals.utc(1500000000000L, 1900000000000L)) ); DefaultLimitSpec ls = new DefaultLimitSpec( Collections.singletonList( new OrderByColumnSpec("a0", OrderByColumnSpec.Direction.DESCENDING, StringComparators.NUMERIC) ), 5 ); GroupByQuery query = GroupByQuery .builder() .setDataSource("blah") .setQuerySegmentSpec(intervalSpec) .setDimensions( new DefaultDimensionSpec("dimA", "d0", ColumnType.STRING), new DefaultDimensionSpec("dimB", "d1", ColumnType.STRING) ).setAggregatorSpecs(new LongSumAggregatorFactory("a0", "metA")) .setLimitSpec(ls) .setContext(context) .setGranularity(Granularities.ALL) .build(); Sequence<ResultRow> queryResult = finalRunner.run( QueryPlus.wrap(GroupByQueryRunnerTestHelper.populateResourceId(query)), ResponseContext.createEmpty() ); return queryResult.toList(); } private List<QueryRunner<ResultRow>> getRunner1(int qIndexNumber) { List<QueryRunner<ResultRow>> runners = new ArrayList<>(); QueryableIndex index = groupByIndices.get(qIndexNumber); QueryRunner<ResultRow> runner = makeQueryRunner( groupByFactoryHistorical, SegmentId.dummy(index.toString()), new QueryableIndexSegment(index, SegmentId.dummy(index.toString())) ); runners.add(groupByFactoryHistorical.getToolchest().preMergeQueryDecoration(runner)); return runners; } private List<QueryRunner<ResultRow>> getRunner2(int qIndexNumber) { List<QueryRunner<ResultRow>> runners = new ArrayList<>(); QueryableIndex index2 = groupByIndices.get(qIndexNumber); QueryRunner<ResultRow> tooSmallRunner = makeQueryRunner( groupByFactoryHistorical2, SegmentId.dummy(index2.toString()), new QueryableIndexSegment(index2, SegmentId.dummy(index2.toString())) ); runners.add(groupByFactoryHistorical2.getToolchest().preMergeQueryDecoration(tooSmallRunner)); return runners; } public static <T, QueryType extends Query<T>> QueryRunner<T> makeQueryRunner( QueryRunnerFactory<T, QueryType> factory, SegmentId segmentId, Segment adapter ) { return new FinalizeResultsQueryRunner<>( new BySegmentQueryRunner<>(segmentId, adapter.getDataInterval().getStart(), factory.createRunner(adapter)), (QueryToolChest<T, Query<T>>) factory.getToolchest() ); } public static final QueryWatcher NOOP_QUERYWATCHER = (query, future) -> {}; }
apache/hadoop-hdfs
37,923
src/java/org/apache/hadoop/hdfs/DFSInputStream.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 java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.ChecksumException; import org.apache.hadoop.fs.FSInputStream; import org.apache.hadoop.fs.UnresolvedLinkException; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.server.datanode.ReplicaNotFoundException; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.StringUtils; /**************************************************************** * DFSInputStream provides bytes from a named file. It handles * negotiation of the namenode and various datanodes as necessary. ****************************************************************/ @InterfaceAudience.Private public class DFSInputStream extends FSInputStream { private final SocketCache socketCache; private final DFSClient dfsClient; private boolean closed = false; private final String src; private long prefetchSize; private BlockReader blockReader = null; private boolean verifyChecksum; private LocatedBlocks locatedBlocks = null; private long lastBlockBeingWrittenLength = 0; private DatanodeInfo currentNode = null; private LocatedBlock currentLocatedBlock = null; private long pos = 0; private long blockEnd = -1; /** * This variable tracks the number of failures since the start of the * most recent user-facing operation. That is to say, it should be reset * whenever the user makes a call on this stream, and if at any point * during the retry logic, the failure count exceeds a threshold, * the errors will be thrown back to the operation. * * Specifically this counts the number of times the client has gone * back to the namenode to get a new list of block locations, and is * capped at maxBlockAcquireFailures */ private int failures = 0; private int timeWindow = 3000; // wait time window (in msec) if BlockMissingException is caught /* XXX Use of CocurrentHashMap is temp fix. Need to fix * parallel accesses to DFSInputStream (through ptreads) properly */ private ConcurrentHashMap<DatanodeInfo, DatanodeInfo> deadNodes = new ConcurrentHashMap<DatanodeInfo, DatanodeInfo>(); private int buffersize = 1; private byte[] oneByteBuf = new byte[1]; // used for 'int read()' private int nCachedConnRetry; void addToDeadNodes(DatanodeInfo dnInfo) { deadNodes.put(dnInfo, dnInfo); } DFSInputStream(DFSClient dfsClient, String src, int buffersize, boolean verifyChecksum ) throws IOException, UnresolvedLinkException { this.dfsClient = dfsClient; this.verifyChecksum = verifyChecksum; this.buffersize = buffersize; this.src = src; this.socketCache = dfsClient.socketCache; prefetchSize = this.dfsClient.conf.getLong(DFSConfigKeys.DFS_CLIENT_READ_PREFETCH_SIZE_KEY, 10 * dfsClient.defaultBlockSize); timeWindow = this.dfsClient.conf.getInt( DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE, timeWindow); nCachedConnRetry = this.dfsClient.conf.getInt( DFSConfigKeys.DFS_CLIENT_CACHED_CONN_RETRY_KEY, DFSConfigKeys.DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT); openInfo(); } /** * Grab the open-file info from namenode */ synchronized void openInfo() throws IOException, UnresolvedLinkException { LocatedBlocks newInfo = DFSClient.callGetBlockLocations(dfsClient.namenode, src, 0, prefetchSize); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("newInfo = " + newInfo); } if (newInfo == null) { throw new IOException("Cannot open filename " + src); } if (locatedBlocks != null) { Iterator<LocatedBlock> oldIter = locatedBlocks.getLocatedBlocks().iterator(); Iterator<LocatedBlock> newIter = newInfo.getLocatedBlocks().iterator(); while (oldIter.hasNext() && newIter.hasNext()) { if (! oldIter.next().getBlock().equals(newIter.next().getBlock())) { throw new IOException("Blocklist for " + src + " has changed!"); } } } locatedBlocks = newInfo; lastBlockBeingWrittenLength = 0; if (!locatedBlocks.isLastBlockComplete()) { final LocatedBlock last = locatedBlocks.getLastLocatedBlock(); if (last != null) { final long len = readBlockLength(last); last.getBlock().setNumBytes(len); lastBlockBeingWrittenLength = len; } } currentNode = null; } /** Read the block length from one of the datanodes. */ private long readBlockLength(LocatedBlock locatedblock) throws IOException { if (locatedblock == null || locatedblock.getLocations().length == 0) { return 0; } int replicaNotFoundCount = locatedblock.getLocations().length; for(DatanodeInfo datanode : locatedblock.getLocations()) { ClientDatanodeProtocol cdp = null; try { cdp = DFSClient.createClientDatanodeProtocolProxy( datanode, dfsClient.conf, dfsClient.socketTimeout, locatedblock); final long n = cdp.getReplicaVisibleLength(locatedblock.getBlock()); if (n >= 0) { return n; } } catch(IOException ioe) { if (ioe instanceof RemoteException && (((RemoteException) ioe).unwrapRemoteException() instanceof ReplicaNotFoundException)) { // special case : replica might not be on the DN, treat as 0 length replicaNotFoundCount--; } if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Failed to getReplicaVisibleLength from datanode " + datanode + " for block " + locatedblock.getBlock(), ioe); } } finally { if (cdp != null) { RPC.stopProxy(cdp); } } } // Namenode told us about these locations, but none know about the replica // means that we hit the race between pipeline creation start and end. // we require all 3 because some other exception could have happened // on a DN that has it. we want to report that error if (replicaNotFoundCount == 0) { return 0; } throw new IOException("Cannot obtain block length for " + locatedblock); } public synchronized long getFileLength() { return locatedBlocks == null? 0: locatedBlocks.getFileLength() + lastBlockBeingWrittenLength; } /** * Returns the datanode from which the stream is currently reading. */ public DatanodeInfo getCurrentDatanode() { return currentNode; } /** * Returns the block containing the target position. */ synchronized public ExtendedBlock getCurrentBlock() { if (currentLocatedBlock == null){ return null; } return currentLocatedBlock.getBlock(); } /** * Return collection of blocks that has already been located. */ synchronized List<LocatedBlock> getAllBlocks() throws IOException { return getBlockRange(0, getFileLength()); } /** * Get block at the specified position. * Fetch it from the namenode if not cached. * * @param offset * @param updatePosition whether to update current position * @return located block * @throws IOException */ private synchronized LocatedBlock getBlockAt(long offset, boolean updatePosition) throws IOException { assert (locatedBlocks != null) : "locatedBlocks is null"; final LocatedBlock blk; //check offset if (offset < 0 || offset >= getFileLength()) { throw new IOException("offset < 0 || offset > getFileLength(), offset=" + offset + ", updatePosition=" + updatePosition + ", locatedBlocks=" + locatedBlocks); } else if (offset >= locatedBlocks.getFileLength()) { // offset to the portion of the last block, // which is not known to the name-node yet; // getting the last block blk = locatedBlocks.getLastLocatedBlock(); } else { // search cached blocks first int targetBlockIdx = locatedBlocks.findBlock(offset); if (targetBlockIdx < 0) { // block is not cached targetBlockIdx = LocatedBlocks.getInsertIndex(targetBlockIdx); // fetch more blocks LocatedBlocks newBlocks; newBlocks = DFSClient.callGetBlockLocations(dfsClient.namenode, src, offset, prefetchSize); assert (newBlocks != null) : "Could not find target position " + offset; locatedBlocks.insertRange(targetBlockIdx, newBlocks.getLocatedBlocks()); } blk = locatedBlocks.get(targetBlockIdx); } // update current position if (updatePosition) { pos = offset; blockEnd = blk.getStartOffset() + blk.getBlockSize() - 1; currentLocatedBlock = blk; } return blk; } /** Fetch a block from namenode and cache it */ private synchronized void fetchBlockAt(long offset) throws IOException { int targetBlockIdx = locatedBlocks.findBlock(offset); if (targetBlockIdx < 0) { // block is not cached targetBlockIdx = LocatedBlocks.getInsertIndex(targetBlockIdx); } // fetch blocks LocatedBlocks newBlocks; newBlocks = DFSClient.callGetBlockLocations(dfsClient.namenode, src, offset, prefetchSize); if (newBlocks == null) { throw new IOException("Could not find target position " + offset); } locatedBlocks.insertRange(targetBlockIdx, newBlocks.getLocatedBlocks()); } /** * Get blocks in the specified range. * Fetch them from the namenode if not cached. * * @param offset * @param length * @return consequent segment of located blocks * @throws IOException */ private synchronized List<LocatedBlock> getBlockRange(long offset, long length) throws IOException { final List<LocatedBlock> blocks; if (locatedBlocks.isLastBlockComplete()) { blocks = getFinalizedBlockRange(offset, length); } else { final boolean readPastEnd = offset + length > locatedBlocks.getFileLength(); /* if requested length is greater than current file length * then, it could possibly be from the current block being * written to. First get the finalized block range and then * if necessary, get the length of last block being written * to. */ if (readPastEnd) length = locatedBlocks.getFileLength() - offset; blocks = getFinalizedBlockRange(offset, length); /* requested length is greater than what finalized blocks * have. */ if (readPastEnd) blocks.add(locatedBlocks.getLastLocatedBlock()); } return blocks; } /** * Get blocks in the specified range. * Includes only the complete blocks. * Fetch them from the namenode if not cached. */ private synchronized List<LocatedBlock> getFinalizedBlockRange( long offset, long length) throws IOException { assert (locatedBlocks != null) : "locatedBlocks is null"; List<LocatedBlock> blockRange = new ArrayList<LocatedBlock>(); // search cached blocks first int blockIdx = locatedBlocks.findBlock(offset); if (blockIdx < 0) { // block is not cached blockIdx = LocatedBlocks.getInsertIndex(blockIdx); } long remaining = length; long curOff = offset; while(remaining > 0) { LocatedBlock blk = null; if(blockIdx < locatedBlocks.locatedBlockCount()) blk = locatedBlocks.get(blockIdx); if (blk == null || curOff < blk.getStartOffset()) { LocatedBlocks newBlocks; newBlocks = DFSClient.callGetBlockLocations(dfsClient.namenode, src, curOff, remaining); locatedBlocks.insertRange(blockIdx, newBlocks.getLocatedBlocks()); continue; } assert curOff >= blk.getStartOffset() : "Block not found"; blockRange.add(blk); long bytesRead = blk.getStartOffset() + blk.getBlockSize() - curOff; remaining -= bytesRead; curOff += bytesRead; blockIdx++; } return blockRange; } /** * Open a DataInputStream to a DataNode so that it can be read from. * We get block ID and the IDs of the destinations at startup, from the namenode. */ private synchronized DatanodeInfo blockSeekTo(long target) throws IOException { if (target >= getFileLength()) { throw new IOException("Attempted to read past end of file"); } // Will be getting a new BlockReader. if (blockReader != null) { closeBlockReader(blockReader); blockReader = null; } // // Connect to best DataNode for desired Block, with potential offset // DatanodeInfo chosenNode = null; int refetchToken = 1; // only need to get a new access token once while (true) { // // Compute desired block // LocatedBlock targetBlock = getBlockAt(target, true); assert (target==pos) : "Wrong postion " + pos + " expect " + target; long offsetIntoBlock = target - targetBlock.getStartOffset(); DNAddrPair retval = chooseDataNode(targetBlock); chosenNode = retval.info; InetSocketAddress targetAddr = retval.addr; try { ExtendedBlock blk = targetBlock.getBlock(); Token<BlockTokenIdentifier> accessToken = targetBlock.getBlockToken(); blockReader = getBlockReader( targetAddr, src, blk, accessToken, offsetIntoBlock, blk.getNumBytes() - offsetIntoBlock, buffersize, verifyChecksum, dfsClient.clientName); return chosenNode; } catch (IOException ex) { if (ex instanceof InvalidBlockTokenException && refetchToken > 0) { DFSClient.LOG.info("Will fetch a new access token and retry, " + "access token was invalid when connecting to " + targetAddr + " : " + ex); /* * Get a new access token and retry. Retry is needed in 2 cases. 1) * When both NN and DN re-started while DFSClient holding a cached * access token. 2) In the case that NN fails to update its * access key at pre-set interval (by a wide margin) and * subsequently restarts. In this case, DN re-registers itself with * NN and receives a new access key, but DN will delete the old * access key from its memory since it's considered expired based on * the estimated expiration date. */ refetchToken--; fetchBlockAt(target); } else { DFSClient.LOG.warn("Failed to connect to " + targetAddr + ", add to deadNodes and continue " + ex); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Connection failure ", ex); } // Put chosen node into dead list, continue addToDeadNodes(chosenNode); } } } } /** * Close it down! */ @Override public synchronized void close() throws IOException { if (closed) { return; } dfsClient.checkOpen(); if (blockReader != null) { closeBlockReader(blockReader); blockReader = null; } super.close(); closed = true; } @Override public synchronized int read() throws IOException { int ret = read( oneByteBuf, 0, 1 ); return ( ret <= 0 ) ? -1 : (oneByteBuf[0] & 0xff); } /* This is a used by regular read() and handles ChecksumExceptions. * name readBuffer() is chosen to imply similarity to readBuffer() in * ChecksumFileSystem */ private synchronized int readBuffer(byte buf[], int off, int len, Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap) throws IOException { IOException ioe; /* we retry current node only once. So this is set to true only here. * Intention is to handle one common case of an error that is not a * failure on datanode or client : when DataNode closes the connection * since client is idle. If there are other cases of "non-errors" then * then a datanode might be retried by setting this to true again. */ boolean retryCurrentNode = true; while (true) { // retry as many times as seekToNewSource allows. try { return blockReader.read(buf, off, len); } catch ( ChecksumException ce ) { DFSClient.LOG.warn("Found Checksum error for " + getCurrentBlock() + " from " + currentNode.getName() + " at " + ce.getPos()); ioe = ce; retryCurrentNode = false; // we want to remember which block replicas we have tried addIntoCorruptedBlockMap(getCurrentBlock(), currentNode, corruptedBlockMap); } catch ( IOException e ) { if (!retryCurrentNode) { DFSClient.LOG.warn("Exception while reading from " + getCurrentBlock() + " of " + src + " from " + currentNode + ": " + StringUtils.stringifyException(e)); } ioe = e; } boolean sourceFound = false; if (retryCurrentNode) { /* possibly retry the same node so that transient errors don't * result in application level failures (e.g. Datanode could have * closed the connection because the client is idle for too long). */ sourceFound = seekToBlockSource(pos); } else { addToDeadNodes(currentNode); sourceFound = seekToNewSource(pos); } if (!sourceFound) { throw ioe; } retryCurrentNode = false; } } /** * Read the entire buffer. */ @Override public synchronized int read(byte buf[], int off, int len) throws IOException { dfsClient.checkOpen(); if (closed) { throw new IOException("Stream closed"); } Map<ExtendedBlock,Set<DatanodeInfo>> corruptedBlockMap = new HashMap<ExtendedBlock, Set<DatanodeInfo>>(); failures = 0; if (pos < getFileLength()) { int retries = 2; while (retries > 0) { try { if (pos > blockEnd) { currentNode = blockSeekTo(pos); } int realLen = (int) Math.min((long) len, (blockEnd - pos + 1L)); int result = readBuffer(buf, off, realLen, corruptedBlockMap); if (result >= 0) { pos += result; } else { // got a EOS from reader though we expect more data on it. throw new IOException("Unexpected EOS from the reader"); } if (dfsClient.stats != null && result != -1) { dfsClient.stats.incrementBytesRead(result); } return result; } catch (ChecksumException ce) { throw ce; } catch (IOException e) { if (retries == 1) { DFSClient.LOG.warn("DFS Read: " + StringUtils.stringifyException(e)); } blockEnd = -1; if (currentNode != null) { addToDeadNodes(currentNode); } if (--retries == 0) { throw e; } } finally { // Check if need to report block replicas corruption either read // was successful or ChecksumException occured. reportCheckSumFailure(corruptedBlockMap, currentLocatedBlock.getLocations().length); } } } return -1; } /** * Add corrupted block replica into map. * @param corruptedBlockMap */ private void addIntoCorruptedBlockMap(ExtendedBlock blk, DatanodeInfo node, Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap) { Set<DatanodeInfo> dnSet = null; if((corruptedBlockMap.containsKey(blk))) { dnSet = corruptedBlockMap.get(blk); }else { dnSet = new HashSet<DatanodeInfo>(); } if (!dnSet.contains(node)) { dnSet.add(node); corruptedBlockMap.put(blk, dnSet); } } private DNAddrPair chooseDataNode(LocatedBlock block) throws IOException { while (true) { DatanodeInfo[] nodes = block.getLocations(); try { DatanodeInfo chosenNode = bestNode(nodes, deadNodes); InetSocketAddress targetAddr = NetUtils.createSocketAddr(chosenNode.getName()); return new DNAddrPair(chosenNode, targetAddr); } catch (IOException ie) { String blockInfo = block.getBlock() + " file=" + src; if (failures >= dfsClient.getMaxBlockAcquireFailures()) { throw new BlockMissingException(src, "Could not obtain block: " + blockInfo, block.getStartOffset()); } if (nodes == null || nodes.length == 0) { DFSClient.LOG.info("No node available for block: " + blockInfo); } DFSClient.LOG.info("Could not obtain block " + block.getBlock() + " from any node: " + ie + ". Will get new block locations from namenode and retry..."); try { // Introducing a random factor to the wait time before another retry. // The wait time is dependent on # of failures and a random factor. // At the first time of getting a BlockMissingException, the wait time // is a random number between 0..3000 ms. If the first retry // still fails, we will wait 3000 ms grace period before the 2nd retry. // Also at the second retry, the waiting window is expanded to 6000 ms // alleviating the request rate from the server. Similarly the 3rd retry // will wait 6000ms grace period before retry and the waiting window is // expanded to 9000ms. double waitTime = timeWindow * failures + // grace period for the last round of attempt timeWindow * (failures + 1) * dfsClient.r.nextDouble(); // expanding time window for each failure DFSClient.LOG.warn("DFS chooseDataNode: got # " + (failures + 1) + " IOException, will wait for " + waitTime + " msec."); Thread.sleep((long)waitTime); } catch (InterruptedException iex) { } deadNodes.clear(); //2nd option is to remove only nodes[blockId] openInfo(); block = getBlockAt(block.getStartOffset(), false); failures++; continue; } } } private void fetchBlockByteRange(LocatedBlock block, long start, long end, byte[] buf, int offset, Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap) throws IOException { // // Connect to best DataNode for desired Block, with potential offset // int refetchToken = 1; // only need to get a new access token once while (true) { // cached block locations may have been updated by chooseDataNode() // or fetchBlockAt(). Always get the latest list of locations at the // start of the loop. block = getBlockAt(block.getStartOffset(), false); DNAddrPair retval = chooseDataNode(block); DatanodeInfo chosenNode = retval.info; InetSocketAddress targetAddr = retval.addr; BlockReader reader = null; try { Token<BlockTokenIdentifier> blockToken = block.getBlockToken(); int len = (int) (end - start + 1); reader = getBlockReader(targetAddr, src, block.getBlock(), blockToken, start, len, buffersize, verifyChecksum, dfsClient.clientName); int nread = reader.readAll(buf, offset, len); if (nread != len) { throw new IOException("truncated return from reader.read(): " + "excpected " + len + ", got " + nread); } return; } catch (ChecksumException e) { DFSClient.LOG.warn("fetchBlockByteRange(). Got a checksum exception for " + src + " at " + block.getBlock() + ":" + e.getPos() + " from " + chosenNode.getName()); // we want to remember what we have tried addIntoCorruptedBlockMap(block.getBlock(), chosenNode, corruptedBlockMap); } catch (IOException e) { if (e instanceof InvalidBlockTokenException && refetchToken > 0) { DFSClient.LOG.info("Will get a new access token and retry, " + "access token was invalid when connecting to " + targetAddr + " : " + e); refetchToken--; fetchBlockAt(block.getStartOffset()); continue; } else { DFSClient.LOG.warn("Failed to connect to " + targetAddr + " for file " + src + " for block " + block.getBlock() + ":" + e); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Connection failure ", e); } } } finally { if (reader != null) { closeBlockReader(reader); } } // Put chosen node into dead list, continue addToDeadNodes(chosenNode); } } /** * Close the given BlockReader and cache its socket. */ private void closeBlockReader(BlockReader reader) throws IOException { if (reader.hasSentStatusCode()) { Socket oldSock = reader.takeSocket(); socketCache.put(oldSock); } reader.close(); } /** * Retrieve a BlockReader suitable for reading. * This method will reuse the cached connection to the DN if appropriate. * Otherwise, it will create a new connection. * * @param dnAddr Address of the datanode * @param file File location * @param block The Block object * @param blockToken The access token for security * @param startOffset The read offset, relative to block head * @param len The number of bytes to read * @param bufferSize The IO buffer size (not the client buffer size) * @param verifyChecksum Whether to verify checksum * @param clientName Client name * @return New BlockReader instance */ protected BlockReader getBlockReader(InetSocketAddress dnAddr, String file, ExtendedBlock block, Token<BlockTokenIdentifier> blockToken, long startOffset, long len, int bufferSize, boolean verifyChecksum, String clientName) throws IOException { IOException err = null; boolean fromCache = true; // Allow retry since there is no way of knowing whether the cached socket // is good until we actually use it. for (int retries = 0; retries <= nCachedConnRetry && fromCache; ++retries) { Socket sock = socketCache.get(dnAddr); if (sock == null) { fromCache = false; sock = dfsClient.socketFactory.createSocket(); // TCP_NODELAY is crucial here because of bad interactions between // Nagle's Algorithm and Delayed ACKs. With connection keepalive // between the client and DN, the conversation looks like: // 1. Client -> DN: Read block X // 2. DN -> Client: data for block X // 3. Client -> DN: Status OK (successful read) // 4. Client -> DN: Read block Y // The fact that step #3 and #4 are both in the client->DN direction // triggers Nagling. If the DN is using delayed ACKs, this results // in a delay of 40ms or more. // // TCP_NODELAY disables nagling and thus avoids this performance // disaster. sock.setTcpNoDelay(true); NetUtils.connect(sock, dnAddr, dfsClient.socketTimeout); sock.setSoTimeout(dfsClient.socketTimeout); } try { // The OP_READ_BLOCK request is sent as we make the BlockReader BlockReader reader = BlockReader.newBlockReader(sock, file, block, blockToken, startOffset, len, bufferSize, verifyChecksum, clientName); return reader; } catch (IOException ex) { // Our socket is no good. DFSClient.LOG.debug("Error making BlockReader. Closing stale " + sock, ex); sock.close(); err = ex; } } throw err; } /** * Read bytes starting from the specified position. * * @param position start read from this position * @param buffer read buffer * @param offset offset into buffer * @param length number of bytes to read * * @return actual number of bytes read */ @Override public int read(long position, byte[] buffer, int offset, int length) throws IOException { // sanity checks dfsClient.checkOpen(); if (closed) { throw new IOException("Stream closed"); } failures = 0; long filelen = getFileLength(); if ((position < 0) || (position >= filelen)) { return -1; } int realLen = length; if ((position + length) > filelen) { realLen = (int)(filelen - position); } // determine the block and byte range within the block // corresponding to position and realLen List<LocatedBlock> blockRange = getBlockRange(position, realLen); int remaining = realLen; Map<ExtendedBlock,Set<DatanodeInfo>> corruptedBlockMap = new HashMap<ExtendedBlock, Set<DatanodeInfo>>(); for (LocatedBlock blk : blockRange) { long targetStart = position - blk.getStartOffset(); long bytesToRead = Math.min(remaining, blk.getBlockSize() - targetStart); try { fetchBlockByteRange(blk, targetStart, targetStart + bytesToRead - 1, buffer, offset, corruptedBlockMap); } finally { // Check and report if any block replicas are corrupted. // BlockMissingException may be caught if all block replicas are // corrupted. reportCheckSumFailure(corruptedBlockMap, blk.getLocations().length); } remaining -= bytesToRead; position += bytesToRead; offset += bytesToRead; } assert remaining == 0 : "Wrong number of bytes read."; if (dfsClient.stats != null) { dfsClient.stats.incrementBytesRead(realLen); } return realLen; } /** * DFSInputStream reports checksum failure. * Case I : client has tried multiple data nodes and at least one of the * attempts has succeeded. We report the other failures as corrupted block to * namenode. * Case II: client has tried out all data nodes, but all failed. We * only report if the total number of replica is 1. We do not * report otherwise since this maybe due to the client is a handicapped client * (who can not read). * @param corruptedBlockMap, map of corrupted blocks * @param dataNodeCount, number of data nodes who contains the block replicas */ private void reportCheckSumFailure( Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap, int dataNodeCount) { if (corruptedBlockMap.isEmpty()) { return; } Iterator<Entry<ExtendedBlock, Set<DatanodeInfo>>> it = corruptedBlockMap .entrySet().iterator(); Entry<ExtendedBlock, Set<DatanodeInfo>> entry = it.next(); ExtendedBlock blk = entry.getKey(); Set<DatanodeInfo> dnSet = entry.getValue(); if (((dnSet.size() < dataNodeCount) && (dnSet.size() > 0)) || ((dataNodeCount == 1) && (dnSet.size() == dataNodeCount))) { DatanodeInfo[] locs = new DatanodeInfo[dnSet.size()]; int i = 0; for (DatanodeInfo dn:dnSet) { locs[i++] = dn; } LocatedBlock [] lblocks = { new LocatedBlock(blk, locs) }; dfsClient.reportChecksumFailure(src, lblocks); } corruptedBlockMap.clear(); } @Override public long skip(long n) throws IOException { if ( n > 0 ) { long curPos = getPos(); long fileLen = getFileLength(); if( n+curPos > fileLen ) { n = fileLen - curPos; } seek(curPos+n); return n; } return n < 0 ? -1 : 0; } /** * Seek to a new arbitrary location */ @Override public synchronized void seek(long targetPos) throws IOException { if (targetPos > getFileLength()) { throw new IOException("Cannot seek after EOF"); } if (closed) { throw new IOException("Stream is closed!"); } boolean done = false; if (pos <= targetPos && targetPos <= blockEnd) { // // If this seek is to a positive position in the current // block, and this piece of data might already be lying in // the TCP buffer, then just eat up the intervening data. // int diff = (int)(targetPos - pos); if (diff <= DFSClient.TCP_WINDOW_SIZE) { try { pos += blockReader.skip(diff); if (pos == targetPos) { done = true; } } catch (IOException e) {//make following read to retry if(DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Exception while seek to " + targetPos + " from " + getCurrentBlock() + " of " + src + " from " + currentNode + ": " + StringUtils.stringifyException(e)); } } } } if (!done) { pos = targetPos; blockEnd = -1; } } /** * Same as {@link #seekToNewSource(long)} except that it does not exclude * the current datanode and might connect to the same node. */ private synchronized boolean seekToBlockSource(long targetPos) throws IOException { currentNode = blockSeekTo(targetPos); return true; } /** * Seek to given position on a node other than the current node. If * a node other than the current node is found, then returns true. * If another node could not be found, then returns false. */ @Override public synchronized boolean seekToNewSource(long targetPos) throws IOException { boolean markedDead = deadNodes.containsKey(currentNode); addToDeadNodes(currentNode); DatanodeInfo oldNode = currentNode; DatanodeInfo newNode = blockSeekTo(targetPos); if (!markedDead) { /* remove it from deadNodes. blockSeekTo could have cleared * deadNodes and added currentNode again. Thats ok. */ deadNodes.remove(oldNode); } if (!oldNode.getStorageID().equals(newNode.getStorageID())) { currentNode = newNode; return true; } else { return false; } } /** */ @Override public synchronized long getPos() throws IOException { return pos; } /** Return the size of the remaining available bytes * if the size is less than or equal to {@link Integer#MAX_VALUE}, * otherwise, return {@link Integer#MAX_VALUE}. */ @Override public synchronized int available() throws IOException { if (closed) { throw new IOException("Stream closed"); } final long remaining = getFileLength() - pos; return remaining <= Integer.MAX_VALUE? (int)remaining: Integer.MAX_VALUE; } /** * We definitely don't support marks */ @Override public boolean markSupported() { return false; } @Override public void mark(int readLimit) { } @Override public void reset() throws IOException { throw new IOException("Mark/reset not supported"); } /** * Pick the best node from which to stream the data. * Entries in <i>nodes</i> are already in the priority order */ static DatanodeInfo bestNode(DatanodeInfo nodes[], AbstractMap<DatanodeInfo, DatanodeInfo> deadNodes) throws IOException { if (nodes != null) { for (int i = 0; i < nodes.length; i++) { if (!deadNodes.containsKey(nodes[i])) { return nodes[i]; } } } throw new IOException("No live nodes contain current block"); } /** Utility class to encapsulate data node info and its ip address. */ static class DNAddrPair { DatanodeInfo info; InetSocketAddress addr; DNAddrPair(DatanodeInfo info, InetSocketAddress addr) { this.info = info; this.addr = addr; } } }
apache/harmony
37,916
classlib/modules/print/src/main/java/common/org/apache/harmony/x/print/cups/CUPSClient.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. */ /** * @author Igor A. Pyankov */ package org.apache.harmony.x.print.cups; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilePermission; import java.io.InputStream; import java.lang.reflect.Array; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Locale; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.PrintException; import javax.print.attribute.Attribute; import javax.print.attribute.AttributeSet; import javax.print.attribute.AttributeSetUtilities; import javax.print.attribute.DocAttributeSet; import javax.print.attribute.HashAttributeSet; import javax.print.attribute.HashPrintServiceAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.PrintServiceAttribute; import javax.print.attribute.PrintServiceAttributeSet; import javax.print.attribute.standard.Destination; import javax.print.attribute.standard.DocumentName; import javax.print.attribute.standard.JobName; import javax.print.attribute.standard.Media; import javax.print.attribute.standard.RequestingUserName; import org.apache.harmony.x.print.PrintClient; import org.apache.harmony.x.print.ipp.IppAttribute; import org.apache.harmony.x.print.ipp.IppAttributeGroup; import org.apache.harmony.x.print.ipp.IppAttributeGroupSet; import org.apache.harmony.x.print.ipp.IppDocument; import org.apache.harmony.x.print.ipp.IppPrinter; import org.apache.harmony.x.print.ipp.IppResponse; import org.apache.harmony.x.print.ipp.util.Ipp2Java; /* * CUPSClient is a print client based on CUPS protocol. * (see Common UNIX Printing System, http://www.cups.org/) * * The CUPS itself extends IPP protocol * (see Internet Printing Protocol, http://www.pwg.org/ipp/index.html) * * So, this class supports as CUPS as IPP print servers * * The class uses special IPP package org.apache.harmony.x.print.ipp for * ipp/cups specific operations. * * CUPSClient implements PrintClient interface, therefore * see PrintClient.java for more information. * * */ class CUPSClient implements PrintClient { // for debug private static int verbose = 0; private IppPrinter printer; private URI printeruri; private PrintServiceAttributeSet attributeset; private DocFlavor[] supportedFlavors = null; CUPSClient(String name) throws PrintException { try { this.printeruri = new URI(name); this.printer = new IppPrinter(printeruri); this.attributeset = new HashPrintServiceAttributeSet(); } catch (Exception e) { throw new PrintException(e); } } /* * SPECIAL - supportedFlavors is global for performance * but it can be set local for dynamic * * @org.apache.harmony.x.print.PrintClient#getSupportedDocFlavors() */ public DocFlavor[] getSupportedDocFlavors() { if (supportedFlavors == null) { ArrayList df = new ArrayList(); try { String[] mimetypes = new String[ALLDOCFLAVORS.length]; String[] validmimes; for (int i = 0, ii = ALLDOCFLAVORS.length; i < ii; i++) { mimetypes[i] = ALLDOCFLAVORS[i].getMimeType(); } validmimes = printer.requestGetSupportedMimeTypes(mimetypes); for (int i = 0, ii = ALLDOCFLAVORS.length; i < ii; i++) { if (validmimes[i] != null) { if (validmimes[i].equals("application/ps")) { /* * SPECIAL processing application/ps */ df.add(ipp2java(ALLDOCFLAVORS[i])); } else { df.add(ALLDOCFLAVORS[i]); } } } } catch (Exception e) { // IGNORE exception e.printStackTrace(); } supportedFlavors = (df.size() == 0 ? new DocFlavor[] { DocFlavor.INPUT_STREAM.AUTOSENSE } : (DocFlavor[]) df.toArray(new DocFlavor[0])); } return supportedFlavors; } /* * @see org.apache.harmony.x.print.PrintClient#getAttributes() */ public PrintServiceAttributeSet getAttributes() { synchronized (this) { try { IppResponse response; IppAttributeGroup agroup; IppAttribute attr; Object[] attrx = new Object[0]; response = printer.requestPrinterDescriptionAttributes(); agroup = response .getGroup(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES); if (agroup != null) { attributeset.clear(); for (int i = 0, ii = agroup.size(); i < ii; i++) { attr = (IppAttribute) agroup.get(i); attrx = Ipp2Java.getJavaByIpp(attr); for (int j = 0, jj = attrx.length; j < jj; j++) { if (attrx[j] instanceof PrintServiceAttribute) { attributeset.add((Attribute) attrx[j]); } } } } } catch (Exception e) { // IGNORE exception e.printStackTrace(); } } return AttributeSetUtilities.unmodifiableView(attributeset); } /* * @see org.apache.harmony.x.PrintClient#getSupportedAttributeCategories() */ public Class[] getSupportedAttributeCategories() { ArrayList clazz = new ArrayList(); try { IppResponse response = printer.requestPrinterAttributes(); IppAttributeGroup agroup = response .getGroup(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES); String aname; Class claz; IppAttribute attr; if (agroup != null) { for (int i = 0, ii = agroup.size(); i < ii; i++) { attr = (IppAttribute) agroup.get(i); aname = new String(attr.getName()); if (aname.indexOf("-supported") > 0) { claz = Ipp2Java.getClassByIppAttributeName(aname .substring(0, aname.indexOf("-supported"))); if (claz != null) { clazz.add(claz); } } } } // SPECIAL attributes processing getSupportedAttributeCategoriesEx(clazz); } catch (Exception e) { // IGNORE exception // e.printStackTrace(); } return (clazz.size() == 0 ? new Class[0] : (Class[]) clazz .toArray(new Class[0])); } private void getSupportedAttributeCategoriesEx(ArrayList clazz) { if (!clazz.contains(Destination.class)) { clazz.add(Destination.class); } if (!clazz.contains(RequestingUserName.class)) { clazz.add(RequestingUserName.class); } if (!clazz.contains(JobName.class)) { clazz.add(JobName.class); } if (!clazz.contains(DocumentName.class)) { clazz.add(DocumentName.class); } } /* * @see org.apache.harmony.x.print.PrintClient#getDefaultAttributeValue(java.lang.Class) */ public Object getDefaultAttributeValue(Class category) { if (category == null) { throw new NullPointerException("Argument is null"); } if (!(Attribute.class.isAssignableFrom(category))) { throw new IllegalArgumentException( "Argument must implement interface Attribute"); } Object defval[] = null; // SPECIAL attributes processing defval = getDefaultAttributeValueEx(category); if (defval != null) { if (defval.length == 0) { return null; } return defval[0]; } if (Media.class.isAssignableFrom(category)) { category = Media.class; } try { IppResponse response = printer.requestPrinterAttributes(); IppAttributeGroup agroup = response .getGroup(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES); IppAttribute attr; String aname; int andex; if (agroup != null) { aname = Ipp2Java.getIppAttributeNameByClass(category); if (aname != null) { if (aname.endsWith("-supported")) { aname = aname.substring(0, aname.indexOf("-supported")); } if (aname.endsWith("-default")) { aname = aname.substring(0, aname.indexOf("-default")); } andex = agroup.findAttribute(aname + "-default"); if (andex >= 0) { attr = (IppAttribute) agroup.get(andex); defval = Ipp2Java.getJavaByIpp(attr); } } } } catch (Exception e) { // IGNORE exception e.printStackTrace(); } return (defval != null && defval.length > 0 ? defval[0] : null); } /* * If attribute was processed - return Object[1] * Else - return null */ private Object[] getDefaultAttributeValueEx(Class category) { if (Destination.class.isAssignableFrom(category)) { return new Object[0]; } else if (RequestingUserName.class.isAssignableFrom(category)) { return new Object[] { new RequestingUserName( (String) AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("user.name"); } }), Locale.US) }; } else if (JobName.class.isAssignableFrom(category)) { return new Object[] { new JobName("Java print job", Locale.US) }; } else if (DocumentName.class.isAssignableFrom(category)) { return new Object[] { new DocumentName("Java print document", Locale.US) }; } return null; } /* * @see org.apache.harmony.x.print.PrintClient#isAttributeValueSupported(javax.print.attribute.Attribute, * javax.print.DocFlavor, javax.print.attribute.AttributeSet) */ public boolean isAttributeValueSupported(Attribute attribute, DocFlavor flavor, AttributeSet attributes) { // verify parameters if (attribute == null) { throw new NullPointerException("Argument is null"); } if (flavor != null && !isDocFlavorSupported(flavor)) { throw new IllegalArgumentException("DocFlavor '" + flavor + "' is not supported by the print service"); } // SPECIAL attributes processing boolean[] supportedEx = isAttributeValueSupportedEx(attribute, flavor); if (supportedEx != null) { return supportedEx[0]; } boolean supported = false; try { IppDocument document; IppResponse response; IppAttributeGroup agroup; IppAttributeGroupSet agroupset; Attribute[] attrs; String mime = null; String aname; aname = Ipp2Java.getIppAttributeNameByClass(attribute.getClass(), -1); if (aname == null) { return false; } if (flavor == null) { mime = "application/octet-stream"; } else { mime = java2ipp(flavor).getMimeType(); } if (attributes == null || attributes.isEmpty()) { document = new IppDocument("Qwerty", mime, ""); agroupset = new IppAttributeGroupSet(); agroupset.setAttribute(aname, Ipp2Java.getIppByJava(attribute)); response = printer.requestValidateJob(aname, document, agroupset); agroup = response .getGroup(IppAttributeGroup.TAG_UNSUPPORTED_ATTRIBUTES); if (agroup == null) { supported = true; } else if (agroup != null && agroup.findAttribute(aname) < 0) { supported = true; } } else { document = new IppDocument("Qwerty", mime, ""); agroupset = new IppAttributeGroupSet(); agroupset.setAttribute(aname, Ipp2Java.getIppByJava(attribute)); attrs = attributes.toArray(); for (int i = 0, ii = attrs.length; i < ii; i++) { agroupset.setAttribute(Ipp2Java.getIppAttributeNameByClass( attrs[i].getClass(), -1), Ipp2Java .getIppByJava(attrs[i])); } response = printer.requestValidateJob(aname, document, agroupset); agroup = response .getGroup(IppAttributeGroup.TAG_UNSUPPORTED_ATTRIBUTES); if (agroup == null) { supported = true; } else if (agroup != null && agroup.findAttribute(aname) < 0) { supported = true; } } } catch (Exception e) { e.printStackTrace(); return false; } return supported; } /* * If attribute was processed - return boolean[1] * Else return null */ private boolean[] isAttributeValueSupportedEx(Attribute avalue, DocFlavor flavor) { if (Destination.class.isAssignableFrom(avalue.getCategory())) { String ms = (flavor != null ? flavor.getMediaSubtype() : ""); Class cls = (flavor != null ? flavor.getClass() : null); if (ms.equalsIgnoreCase("gif") || ms.equalsIgnoreCase("jpeg") || ms.equalsIgnoreCase("png") || ms.equalsIgnoreCase("postscript") || flavor == null || cls == DocFlavor.SERVICE_FORMATTED.class) { if (!canPrintToFile()) { return new boolean[] { false }; } URI uri = ((Destination) avalue).getURI(); try { File file = new File(uri); if (file.isFile()) { if (file.canWrite()) { return new boolean[] { true }; } return new boolean[] { false }; } String path = file.getParent(); File parent = new File(path); if (parent.isDirectory()) { if (parent.canWrite()) { return new boolean[] { true }; } return new boolean[] { false }; } } catch (Exception e) { return new boolean[] { false }; } } } return null; } /* * @see org.apache.harmony.x.print.PrintClient#getSupportedAttributeValues(java.lang.Class, * javax.print.DocFlavor, javax.print.attribute.AttributeSet) */ public Object getSupportedAttributeValues(Class category, DocFlavor flavor, AttributeSet attributes) { if (category == null) { throw new NullPointerException("Argument is null"); } if (!(Attribute.class.isAssignableFrom(category))) { throw new IllegalArgumentException( "Argument must implement interface Attribute"); } if (flavor != null && !isDocFlavorSupported(flavor)) { throw new IllegalArgumentException("DocFlavor '" + flavor + "' is not supported by the print service"); } Object vals = null; // SPECIAL attributes processing vals = getSupportedAttributeValuesEx(category, flavor); if (vals != null) { if (((Object[]) vals).length == 0) { return null; } return ((Object[]) vals)[0]; } // General attributes try { String aname = Ipp2Java.getIppAttributeNameByClass(category, 0) + "-supported"; doVerbose(2, "CUPSClient.java: getSupportedAttributeValues(): ipp attribute: " + aname); IppResponse response = printer.requestPrinterAttributes(aname, (flavor == null ? null : java2ipp(flavor).getMimeType())); doVerbose(2, "CUPSClient.java: getSupportedAttributeValues(): response: " + response.toString()); IppAttributeGroup agroup = response .getGroup(IppAttributeGroup.TAG_GET_PRINTER_ATTRIBUTES); doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): agroup: " + agroup.toString()); if (agroup != null) { int aind = agroup.findAttribute(aname); if (aind >= 0) { IppAttribute attr = (IppAttribute) agroup.get(aind); vals = Ipp2Java.getJavaByIpp(attr); } } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 1"); // Make right type/value for return if (vals != null && vals.getClass().isArray()) { Object[] ara = (Object[]) vals; if (ara.length == 1 && ara[0].getClass() != category) { vals = ara[0]; } } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 2"); if (vals != null && vals.getClass().isArray()) { int asize = ((Object[]) vals).length; if (asize > 0) { Class c = ((Object[]) vals)[0].getClass(); /* SPECIAL case for Media* attributes * * Special case for Media* attributes. * vals[] contains all type of Media classes * So, c must be Media type, not a[0] type */ if (Media.class.isAssignableFrom(c)) { c = Media.class; } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 3"); Object[] a = (Object[]) Array.newInstance(c, asize); System.arraycopy(vals, 0, a, 0, a.length); vals = a; } else { vals = null; } } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 4"); if (vals != null && vals.getClass().isArray()) { for (int i = 0, ii = ((Attribute[]) vals).length; i < ii; i++) { if (!isAttributeValueSupported(((Attribute[]) vals)[i], flavor, attributes)) { ((Attribute[]) vals)[i] = null; } } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 5"); int newvalslength = 0; for (int i = 0, ii = ((Attribute[]) vals).length; i < ii; i++) { if (((Attribute[]) vals)[i] != null) { newvalslength++; } } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 6"); if (newvalslength != ((Attribute[]) vals).length) { Object[] newvals = new Object[newvalslength]; for (int j = 0, i = 0, ii = ((Attribute[]) vals).length; i < ii; i++) { if (((Attribute[]) vals)[i] != null) { newvals[j++] = ((Attribute[]) vals)[i]; } } vals = newvals; } } else if (vals != null) { if (!isAttributeValueSupported((Attribute) vals, flavor, attributes)) { vals = null; } } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 7"); return vals; } catch (Exception e) { // IGNORE exception e.printStackTrace(); } doVerbose(1, "CUPSClient.java: getSupportedAttributeValues(): 8"); return null; } /* * If category processed - return non-null value */ private Object[] getSupportedAttributeValuesEx(Class category, DocFlavor flavor) { if (Destination.class.isAssignableFrom(category)) { String ms = flavor.getMediaSubtype(); if (ms.equalsIgnoreCase("gif") || ms.equalsIgnoreCase("jpeg") || ms.equalsIgnoreCase("png") || ms.equalsIgnoreCase("postscript") || flavor.getClass() == DocFlavor.SERVICE_FORMATTED.class) { try { return new Object[] { new Destination(new URI( "file:///foo/bar")) }; } catch (URISyntaxException e) { // return empty array - values are not supported return new Object[0]; } } } else if (RequestingUserName.class.isAssignableFrom(category)) { return new Object[] { new RequestingUserName("I.A.Muser", Locale.US) }; } else if (JobName.class.isAssignableFrom(category)) { return new Object[] { new JobName("Foo print job", Locale.US) }; } else if (DocumentName.class.isAssignableFrom(category)) { return new Object[] { new DocumentName("Foo document", Locale.US) }; } return null; } /* * @see org.apache.harmony.x.print.PrintClient#print(javax.print.Doc, * javax.print.attribute.PrintRequestAttributeSet) */ public void print(Doc doc, PrintRequestAttributeSet attributes) throws PrintException { synchronized (this) { doVerbose(1, "Print " + doc.toString()); try { DocFlavor df = doc.getDocFlavor(); if (!(df instanceof DocFlavor.INPUT_STREAM || df instanceof DocFlavor.BYTE_ARRAY || df instanceof DocFlavor.CHAR_ARRAY || df instanceof DocFlavor.STRING || df instanceof DocFlavor.READER || df instanceof DocFlavor.URL)) { throw new PrintException("Doc flavor " + df.getRepresentationClassName() + " is not supported yet"); } HashAttributeSet as = new HashAttributeSet(); DocAttributeSet das; das = doc.getAttributes(); // construct attributes if (das != null) { as.addAll(das); } if (attributes != null) { as.addAll(attributes); } as.addAll(attributeset); // print if (as.containsKey(Destination.class)) { print2destination(doc, (Destination) as .get(Destination.class)); } else { printsimple(doc, as); } } catch (PrintException e) { throw e; } catch (Exception e) { throw new PrintException(e); } } } /* * printing to Destination */ private void print2destination(Doc doc, Destination destination) throws PrintException { try { DataOutputStream bw = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(new File( destination.getURI())))); if (doc != null) { if (doc.getDocFlavor() instanceof DocFlavor.INPUT_STREAM) { InputStream stream = (InputStream) doc.getPrintData(); byte[] buf = new byte[1024 * 8]; int count = 0; while ((count = stream.read(buf, 0, buf.length)) != -1) { bw.write(buf, 0, count); } stream.close(); } else if (doc.getDocFlavor() instanceof DocFlavor.URL) { BufferedInputStream stream = new BufferedInputStream( ((URL) doc.getPrintData()).openStream()); byte[] buf = new byte[1024 * 8]; int count = 0; while ((count = stream.read(buf, 0, buf.length)) != -1) { if (count > 0) { bw.write(buf, 0, count); } } stream.close(); } else if (doc.getDocFlavor() instanceof DocFlavor.BYTE_ARRAY) { InputStream stream = new ByteArrayInputStream((byte[]) doc .getPrintData()); byte[] buf = new byte[1024 * 8]; int count = 0; while ((count = stream.read(buf, 0, buf.length)) != -1) { bw.write(buf, 0, count); } stream.close(); } else if (doc.getDocFlavor() instanceof DocFlavor.SERVICE_FORMATTED) { // TODO - print DocFlavor.SERVICE_FORMATTED } } bw.flush(); bw.close(); } catch (Exception e) { throw new PrintException(e); } } /* * request IppPrinter printer to print document */ private void printsimple(Doc doc, HashAttributeSet as) throws PrintException { IppDocument document; IppResponse response; IppAttributeGroupSet agroupset; Attribute[] attrs; DocFlavor df = doc.getDocFlavor(); String docname = doc.toString(); try { document = new IppDocument(docname, java2ipp(df).getMimeType(), doc .getPrintData()); agroupset = new IppAttributeGroupSet(); attrs = as.toArray(); for (int i = 0, ii = attrs.length; i < ii; i++) { agroupset.setAttribute(Ipp2Java.getIppAttributeNameByClass( attrs[i].getClass(), -1), Ipp2Java .getIppByJava(attrs[i])); } document.setAgroups(agroupset); doVerbose(1, "Validating print job..."); response = printer.requestValidateJob(docname, document, agroupset); doVerbose(1, response.toString()); checkResponseIsZero(response, "IPP Validate Job: \n"); doVerbose(1, "Validate OK"); doVerbose(1, "Printing " + docname + "..."); response = printer.requestPrintJob(docname, document, agroupset); doVerbose(1, response.toString()); checkResponseIsZero(response, "IPP Print Job: \n"); doVerbose(1, "Printing OK"); } catch (PrintException e) { throw e; } catch (Exception e) { if (getVerbose() > 1) { e.printStackTrace(); } throw new PrintException(e); } } /* * just check that IppResponse is OK */ private void checkResponseIsZero(IppResponse response, String prefix) throws PrintException { if (response.getStatusCode() != 0) { String status = Integer.toHexString(response.getStatusCode()); String id = Integer.toHexString(response.getRequestId()); throw new PrintException(prefix + "\n================ IPP response id: 0x" + id + " =====================" + "\nresponse status code: 0x" + status + "\n" + response.toString() + "\n================ end IPP response 0x" + id + " ====================="); } } /* * convert DocFlavor to DocFlavor ;-) * * some printers support application/ps instead of application/postscript * So: * if mimetype==application/postscript * && printer does not support mimetype application/postscript * && printer supports mimetype application/ps * then * we change mimetype of docflavor to application/ps */ private DocFlavor java2ipp(DocFlavor pDocFlavor) { DocFlavor ippDocFlavor = pDocFlavor; String mime = pDocFlavor.getMimeType(); /* * SPECIAL processing application/ps */ if (mime.equals("application/postscript")) { try { IppDocument document = new IppDocument("Qwerty", "application/postscript", ""); IppResponse response = printer.requestValidateJob("Qwerty", document, null); if (response.getStatusCode() != 0) { document = new IppDocument("Qwerty", "application/ps", ""); response = printer.requestValidateJob("Qwerty", document, null); if (response.getStatusCode() == 0) { if (pDocFlavor instanceof DocFlavor.INPUT_STREAM) { ippDocFlavor = new DocFlavor.INPUT_STREAM( "application/ps"); } else if (ippDocFlavor instanceof DocFlavor.BYTE_ARRAY) { ippDocFlavor = new DocFlavor.BYTE_ARRAY( "application/ps"); } else if (ippDocFlavor instanceof DocFlavor.URL) { ippDocFlavor = new DocFlavor.URL("application/ps"); } } } } catch (Exception e) { e.printStackTrace(); } } return ippDocFlavor; } /* * opposite to java2ipp() method */ private DocFlavor ipp2java(DocFlavor ippDocFlavor) { DocFlavor pDocFlavor = ippDocFlavor; String mime = ippDocFlavor.getMimeType(); /* * SPECIAL processing application/ps */ if (mime.equals("application/ps")) { if (ippDocFlavor instanceof DocFlavor.INPUT_STREAM) { pDocFlavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; } else if (ippDocFlavor instanceof DocFlavor.BYTE_ARRAY) { pDocFlavor = DocFlavor.BYTE_ARRAY.POSTSCRIPT; } else if (ippDocFlavor instanceof DocFlavor.URL) { pDocFlavor = DocFlavor.URL.POSTSCRIPT; } } return pDocFlavor; } /* * the method's name is saying all */ private boolean isDocFlavorSupported(DocFlavor flavor) { if (flavor == null) { throw new NullPointerException("DocFlavor flavor is null"); } DocFlavor clientFlavors[] = getSupportedDocFlavors(); for (int i = 0; i < clientFlavors.length; i++) { if (clientFlavors[i].equals(flavor)) { return true; } } return false; } /* * check permission to read/write to any file */ private boolean canPrintToFile() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkPermission(new FilePermission("<<ALL FILES>>", "read,write")); return true; } catch (SecurityException e) { return false; } } return true; } /* * just list of all doc flavors from specification * it is used in getSupportedDocFlavors() method */ private static DocFlavor[] ALLDOCFLAVORS = { DocFlavor.BYTE_ARRAY.TEXT_PLAIN_HOST, DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_8, DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_16, DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_16BE, DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_16LE, DocFlavor.BYTE_ARRAY.TEXT_PLAIN_US_ASCII, DocFlavor.BYTE_ARRAY.TEXT_HTML_HOST, DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_8, DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_16, DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_16BE, DocFlavor.BYTE_ARRAY.TEXT_HTML_UTF_16LE, DocFlavor.BYTE_ARRAY.TEXT_HTML_US_ASCII, DocFlavor.BYTE_ARRAY.PDF, DocFlavor.BYTE_ARRAY.POSTSCRIPT, DocFlavor.BYTE_ARRAY.PCL, DocFlavor.BYTE_ARRAY.GIF, DocFlavor.BYTE_ARRAY.JPEG, DocFlavor.BYTE_ARRAY.PNG, DocFlavor.BYTE_ARRAY.AUTOSENSE, DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST, DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8, DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16, DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16BE, DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16LE, DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII, DocFlavor.INPUT_STREAM.TEXT_HTML_HOST, DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_8, DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_16, DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_16BE, DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_16LE, DocFlavor.INPUT_STREAM.TEXT_HTML_US_ASCII, DocFlavor.INPUT_STREAM.PDF, DocFlavor.INPUT_STREAM.POSTSCRIPT, DocFlavor.INPUT_STREAM.PCL, DocFlavor.INPUT_STREAM.GIF, DocFlavor.INPUT_STREAM.JPEG, DocFlavor.INPUT_STREAM.PNG, DocFlavor.INPUT_STREAM.AUTOSENSE, DocFlavor.URL.TEXT_PLAIN_HOST, DocFlavor.URL.TEXT_PLAIN_UTF_8, DocFlavor.URL.TEXT_PLAIN_UTF_16, DocFlavor.URL.TEXT_PLAIN_UTF_16BE, DocFlavor.URL.TEXT_PLAIN_UTF_16LE, DocFlavor.URL.TEXT_PLAIN_US_ASCII, DocFlavor.URL.TEXT_HTML_HOST, DocFlavor.URL.TEXT_HTML_UTF_8, DocFlavor.URL.TEXT_HTML_UTF_16, DocFlavor.URL.TEXT_HTML_UTF_16BE, DocFlavor.URL.TEXT_HTML_UTF_16LE, DocFlavor.URL.TEXT_HTML_US_ASCII, DocFlavor.URL.PDF, DocFlavor.URL.POSTSCRIPT, DocFlavor.URL.PCL, DocFlavor.URL.GIF, DocFlavor.URL.JPEG, DocFlavor.URL.PNG, DocFlavor.URL.AUTOSENSE, DocFlavor.CHAR_ARRAY.TEXT_PLAIN, DocFlavor.CHAR_ARRAY.TEXT_HTML, DocFlavor.STRING.TEXT_PLAIN, DocFlavor.STRING.TEXT_HTML, DocFlavor.READER.TEXT_PLAIN, DocFlavor.READER.TEXT_HTML, DocFlavor.SERVICE_FORMATTED.RENDERABLE_IMAGE, DocFlavor.SERVICE_FORMATTED.PRINTABLE, DocFlavor.SERVICE_FORMATTED.PAGEABLE, /* * Some printers accept "application/ps" instead of "application/postscript" * So, we have special processing for those DocFlavor * See comments with phrase: * SPECIAL processing application/ps */ new DocFlavor.INPUT_STREAM("application/ps"), new DocFlavor.URL("application/ps"), new DocFlavor.BYTE_ARRAY("application/ps") }; public static int getVerbose() { return verbose; } public static void setVerbose(int newverbose) { verbose = newverbose; IppPrinter.setVerbose(verbose); } public static void doVerbose(String v) { System.out.println(v); } public static void doVerbose(int level, String v) { if (verbose >= level) { System.out.println(v); } } }
apache/manifoldcf
37,740
connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/sharepoint/SharePointAuthority.java
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.authorities.authorities.sharepoint; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.authorities.interfaces.*; import org.apache.manifoldcf.authorities.system.Logging; import org.apache.manifoldcf.authorities.system.ManifoldCF; import org.apache.manifoldcf.core.util.URLEncoder; import org.apache.manifoldcf.core.util.URLDecoder; import org.apache.manifoldcf.connectorcommon.interfaces.*; import java.io.*; import java.util.*; import java.net.*; import java.util.concurrent.TimeUnit; import javax.naming.*; import javax.naming.ldap.*; import javax.naming.directory.*; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.client.HttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.impl.client.HttpClients; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.config.SocketConfig; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.util.EntityUtils; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.protocol.HttpContext; import org.apache.http.HttpHost; /** This is the native SharePoint implementation of the IAuthorityConnector interface. */ public class SharePointAuthority extends org.apache.manifoldcf.authorities.authorities.BaseAuthorityConnector { public static final String _rcsid = "@(#)$Id$"; // Data from the parameters /** Cache manager. */ private ICacheManager cacheManager = null; private boolean hasSessionParameters = false; /** Length of time that a SharePoint session can remain idle */ private static final long SharePointExpirationInterval = 300000L; // SharePoint server parameters // These are needed for caching, so they are set at connect() time private boolean isClaimSpace = false; private String serverProtocol = null; private String serverUrl = null; private String fileBaseUrl = null; private String serverUserName = null; private String password = null; private String ntlmDomain = null; private String serverName = null; private String serverPortString = null; private String serverLocation = null; private String strippedUserName = null; private String encodedServerLocation = null; private String keystoreData = null; private String proxyHost = null; private String proxyPortString = null; private String proxyUsername = null; private String proxyPassword = null; private String proxyDomain = null; private String cacheLRUsize = null; private String cacheLifetime = null; // These are calculated when the session is set up private int serverPort = -1; private SPSProxyHelper proxy = null; private long sharepointSessionTimeout; private long responseLifetime = -1L; private int LRUsize = -1; private IKeystoreManager keystoreManager = null; private HttpClientConnectionManager connectionManager = null; private HttpClient httpClient = null; // Current host name private static String currentHost = null; static { // Find the current host name try { java.net.InetAddress addr = java.net.InetAddress.getLocalHost(); // Get hostname currentHost = addr.getHostName(); } catch (UnknownHostException e) { } } /** Constructor. */ public SharePointAuthority() { } /** Set thread context. */ @Override public void setThreadContext(IThreadContext tc) throws ManifoldCFException { super.setThreadContext(tc); cacheManager = CacheManagerFactory.make(tc); } /** Clear thread context. */ @Override public void clearThreadContext() { super.clearThreadContext(); cacheManager = null; } /** Connect. The configuration parameters are included. *@param configParams are the configuration parameters for this connection. */ @Override public void connect(ConfigParams configParams) { super.connect(configParams); // Pick up all the parameters that go into the cache key here cacheLifetime = configParams.getParameter(SharePointConfig.PARAM_CACHELIFETIME); if (cacheLifetime == null) cacheLifetime = "1"; cacheLRUsize = configParams.getParameter(SharePointConfig.PARAM_CACHELRUSIZE); if (cacheLRUsize == null) cacheLRUsize = "1000"; String serverVersion = configParams.getParameter( SharePointConfig.PARAM_SERVERVERSION ); if (serverVersion == null) serverVersion = "4.0"; // Authority needs to do nothing with SharePoint version right now. String serverClaimSpace = configParams.getParameter( SharePointConfig.PARAM_SERVERCLAIMSPACE); if (serverClaimSpace == null) serverClaimSpace = "false"; isClaimSpace = serverClaimSpace.equals("true"); serverProtocol = configParams.getParameter( SharePointConfig.PARAM_SERVERPROTOCOL ); if (serverProtocol == null) serverProtocol = "http"; serverName = configParams.getParameter( SharePointConfig.PARAM_SERVERNAME ); serverPortString = configParams.getParameter( SharePointConfig.PARAM_SERVERPORT ); serverLocation = configParams.getParameter(SharePointConfig.PARAM_SERVERLOCATION); if (serverLocation == null) serverLocation = ""; if (serverLocation.endsWith("/")) serverLocation = serverLocation.substring(0,serverLocation.length()-1); if (serverLocation.length() > 0 && !serverLocation.startsWith("/")) serverLocation = "/" + serverLocation; encodedServerLocation = serverLocation; serverLocation = decodePath(serverLocation); serverUserName = configParams.getParameter(SharePointConfig.PARAM_SERVERUSERNAME); password = configParams.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD); int index = serverUserName.indexOf("\\"); if (index != -1) { strippedUserName = serverUserName.substring(index+1); ntlmDomain = serverUserName.substring(0,index); } else { strippedUserName = null; ntlmDomain = null; } proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST); proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT); proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER); proxyPassword = params.getObfuscatedParameter(SharePointConfig.PARAM_PROXYPASSWORD); proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN); keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE); } // All methods below this line will ONLY be called if a connect() call succeeded // on this instance! /** Check connection for sanity. */ @Override public String check() throws ManifoldCFException { getSharePointSession(); try { URL urlServer = new URL( serverUrl ); } catch ( MalformedURLException e ) { return "Illegal SharePoint url: "+e.getMessage(); } try { proxy.checkConnection( "/" ); } catch (ManifoldCFException e) { return e.getMessage(); } return super.check(); } /** Poll. The connection should be closed if it has been idle for too long. */ @Override public void poll() throws ManifoldCFException { long currentTime = System.currentTimeMillis(); if (proxy != null && System.currentTimeMillis() >= sharepointSessionTimeout) expireSharePointSession(); if (connectionManager != null) connectionManager.closeIdleConnections(60000L,TimeUnit.MILLISECONDS); super.poll(); } /** This method is called to assess whether to count this connector instance should * actually be counted as being connected. *@return true if the connector instance is actually connected. */ @Override public boolean isConnected() { return connectionManager != null; } /** Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { // Clean up caching parameters cacheLifetime = null; cacheLRUsize = null; // Clean up SharePoint parameters isClaimSpace = false; serverUrl = null; fileBaseUrl = null; serverUserName = null; strippedUserName = null; password = null; ntlmDomain = null; serverName = null; serverLocation = null; encodedServerLocation = null; serverPort = -1; proxyHost = null; proxyPortString = null; proxyUsername = null; proxyPassword = null; proxyDomain = null; keystoreData = null; keystoreManager = null; proxy = null; httpClient = null; if (connectionManager != null) connectionManager.shutdown(); connectionManager = null; hasSessionParameters = false; super.disconnect(); } /** Obtain the access tokens for a given user name. *@param userName is the user name or identifier. *@return the response tokens (according to the current authority). * (Should throws an exception only when a condition cannot be properly described within the authorization response object.) */ @Override public AuthorizationResponse getAuthorizationResponse(String userName) throws ManifoldCFException { getSessionParameters(); // Construct a cache description object ICacheDescription objectDescription = new AuthorizationResponseDescription(userName, serverName,serverPortString,serverLocation,serverProtocol,serverUserName,password, this.responseLifetime,this.LRUsize); // Enter the cache ICacheHandle ch = cacheManager.enterCache(new ICacheDescription[]{objectDescription},null,null); try { ICacheCreateHandle createHandle = cacheManager.enterCreateSection(ch); try { // Lookup the object AuthorizationResponse response = (AuthorizationResponse)cacheManager.lookupObject(createHandle,objectDescription); if (response != null) return response; // Create the object. response = getAuthorizationResponseUncached(userName); // Save it in the cache cacheManager.saveObject(createHandle,objectDescription,response); // And return it... return response; } finally { cacheManager.leaveCreateSection(createHandle); } } finally { cacheManager.leaveCache(ch); } } /** Obtain the access tokens for a given user name, uncached. *@param userName is the user name or identifier. *@return the response tokens (according to the current authority). * (Should throws an exception only when a condition cannot be properly described within the authorization response object.) */ protected AuthorizationResponse getAuthorizationResponseUncached(String userName) throws ManifoldCFException { //String searchBase = "CN=Administrator,CN=Users,DC=qa-ad-76,DC=metacarta,DC=com"; int index = userName.indexOf("@"); if (index == -1) throw new ManifoldCFException("Username is in unexpected form (no @): '"+userName+"'"); String userPart = userName.substring(0,index); String domainPart = userName.substring(index+1); // First, look up user in SharePoint. getSharePointSession(); List<String> sharePointTokens = proxy.getAccessTokens("/", domainPart + "\\" + userPart); if (sharePointTokens == null) return RESPONSE_USERNOTFOUND_ADDITIVE; return new AuthorizationResponse(sharePointTokens.toArray(new String[0]),AuthorizationResponse.RESPONSE_OK); } /** Obtain the default access tokens for a given user name. *@param userName is the user name or identifier. *@return the default response tokens, presuming that the connect method fails. */ @Override public AuthorizationResponse getDefaultAuthorizationResponse(String userName) { // The default response if the getConnection method fails return RESPONSE_UNREACHABLE_ADDITIVE; } // UI support methods. // // These support methods are involved in setting up authority connection configuration information. The configuration methods cannot assume that the // current authority object is connected. That is why they receive a thread context argument. /** Output the configuration header section. * This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"SharePointAuthority.Server")); tabsArray.add(Messages.getString(locale,"SharePointAuthority.Cache")); Messages.outputResourceWithVelocity(out,locale,"editConfiguration.js",null); } /** Output the configuration body section. * This method is called in the body section of the authority connector's configuration page. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate &lt;html&gt;, &lt;body&gt;, and &lt;form&gt; tags. The name of the * form is "editconnection". *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabName is the current tab name. */ @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { Map<String,Object> velocityContext = new HashMap<String,Object>(); velocityContext.put("TabName",tabName); fillInCacheTab(velocityContext,out,parameters); fillInServerTab(velocityContext,out,parameters); Messages.outputResourceWithVelocity(out,locale,"editConfiguration_Cache.html",velocityContext); Messages.outputResourceWithVelocity(out,locale,"editConfiguration_Server.html",velocityContext); } protected static void fillInServerTab(Map<String,Object> velocityContext, IHTTPOutput out, ConfigParams parameters) throws ManifoldCFException { String serverVersion = parameters.getParameter(SharePointConfig.PARAM_SERVERVERSION); if (serverVersion == null) serverVersion = "2.0"; String serverClaimSpace = parameters.getParameter(SharePointConfig.PARAM_SERVERCLAIMSPACE); if (serverClaimSpace == null) serverClaimSpace = "false"; String serverProtocol = parameters.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL); if (serverProtocol == null) serverProtocol = "http"; String serverName = parameters.getParameter(SharePointConfig.PARAM_SERVERNAME); if (serverName == null) serverName = "localhost"; String serverPort = parameters.getParameter(SharePointConfig.PARAM_SERVERPORT); if (serverPort == null) serverPort = ""; String serverLocation = parameters.getParameter(SharePointConfig.PARAM_SERVERLOCATION); if (serverLocation == null) serverLocation = ""; String userName = parameters.getParameter(SharePointConfig.PARAM_SERVERUSERNAME); if (userName == null) userName = ""; String password = parameters.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD); if (password == null) password = ""; else password = out.mapPasswordToKey(password); String keystore = parameters.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE); IKeystoreManager localKeystore; if (keystore == null) localKeystore = KeystoreManagerFactory.make(""); else localKeystore = KeystoreManagerFactory.make("",keystore); List<Map<String,String>> certificates = new ArrayList<Map<String,String>>(); String[] contents = localKeystore.getContents(); for (String alias : contents) { String description = localKeystore.getDescription(alias); if (description.length() > 128) description = description.substring(0,125) + "..."; Map<String,String> certificate = new HashMap<String,String>(); certificate.put("ALIAS", alias); certificate.put("DESCRIPTION", description); certificates.add(certificate); } String proxyHost = parameters.getParameter(SharePointConfig.PARAM_PROXYHOST); if (proxyHost == null) proxyHost = ""; String proxyPort = parameters.getParameter(SharePointConfig.PARAM_PROXYPORT); if (proxyPort == null) proxyPort = ""; String proxyUser = parameters.getParameter(SharePointConfig.PARAM_PROXYUSER); if (proxyUser == null) proxyUser = ""; String proxyPassword = parameters.getObfuscatedParameter(SharePointConfig.PARAM_PROXYPASSWORD); if (proxyPassword == null) proxyPassword = ""; else proxyPassword = out.mapPasswordToKey(proxyPassword); String proxyDomain = parameters.getParameter(SharePointConfig.PARAM_PROXYDOMAIN); if (proxyDomain == null) proxyDomain = ""; // Fill in context velocityContext.put("SERVERVERSION", serverVersion); velocityContext.put("SERVERCLAIMSPACE", serverClaimSpace); velocityContext.put("SERVERPROTOCOL", serverProtocol); velocityContext.put("SERVERNAME", serverName); velocityContext.put("SERVERPORT", serverPort); velocityContext.put("SERVERLOCATION", serverLocation); velocityContext.put("SERVERUSERNAME", userName); velocityContext.put("SERVERPASSWORD", password); if (keystore != null) velocityContext.put("KEYSTORE", keystore); velocityContext.put("CERTIFICATELIST", certificates); velocityContext.put("PROXYHOST", proxyHost); velocityContext.put("PROXYPORT", proxyPort); velocityContext.put("PROXYUSER", proxyUser); velocityContext.put("PROXYPASSWORD", proxyPassword); velocityContext.put("PROXYDOMAIN", proxyDomain); } protected static void fillInCacheTab(Map<String,Object> velocityContext, IPasswordMapperActivity mapper, ConfigParams parameters) { String cacheLifetime = parameters.getParameter(SharePointConfig.PARAM_CACHELIFETIME); if (cacheLifetime == null) cacheLifetime = "1"; velocityContext.put("CACHELIFETIME",cacheLifetime); String cacheLRUsize = parameters.getParameter(SharePointConfig.PARAM_CACHELRUSIZE); if (cacheLRUsize == null) cacheLRUsize = "1000"; velocityContext.put("CACHELRUSIZE",cacheLRUsize); } /** Process a configuration post. * This method is called at the start of the authority connector's configuration page, whenever there is a possibility that form data for a connection has been * posted. Its purpose is to gather form information and modify the configuration parameters accordingly. * The name of the posted form is "editconnection". *@param threadContext is the local thread context. *@param variableContext is the set of variables available from the post, including binary file post information. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, Locale locale, ConfigParams parameters) throws ManifoldCFException { // Cache parameters String cacheLifetime = variableContext.getParameter("cachelifetime"); if (cacheLifetime != null) parameters.setParameter(SharePointConfig.PARAM_CACHELIFETIME,cacheLifetime); String cacheLRUsize = variableContext.getParameter("cachelrusize"); if (cacheLRUsize != null) parameters.setParameter(SharePointConfig.PARAM_CACHELRUSIZE,cacheLRUsize); // SharePoint server parameters String serverVersion = variableContext.getParameter("serverVersion"); if (serverVersion != null) parameters.setParameter(SharePointConfig.PARAM_SERVERVERSION,serverVersion); String serverClaimSpace = variableContext.getParameter("serverClaimSpace"); if (serverClaimSpace != null) parameters.setParameter(SharePointConfig.PARAM_SERVERCLAIMSPACE,serverClaimSpace); String serverProtocol = variableContext.getParameter("serverProtocol"); if (serverProtocol != null) parameters.setParameter(SharePointConfig.PARAM_SERVERPROTOCOL,serverProtocol); String serverName = variableContext.getParameter("serverName"); if (serverName != null) parameters.setParameter(SharePointConfig.PARAM_SERVERNAME,serverName); String serverPort = variableContext.getParameter("serverPort"); if (serverPort != null) parameters.setParameter(SharePointConfig.PARAM_SERVERPORT,serverPort); String serverLocation = variableContext.getParameter("serverLocation"); if (serverLocation != null) parameters.setParameter(SharePointConfig.PARAM_SERVERLOCATION,serverLocation); String userName = variableContext.getParameter("serverUserName"); if (userName != null) parameters.setParameter(SharePointConfig.PARAM_SERVERUSERNAME,userName); String password = variableContext.getParameter("serverPassword"); if (password != null) parameters.setObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD,variableContext.mapKeyToPassword(password)); String proxyHost = variableContext.getParameter("proxyhost"); if (proxyHost != null) parameters.setParameter(SharePointConfig.PARAM_PROXYHOST,proxyHost); String proxyPort = variableContext.getParameter("proxyport"); if (proxyPort != null) parameters.setParameter(SharePointConfig.PARAM_PROXYPORT,proxyPort); String proxyUser = variableContext.getParameter("proxyuser"); if (proxyUser != null) parameters.setParameter(SharePointConfig.PARAM_PROXYUSER,proxyUser); String proxyPassword = variableContext.getParameter("proxypassword"); if (proxyPassword != null) parameters.setObfuscatedParameter(SharePointConfig.PARAM_PROXYPASSWORD,variableContext.mapKeyToPassword(proxyPassword)); String proxyDomain = variableContext.getParameter("proxydomain"); if (proxyDomain != null) parameters.setParameter(SharePointConfig.PARAM_PROXYDOMAIN,proxyDomain); String keystoreValue = variableContext.getParameter("keystoredata"); if (keystoreValue != null) parameters.setParameter(SharePointConfig.PARAM_SERVERKEYSTORE,keystoreValue); String configOp = variableContext.getParameter("configop"); if (configOp != null) { if (configOp.equals("Delete")) { String alias = variableContext.getParameter("shpkeystorealias"); keystoreValue = parameters.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE); IKeystoreManager mgr; if (keystoreValue != null) mgr = KeystoreManagerFactory.make("",keystoreValue); else mgr = KeystoreManagerFactory.make(""); mgr.remove(alias); parameters.setParameter(SharePointConfig.PARAM_SERVERKEYSTORE,mgr.getString()); } else if (configOp.equals("Add")) { String alias = IDFactory.make(threadContext); byte[] certificateValue = variableContext.getBinaryBytes("shpcertificate"); keystoreValue = parameters.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE); IKeystoreManager mgr; if (keystoreValue != null) mgr = KeystoreManagerFactory.make("",keystoreValue); else mgr = KeystoreManagerFactory.make(""); java.io.InputStream is = new java.io.ByteArrayInputStream(certificateValue); String certError = null; try { mgr.importCertificate(alias,is); } catch (Throwable e) { certError = e.getMessage(); } finally { try { is.close(); } catch (IOException e) { // Don't report anything } } if (certError != null) { // Redirect to error page return "Illegal certificate: "+certError; } parameters.setParameter(SharePointConfig.PARAM_SERVERKEYSTORE,mgr.getString()); } } return null; } /** View configuration. * This method is called in the body section of the authority connector's view configuration page. Its purpose is to present the connection information to the user. * The coder can presume that the HTML that is output from this configuration will be within appropriate &lt;html&gt; and &lt;body&gt;tags. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { Map<String,Object> velocityContext = new HashMap<String,Object>(); fillInCacheTab(velocityContext,out,parameters); fillInServerTab(velocityContext,out,parameters); Messages.outputResourceWithVelocity(out,locale,"viewConfiguration.html",velocityContext); } // Protected methods /** Get parameters needed for caching. */ protected void getSessionParameters() throws ManifoldCFException { if (!hasSessionParameters) { try { responseLifetime = Long.parseLong(this.cacheLifetime) * 60L * 1000L; LRUsize = Integer.parseInt(this.cacheLRUsize); } catch (NumberFormatException e) { throw new ManifoldCFException("Cache lifetime or Cache LRU size must be an integer: "+e.getMessage(),e); } hasSessionParameters = true; } } protected void getSharePointSession() throws ManifoldCFException { if (proxy == null) { // Set up server URL try { if (serverPortString == null || serverPortString.length() == 0) { if (serverProtocol.equals("https")) this.serverPort = 443; else this.serverPort = 80; } else this.serverPort = Integer.parseInt(serverPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(),e); } int proxyPort = 8080; if (proxyPortString != null && proxyPortString.length() > 0) { try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(),e); } } serverUrl = serverProtocol + "://" + serverName; if (serverProtocol.equals("https")) { if (serverPort != 443) serverUrl += ":" + Integer.toString(serverPort); } else { if (serverPort != 80) serverUrl += ":" + Integer.toString(serverPort); } fileBaseUrl = serverUrl + encodedServerLocation; int connectionTimeout = 60000; int socketTimeout = 900000; // Set up ssl if indicated SSLConnectionSocketFactory myFactory = null; if (keystoreData != null) { keystoreManager = KeystoreManagerFactory.make("",keystoreData); myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(), new DefaultHostnameVerifier()); } else { myFactory = SSLConnectionSocketFactory.getSocketFactory(); } PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", myFactory) .build()); poolingConnectionManager.setDefaultMaxPerRoute(1); poolingConnectionManager.setValidateAfterInactivity(2000); poolingConnectionManager.setDefaultSocketConfig(SocketConfig.custom() .setTcpNoDelay(true) .setSoTimeout(socketTimeout) .build()); connectionManager = poolingConnectionManager; CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (strippedUserName != null) { credentialsProvider.setCredentials( new AuthScope(serverName,serverPort), new NTCredentials(strippedUserName, password, currentHost, ntlmDomain)); } RequestConfig.Builder requestBuilder = RequestConfig.custom() .setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout) .setExpectContinueEnabled(false) .setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(proxy); } HttpClientBuilder builder = HttpClients.custom() .setConnectionManager(connectionManager) .disableAutomaticRetries() .setDefaultRequestConfig(requestBuilder.build()) .setDefaultCredentialsProvider(credentialsProvider); builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new LaxRedirectStrategy()); httpClient = builder.build(); proxy = new SPSProxyHelper( serverUrl, encodedServerLocation, serverLocation, serverUserName, password, org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd", httpClient, isClaimSpace ); } sharepointSessionTimeout = System.currentTimeMillis() + SharePointExpirationInterval; } protected void expireSharePointSession() throws ManifoldCFException { serverPort = -1; serverUrl = null; fileBaseUrl = null; keystoreManager = null; proxy = null; httpClient = null; if (connectionManager != null) connectionManager.shutdown(); connectionManager = null; } /** Decode a path item. */ public static String pathItemDecode(String pathItem) { return URLDecoder.decode(pathItem.replaceAll("\\%20","+")); } /** Encode a path item. */ public static String pathItemEncode(String pathItem) { String output = URLEncoder.encode(pathItem); return output.replaceAll("\\+","%20"); } /** Given a path that is /-separated, and otherwise encoded, decode properly to convert to * unencoded form. */ public static String decodePath(String relPath) { StringBuilder sb = new StringBuilder(); String[] pathEntries = relPath.split("/"); int k = 0; boolean isFirst = true; while (k < pathEntries.length) { if (isFirst) isFirst = false; else sb.append("/"); sb.append(pathItemDecode(pathEntries[k++])); } return sb.toString(); } /** Given a path that is /-separated, and otherwise unencoded, encode properly for an actual * URI */ public static String encodePath(String relPath) { StringBuilder sb = new StringBuilder(); String[] pathEntries = relPath.split("/"); int k = 0; boolean isFirst = true; while (k < pathEntries.length) { if (isFirst) isFirst = false; else sb.append("/"); sb.append(pathItemEncode(pathEntries[k++])); } return sb.toString(); } protected static StringSet emptyStringSet = new StringSet(); /** This is the cache object descriptor for cached access tokens from * this connector. */ protected static class AuthorizationResponseDescription extends org.apache.manifoldcf.core.cachemanager.BaseDescription { /** The user name */ protected final String userName; /** The response lifetime */ protected final long responseLifetime; /** The expiration time */ protected long expirationTime = -1; // Parameters designed to guarantee cache key uniqueness protected final String serverName; protected final String serverPortString; protected final String serverLocation; protected final String serverProtocol; protected final String serverUserName; protected final String password; /** Constructor. */ public AuthorizationResponseDescription(String userName, String serverName, String serverPortString, String serverLocation, String serverProtocol, String serverUserName, String password, long responseLifetime, int LRUsize) { super("SharePointAuthority",LRUsize); this.userName = userName; this.responseLifetime = responseLifetime; this.serverName = serverName; this.serverPortString = serverPortString; this.serverLocation = serverLocation; this.serverProtocol = serverProtocol; this.serverUserName = serverUserName; this.password = password; } /** Return the invalidation keys for this object. */ public StringSet getObjectKeys() { return emptyStringSet; } /** Get the critical section name, used for synchronizing the creation of the object */ public String getCriticalSectionName() { StringBuilder sb = new StringBuilder(getClass().getName()); sb.append("-").append(userName); sb.append("-").append(serverName); sb.append("-").append(serverPortString); sb.append("-").append(serverLocation); sb.append("-").append(serverProtocol); sb.append("-").append(serverUserName); sb.append("-").append(password); return sb.toString(); } /** Return the object expiration interval */ public long getObjectExpirationTime(long currentTime) { if (expirationTime == -1) expirationTime = currentTime + responseLifetime; return expirationTime; } public int hashCode() { int rval = userName.hashCode(); rval += serverName.hashCode(); rval += serverPortString.hashCode(); rval += serverLocation.hashCode(); rval += serverProtocol.hashCode(); rval += serverUserName.hashCode(); rval += password.hashCode(); return rval; } public boolean equals(Object o) { if (!(o instanceof AuthorizationResponseDescription)) return false; AuthorizationResponseDescription ard = (AuthorizationResponseDescription)o; if (!ard.userName.equals(userName)) return false; if (!ard.serverName.equals(serverName)) return false; if (!ard.serverPortString.equals(serverPortString)) return false; if (!ard.serverLocation.equals(serverLocation)) return false; if (!ard.serverProtocol.equals(serverProtocol)) return false; if (!ard.serverUserName.equals(serverUserName)) return false; if (!ard.password.equals(password)) return false; return true; } } }
googleapis/google-cloud-java
37,807
java-certificate-manager/proto-google-cloud-certificate-manager-v1/src/main/java/com/google/cloud/certificatemanager/v1/CreateTrustConfigRequest.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/certificatemanager/v1/trust_config.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.certificatemanager.v1; /** * * * <pre> * Request for the `CreateTrustConfig` method. * </pre> * * Protobuf type {@code google.cloud.certificatemanager.v1.CreateTrustConfigRequest} */ public final class CreateTrustConfigRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.certificatemanager.v1.CreateTrustConfigRequest) CreateTrustConfigRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateTrustConfigRequest.newBuilder() to construct. private CreateTrustConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateTrustConfigRequest() { parent_ = ""; trustConfigId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateTrustConfigRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.certificatemanager.v1.TrustConifgProto .internal_static_google_cloud_certificatemanager_v1_CreateTrustConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.certificatemanager.v1.TrustConifgProto .internal_static_google_cloud_certificatemanager_v1_CreateTrustConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.class, com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TRUST_CONFIG_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object trustConfigId_ = ""; /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The trustConfigId. */ @java.lang.Override public java.lang.String getTrustConfigId() { java.lang.Object ref = trustConfigId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); trustConfigId_ = s; return s; } } /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for trustConfigId. */ @java.lang.Override public com.google.protobuf.ByteString getTrustConfigIdBytes() { java.lang.Object ref = trustConfigId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); trustConfigId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TRUST_CONFIG_FIELD_NUMBER = 3; private com.google.cloud.certificatemanager.v1.TrustConfig trustConfig_; /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the trustConfig field is set. */ @java.lang.Override public boolean hasTrustConfig() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The trustConfig. */ @java.lang.Override public com.google.cloud.certificatemanager.v1.TrustConfig getTrustConfig() { return trustConfig_ == null ? com.google.cloud.certificatemanager.v1.TrustConfig.getDefaultInstance() : trustConfig_; } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.certificatemanager.v1.TrustConfigOrBuilder getTrustConfigOrBuilder() { return trustConfig_ == null ? com.google.cloud.certificatemanager.v1.TrustConfig.getDefaultInstance() : trustConfig_; } 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(trustConfigId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, trustConfigId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getTrustConfig()); } 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(trustConfigId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, trustConfigId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getTrustConfig()); } 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.certificatemanager.v1.CreateTrustConfigRequest)) { return super.equals(obj); } com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest other = (com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getTrustConfigId().equals(other.getTrustConfigId())) return false; if (hasTrustConfig() != other.hasTrustConfig()) return false; if (hasTrustConfig()) { if (!getTrustConfig().equals(other.getTrustConfig())) 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) + TRUST_CONFIG_ID_FIELD_NUMBER; hash = (53 * hash) + getTrustConfigId().hashCode(); if (hasTrustConfig()) { hash = (37 * hash) + TRUST_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getTrustConfig().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest 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.certificatemanager.v1.CreateTrustConfigRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest 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.certificatemanager.v1.CreateTrustConfigRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest 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.certificatemanager.v1.CreateTrustConfigRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest 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.certificatemanager.v1.CreateTrustConfigRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest 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.certificatemanager.v1.CreateTrustConfigRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request for the `CreateTrustConfig` method. * </pre> * * Protobuf type {@code google.cloud.certificatemanager.v1.CreateTrustConfigRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.certificatemanager.v1.CreateTrustConfigRequest) com.google.cloud.certificatemanager.v1.CreateTrustConfigRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.certificatemanager.v1.TrustConifgProto .internal_static_google_cloud_certificatemanager_v1_CreateTrustConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.certificatemanager.v1.TrustConifgProto .internal_static_google_cloud_certificatemanager_v1_CreateTrustConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.class, com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.Builder.class); } // Construct using com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTrustConfigFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; trustConfigId_ = ""; trustConfig_ = null; if (trustConfigBuilder_ != null) { trustConfigBuilder_.dispose(); trustConfigBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.certificatemanager.v1.TrustConifgProto .internal_static_google_cloud_certificatemanager_v1_CreateTrustConfigRequest_descriptor; } @java.lang.Override public com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest getDefaultInstanceForType() { return com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest build() { com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest buildPartial() { com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest result = new com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.trustConfigId_ = trustConfigId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.trustConfig_ = trustConfigBuilder_ == null ? trustConfig_ : trustConfigBuilder_.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.certificatemanager.v1.CreateTrustConfigRequest) { return mergeFrom((com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest other) { if (other == com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getTrustConfigId().isEmpty()) { trustConfigId_ = other.trustConfigId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasTrustConfig()) { mergeTrustConfig(other.getTrustConfig()); } 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: { trustConfigId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getTrustConfigFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the TrustConfig. Must be in the format * `projects/&#42;&#47;locations/&#42;`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object trustConfigId_ = ""; /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The trustConfigId. */ public java.lang.String getTrustConfigId() { java.lang.Object ref = trustConfigId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); trustConfigId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for trustConfigId. */ public com.google.protobuf.ByteString getTrustConfigIdBytes() { java.lang.Object ref = trustConfigId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); trustConfigId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The trustConfigId to set. * @return This builder for chaining. */ public Builder setTrustConfigId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } trustConfigId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearTrustConfigId() { trustConfigId_ = getDefaultInstance().getTrustConfigId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. A user-provided name of the TrustConfig. Must match the regexp * `[a-z0-9-]{1,63}`. * </pre> * * <code>string trust_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for trustConfigId to set. * @return This builder for chaining. */ public Builder setTrustConfigIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); trustConfigId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.certificatemanager.v1.TrustConfig trustConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.certificatemanager.v1.TrustConfig, com.google.cloud.certificatemanager.v1.TrustConfig.Builder, com.google.cloud.certificatemanager.v1.TrustConfigOrBuilder> trustConfigBuilder_; /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the trustConfig field is set. */ public boolean hasTrustConfig() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The trustConfig. */ public com.google.cloud.certificatemanager.v1.TrustConfig getTrustConfig() { if (trustConfigBuilder_ == null) { return trustConfig_ == null ? com.google.cloud.certificatemanager.v1.TrustConfig.getDefaultInstance() : trustConfig_; } else { return trustConfigBuilder_.getMessage(); } } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTrustConfig(com.google.cloud.certificatemanager.v1.TrustConfig value) { if (trustConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } trustConfig_ = value; } else { trustConfigBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTrustConfig( com.google.cloud.certificatemanager.v1.TrustConfig.Builder builderForValue) { if (trustConfigBuilder_ == null) { trustConfig_ = builderForValue.build(); } else { trustConfigBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeTrustConfig(com.google.cloud.certificatemanager.v1.TrustConfig value) { if (trustConfigBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && trustConfig_ != null && trustConfig_ != com.google.cloud.certificatemanager.v1.TrustConfig.getDefaultInstance()) { getTrustConfigBuilder().mergeFrom(value); } else { trustConfig_ = value; } } else { trustConfigBuilder_.mergeFrom(value); } if (trustConfig_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearTrustConfig() { bitField0_ = (bitField0_ & ~0x00000004); trustConfig_ = null; if (trustConfigBuilder_ != null) { trustConfigBuilder_.dispose(); trustConfigBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.certificatemanager.v1.TrustConfig.Builder getTrustConfigBuilder() { bitField0_ |= 0x00000004; onChanged(); return getTrustConfigFieldBuilder().getBuilder(); } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.certificatemanager.v1.TrustConfigOrBuilder getTrustConfigOrBuilder() { if (trustConfigBuilder_ != null) { return trustConfigBuilder_.getMessageOrBuilder(); } else { return trustConfig_ == null ? com.google.cloud.certificatemanager.v1.TrustConfig.getDefaultInstance() : trustConfig_; } } /** * * * <pre> * Required. A definition of the TrustConfig to create. * </pre> * * <code> * .google.cloud.certificatemanager.v1.TrustConfig trust_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.certificatemanager.v1.TrustConfig, com.google.cloud.certificatemanager.v1.TrustConfig.Builder, com.google.cloud.certificatemanager.v1.TrustConfigOrBuilder> getTrustConfigFieldBuilder() { if (trustConfigBuilder_ == null) { trustConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.certificatemanager.v1.TrustConfig, com.google.cloud.certificatemanager.v1.TrustConfig.Builder, com.google.cloud.certificatemanager.v1.TrustConfigOrBuilder>( getTrustConfig(), getParentForChildren(), isClean()); trustConfig_ = null; } return trustConfigBuilder_; } @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.certificatemanager.v1.CreateTrustConfigRequest) } // @@protoc_insertion_point(class_scope:google.cloud.certificatemanager.v1.CreateTrustConfigRequest) private static final com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest(); } public static com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateTrustConfigRequest> PARSER = new com.google.protobuf.AbstractParser<CreateTrustConfigRequest>() { @java.lang.Override public CreateTrustConfigRequest 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<CreateTrustConfigRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateTrustConfigRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.certificatemanager.v1.CreateTrustConfigRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,783
java-network-management/proto-google-cloud-network-management-v1beta1/src/main/java/com/google/cloud/networkmanagement/v1beta1/QueryOrgVpcFlowLogsConfigsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/networkmanagement/v1beta1/vpc_flow_logs.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.networkmanagement.v1beta1; /** * * * <pre> * Request for the `QueryOrgVpcFlowLogsConfigs` method. * </pre> * * Protobuf type {@code google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest} */ public final class QueryOrgVpcFlowLogsConfigsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) QueryOrgVpcFlowLogsConfigsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use QueryOrgVpcFlowLogsConfigsRequest.newBuilder() to construct. private QueryOrgVpcFlowLogsConfigsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private QueryOrgVpcFlowLogsConfigsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new QueryOrgVpcFlowLogsConfigsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkmanagement.v1beta1.VpcFlowLogsProto .internal_static_google_cloud_networkmanagement_v1beta1_QueryOrgVpcFlowLogsConfigsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkmanagement.v1beta1.VpcFlowLogsProto .internal_static_google_cloud_networkmanagement_v1beta1_QueryOrgVpcFlowLogsConfigsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest.class, com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest.Builder .class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. Number of `VpcFlowLogsConfigs` to return. * </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 from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. Page token from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </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. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest)) { return super.equals(obj); } com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest other = (com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request for the `QueryOrgVpcFlowLogsConfigs` method. * </pre> * * Protobuf type {@code google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkmanagement.v1beta1.VpcFlowLogsProto .internal_static_google_cloud_networkmanagement_v1beta1_QueryOrgVpcFlowLogsConfigsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkmanagement.v1beta1.VpcFlowLogsProto .internal_static_google_cloud_networkmanagement_v1beta1_QueryOrgVpcFlowLogsConfigsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest.class, com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest.Builder .class); } // Construct using // com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.networkmanagement.v1beta1.VpcFlowLogsProto .internal_static_google_cloud_networkmanagement_v1beta1_QueryOrgVpcFlowLogsConfigsRequest_descriptor; } @java.lang.Override public com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest getDefaultInstanceForType() { return com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest build() { com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest buildPartial() { com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest result = new com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) { return mergeFrom( (com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest other) { if (other == com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the VpcFlowLogsConfig, specified in * the following format: `projects/{project_id}/locations/global` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Number of `VpcFlowLogsConfigs` to return. * </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. Number of `VpcFlowLogsConfigs` to return. * </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. Number of `VpcFlowLogsConfigs` to return. * </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 from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Page token from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Page token from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Page token from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. Page token from an earlier query, as returned in * `next_page_token`. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </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. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </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. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </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. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </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. Lists the `VpcFlowLogsConfigs` that match the filter expression. * A filter expression must use the supported [CEL logic operators] * (https://cloud.google.com/vpc/docs/about-flow-logs-records#supported_cel_logic_operators). * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest) private static final com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest(); } public static com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<QueryOrgVpcFlowLogsConfigsRequest> PARSER = new com.google.protobuf.AbstractParser<QueryOrgVpcFlowLogsConfigsRequest>() { @java.lang.Override public QueryOrgVpcFlowLogsConfigsRequest 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<QueryOrgVpcFlowLogsConfigsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<QueryOrgVpcFlowLogsConfigsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.networkmanagement.v1beta1.QueryOrgVpcFlowLogsConfigsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,900
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetHealthBackendServiceRequest.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 BackendServices.GetHealth. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetHealthBackendServiceRequest} */ public final class GetHealthBackendServiceRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetHealthBackendServiceRequest) GetHealthBackendServiceRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetHealthBackendServiceRequest.newBuilder() to construct. private GetHealthBackendServiceRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetHealthBackendServiceRequest() { backendService_ = ""; project_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GetHealthBackendServiceRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetHealthBackendServiceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetHealthBackendServiceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetHealthBackendServiceRequest.class, com.google.cloud.compute.v1.GetHealthBackendServiceRequest.Builder.class); } private int bitField0_; public static final int BACKEND_SERVICE_FIELD_NUMBER = 306946058; @SuppressWarnings("serial") private volatile java.lang.Object backendService_ = ""; /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The backendService. */ @java.lang.Override public java.lang.String getBackendService() { java.lang.Object ref = backendService_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); backendService_ = s; return s; } } /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for backendService. */ @java.lang.Override public com.google.protobuf.ByteString getBackendServiceBytes() { java.lang.Object ref = backendService_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); backendService_ = 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_ = ""; /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESOURCE_GROUP_REFERENCE_RESOURCE_FIELD_NUMBER = 112951123; private com.google.cloud.compute.v1.ResourceGroupReference resourceGroupReferenceResource_; /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the resourceGroupReferenceResource field is set. */ @java.lang.Override public boolean hasResourceGroupReferenceResource() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The resourceGroupReferenceResource. */ @java.lang.Override public com.google.cloud.compute.v1.ResourceGroupReference getResourceGroupReferenceResource() { return resourceGroupReferenceResource_ == null ? com.google.cloud.compute.v1.ResourceGroupReference.getDefaultInstance() : resourceGroupReferenceResource_; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.ResourceGroupReferenceOrBuilder getResourceGroupReferenceResourceOrBuilder() { return resourceGroupReferenceResource_ == null ? com.google.cloud.compute.v1.ResourceGroupReference.getDefaultInstance() : resourceGroupReferenceResource_; } 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(112951123, getResourceGroupReferenceResource()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backendService_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 306946058, backendService_); } 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( 112951123, getResourceGroupReferenceResource()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backendService_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(306946058, backendService_); } 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.GetHealthBackendServiceRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.GetHealthBackendServiceRequest other = (com.google.cloud.compute.v1.GetHealthBackendServiceRequest) obj; if (!getBackendService().equals(other.getBackendService())) return false; if (!getProject().equals(other.getProject())) return false; if (hasResourceGroupReferenceResource() != other.hasResourceGroupReferenceResource()) return false; if (hasResourceGroupReferenceResource()) { if (!getResourceGroupReferenceResource().equals(other.getResourceGroupReferenceResource())) 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) + BACKEND_SERVICE_FIELD_NUMBER; hash = (53 * hash) + getBackendService().hashCode(); hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); if (hasResourceGroupReferenceResource()) { hash = (37 * hash) + RESOURCE_GROUP_REFERENCE_RESOURCE_FIELD_NUMBER; hash = (53 * hash) + getResourceGroupReferenceResource().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest 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.GetHealthBackendServiceRequest 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 BackendServices.GetHealth. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetHealthBackendServiceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetHealthBackendServiceRequest) com.google.cloud.compute.v1.GetHealthBackendServiceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetHealthBackendServiceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetHealthBackendServiceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetHealthBackendServiceRequest.class, com.google.cloud.compute.v1.GetHealthBackendServiceRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.GetHealthBackendServiceRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getResourceGroupReferenceResourceFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; backendService_ = ""; project_ = ""; resourceGroupReferenceResource_ = null; if (resourceGroupReferenceResourceBuilder_ != null) { resourceGroupReferenceResourceBuilder_.dispose(); resourceGroupReferenceResourceBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetHealthBackendServiceRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.GetHealthBackendServiceRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.GetHealthBackendServiceRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.GetHealthBackendServiceRequest build() { com.google.cloud.compute.v1.GetHealthBackendServiceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.GetHealthBackendServiceRequest buildPartial() { com.google.cloud.compute.v1.GetHealthBackendServiceRequest result = new com.google.cloud.compute.v1.GetHealthBackendServiceRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.GetHealthBackendServiceRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.backendService_ = backendService_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.project_ = project_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.resourceGroupReferenceResource_ = resourceGroupReferenceResourceBuilder_ == null ? resourceGroupReferenceResource_ : resourceGroupReferenceResourceBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.GetHealthBackendServiceRequest) { return mergeFrom((com.google.cloud.compute.v1.GetHealthBackendServiceRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.GetHealthBackendServiceRequest other) { if (other == com.google.cloud.compute.v1.GetHealthBackendServiceRequest.getDefaultInstance()) return this; if (!other.getBackendService().isEmpty()) { backendService_ = other.backendService_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasResourceGroupReferenceResource()) { mergeResourceGroupReferenceResource(other.getResourceGroupReferenceResource()); } 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 903608986: { input.readMessage( getResourceGroupReferenceResourceFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 903608986 case 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 1820481738 case -1839398830: { backendService_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case -1839398830 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 backendService_ = ""; /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The backendService. */ public java.lang.String getBackendService() { java.lang.Object ref = backendService_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); backendService_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for backendService. */ public com.google.protobuf.ByteString getBackendServiceBytes() { java.lang.Object ref = backendService_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); backendService_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The backendService to set. * @return This builder for chaining. */ public Builder setBackendService(java.lang.String value) { if (value == null) { throw new NullPointerException(); } backendService_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearBackendService() { backendService_ = getDefaultInstance().getBackendService(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of the BackendService resource to which the queried instance belongs. * </pre> * * <code>string backend_service = 306946058 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for backendService to set. * @return This builder for chaining. */ public Builder setBackendServiceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); backendService_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object project_ = ""; /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.compute.v1.ResourceGroupReference resourceGroupReferenceResource_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.ResourceGroupReference, com.google.cloud.compute.v1.ResourceGroupReference.Builder, com.google.cloud.compute.v1.ResourceGroupReferenceOrBuilder> resourceGroupReferenceResourceBuilder_; /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the resourceGroupReferenceResource field is set. */ public boolean hasResourceGroupReferenceResource() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The resourceGroupReferenceResource. */ public com.google.cloud.compute.v1.ResourceGroupReference getResourceGroupReferenceResource() { if (resourceGroupReferenceResourceBuilder_ == null) { return resourceGroupReferenceResource_ == null ? com.google.cloud.compute.v1.ResourceGroupReference.getDefaultInstance() : resourceGroupReferenceResource_; } else { return resourceGroupReferenceResourceBuilder_.getMessage(); } } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setResourceGroupReferenceResource( com.google.cloud.compute.v1.ResourceGroupReference value) { if (resourceGroupReferenceResourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } resourceGroupReferenceResource_ = value; } else { resourceGroupReferenceResourceBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setResourceGroupReferenceResource( com.google.cloud.compute.v1.ResourceGroupReference.Builder builderForValue) { if (resourceGroupReferenceResourceBuilder_ == null) { resourceGroupReferenceResource_ = builderForValue.build(); } else { resourceGroupReferenceResourceBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeResourceGroupReferenceResource( com.google.cloud.compute.v1.ResourceGroupReference value) { if (resourceGroupReferenceResourceBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && resourceGroupReferenceResource_ != null && resourceGroupReferenceResource_ != com.google.cloud.compute.v1.ResourceGroupReference.getDefaultInstance()) { getResourceGroupReferenceResourceBuilder().mergeFrom(value); } else { resourceGroupReferenceResource_ = value; } } else { resourceGroupReferenceResourceBuilder_.mergeFrom(value); } if (resourceGroupReferenceResource_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearResourceGroupReferenceResource() { bitField0_ = (bitField0_ & ~0x00000004); resourceGroupReferenceResource_ = null; if (resourceGroupReferenceResourceBuilder_ != null) { resourceGroupReferenceResourceBuilder_.dispose(); resourceGroupReferenceResourceBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.compute.v1.ResourceGroupReference.Builder getResourceGroupReferenceResourceBuilder() { bitField0_ |= 0x00000004; onChanged(); return getResourceGroupReferenceResourceFieldBuilder().getBuilder(); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.compute.v1.ResourceGroupReferenceOrBuilder getResourceGroupReferenceResourceOrBuilder() { if (resourceGroupReferenceResourceBuilder_ != null) { return resourceGroupReferenceResourceBuilder_.getMessageOrBuilder(); } else { return resourceGroupReferenceResource_ == null ? com.google.cloud.compute.v1.ResourceGroupReference.getDefaultInstance() : resourceGroupReferenceResource_; } } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.ResourceGroupReference resource_group_reference_resource = 112951123 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.ResourceGroupReference, com.google.cloud.compute.v1.ResourceGroupReference.Builder, com.google.cloud.compute.v1.ResourceGroupReferenceOrBuilder> getResourceGroupReferenceResourceFieldBuilder() { if (resourceGroupReferenceResourceBuilder_ == null) { resourceGroupReferenceResourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.ResourceGroupReference, com.google.cloud.compute.v1.ResourceGroupReference.Builder, com.google.cloud.compute.v1.ResourceGroupReferenceOrBuilder>( getResourceGroupReferenceResource(), getParentForChildren(), isClean()); resourceGroupReferenceResource_ = null; } return resourceGroupReferenceResourceBuilder_; } @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.GetHealthBackendServiceRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetHealthBackendServiceRequest) private static final com.google.cloud.compute.v1.GetHealthBackendServiceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetHealthBackendServiceRequest(); } public static com.google.cloud.compute.v1.GetHealthBackendServiceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetHealthBackendServiceRequest> PARSER = new com.google.protobuf.AbstractParser<GetHealthBackendServiceRequest>() { @java.lang.Override public GetHealthBackendServiceRequest 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<GetHealthBackendServiceRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetHealthBackendServiceRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.GetHealthBackendServiceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
hibernate/hibernate-orm
35,773
hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
/* * SPDX-License-Identifier: Apache-2.0 * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.mapping; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.function.Supplier; import org.hibernate.Internal; import org.hibernate.MappingException; import org.hibernate.annotations.CacheLayout; import org.hibernate.boot.Metadata; import org.hibernate.boot.registry.classloading.spi.ClassLoadingException; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.dialect.Dialect; import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.internal.FilterConfiguration; import org.hibernate.internal.util.collections.JoinedList; import org.hibernate.jdbc.Expectation; import org.hibernate.jpa.event.spi.CallbackDefinition; import org.hibernate.metamodel.spi.RuntimeModelCreationContext; import org.hibernate.service.ServiceRegistry; import org.hibernate.sql.Alias; import org.hibernate.type.CollectionType; import org.hibernate.type.spi.TypeConfiguration; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static java.util.Comparator.comparing; import static org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle.expectationConstructor; import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.root; import static org.hibernate.mapping.MappingHelper.checkPropertyColumnDuplication; import static org.hibernate.mapping.MappingHelper.classForName; import static org.hibernate.sql.Template.collectColumnNames; /** * A mapping model object that represents an {@linkplain jakarta.persistence.Entity entity class}. * * @author Gavin King */ public abstract sealed class PersistentClass implements IdentifiableTypeClass, AttributeContainer, Filterable, MetaAttributable, Contributable, Serializable permits RootClass, Subclass { private static final Alias PK_ALIAS = new Alias( 15, "PK" ); /** * The magic value of {@link jakarta.persistence.DiscriminatorValue#value} * which indicates that the subclass is distinguished by a null value of the * discriminator column. */ public static final String NULL_DISCRIMINATOR_MAPPING = "null"; /** * The magic value of {@link jakarta.persistence.DiscriminatorValue#value} * which indicates that the subclass is distinguished by any non-null value * of the discriminator column. */ public static final String NOT_NULL_DISCRIMINATOR_MAPPING = "not null"; private final MetadataBuildingContext metadataBuildingContext; private final String contributor; private String entityName; private String className; private transient Class<?> mappedClass; private String proxyInterfaceName; private transient Class<?> proxyInterface; private String jpaEntityName; private String discriminatorValue; private boolean lazy; private final List<Property> properties = new ArrayList<>(); private final List<Property> declaredProperties = new ArrayList<>(); private final List<Subclass> subclasses = new ArrayList<>(); private final List<Property> subclassProperties = new ArrayList<>(); private final List<Table> subclassTables = new ArrayList<>(); private boolean dynamicInsert; private boolean dynamicUpdate; private int batchSize = -1; private boolean selectBeforeUpdate; private java.util.Map<String, MetaAttribute> metaAttributes; private final List<Join> joins = new ArrayList<>(); private final List<Join> subclassJoins = new ArrayList<>(); private final List<FilterConfiguration> filters = new ArrayList<>(); protected final Set<String> synchronizedTables = new HashSet<>(); private String loaderName; private Boolean isAbstract; private boolean hasSubselectLoadableCollections; private Component identifierMapper; private List<CallbackDefinition> callbackDefinitions; private final List<CheckConstraint> checkConstraints = new ArrayList<>(); // Custom SQL private String customSQLInsert; private boolean customInsertCallable; private String customSQLUpdate; private boolean customUpdateCallable; private String customSQLDelete; private boolean customDeleteCallable; private MappedSuperclass superMappedSuperclass; private Component declaredIdentifierMapper; private OptimisticLockStyle optimisticLockStyle; private Supplier<? extends Expectation> insertExpectation; private Supplier<? extends Expectation> updateExpectation; private Supplier<? extends Expectation> deleteExpectation; private boolean isCached; private CacheLayout queryCacheLayout; public PersistentClass(MetadataBuildingContext buildingContext) { this.metadataBuildingContext = buildingContext; this.contributor = buildingContext.getCurrentContributorName(); } public String getContributor() { return contributor; } public ServiceRegistry getServiceRegistry() { return metadataBuildingContext.getBuildingOptions().getServiceRegistry(); } public String getClassName() { return className; } public void setClassName(String className) { this.className = className == null ? null : className.intern(); this.mappedClass = null; } public String getProxyInterfaceName() { return proxyInterfaceName; } public void setProxyInterfaceName(String proxyInterfaceName) { this.proxyInterfaceName = proxyInterfaceName; this.proxyInterface = null; } private Class<?> getClassForName(String className) { return classForName( className, metadataBuildingContext.getBootstrapContext() ); } public Class<?> getMappedClass() throws MappingException { if ( className == null ) { return null; } try { if ( mappedClass == null ) { mappedClass = getClassForName( className ); } return mappedClass; } catch (ClassLoadingException e) { throw new MappingException( "entity class not found: " + className, e ); } } public Class<?> getProxyInterface() { if ( proxyInterfaceName == null ) { return null; } try { if ( proxyInterface == null ) { proxyInterface = getClassForName( proxyInterfaceName ); } return proxyInterface; } catch (ClassLoadingException e) { throw new MappingException( "proxy class not found: " + proxyInterfaceName, e ); } } public boolean useDynamicInsert() { return dynamicInsert; } abstract int nextSubclassId(); public abstract int getSubclassId(); public boolean useDynamicUpdate() { return dynamicUpdate; } public void setDynamicInsert(boolean dynamicInsert) { this.dynamicInsert = dynamicInsert; } public void setDynamicUpdate(boolean dynamicUpdate) { this.dynamicUpdate = dynamicUpdate; } public String getDiscriminatorValue() { return discriminatorValue; } public void addSubclass(Subclass subclass) throws MappingException { // inheritance cycle detection (paranoid check) PersistentClass superclass = getSuperclass(); while ( superclass != null ) { if ( subclass.getEntityName().equals( superclass.getEntityName() ) ) { throw new MappingException( "Circular inheritance mapping: '" + subclass.getEntityName() + "' will have itself as superclass when extending '" + getEntityName() + "'" ); } superclass = superclass.getSuperclass(); } subclasses.add( subclass ); } public boolean hasSubclasses() { return !subclasses.isEmpty(); } public int getSubclassSpan() { int span = subclasses.size(); for ( var subclass : subclasses ) { span += subclass.getSubclassSpan(); } return span; } /** * Get the subclasses in a special 'order', most derived subclasses first. */ public List<Subclass> getSubclasses() { @SuppressWarnings("unchecked") final List<Subclass>[] subclassLists = new List[subclasses.size() + 1]; int j; for (j = 0; j < subclasses.size(); j++) { subclassLists[j] = subclasses.get(j).getSubclasses(); } subclassLists[j] = subclasses; return new JoinedList<>( subclassLists ); } public List<PersistentClass> getSubclassClosure() { final ArrayList<List<PersistentClass>> lists = new ArrayList<>(); lists.add( List.of( this ) ); for ( var subclass : getSubclasses() ) { lists.add( subclass.getSubclassClosure() ); } return new JoinedList<>( lists ); } public Table getIdentityTable() { return getRootTable(); } public List<Subclass> getDirectSubclasses() { return subclasses; } @Override public void addProperty(Property property) { properties.add( property ); declaredProperties.add( property ); property.setPersistentClass( this ); } @Override public boolean contains(Property property) { return properties.contains( property ); } public abstract Table getTable(); public String getEntityName() { return entityName; } public abstract boolean isMutable(); public abstract boolean hasIdentifierProperty(); public abstract Property getIdentifierProperty(); public abstract Property getDeclaredIdentifierProperty(); public abstract KeyValue getIdentifier(); public abstract Property getVersion(); public abstract Property getDeclaredVersion(); public abstract Value getDiscriminator(); public abstract boolean isInherited(); public abstract boolean isPolymorphic(); public abstract boolean isVersioned(); public boolean isCached() { return isCached; } public void setCached(boolean cached) { isCached = cached; } public CacheLayout getQueryCacheLayout() { return queryCacheLayout; } public void setQueryCacheLayout(CacheLayout queryCacheLayout) { this.queryCacheLayout = queryCacheLayout; } public abstract String getCacheConcurrencyStrategy(); public abstract String getNaturalIdCacheRegionName(); public abstract PersistentClass getSuperclass(); /** * @deprecated No longer supported */ @Deprecated public boolean isExplicitPolymorphism() { return false; } public abstract boolean isDiscriminatorInsertable(); public abstract List<Property> getPropertyClosure(); public abstract List<Table> getTableClosure(); public abstract List<KeyValue> getKeyClosure(); protected void addSubclassProperty(Property prop) { subclassProperties.add( prop ); } protected void addSubclassJoin(Join join) { subclassJoins.add( join ); } protected void addSubclassTable(Table subclassTable) { subclassTables.add( subclassTable ); } public List<Property> getSubclassPropertyClosure() { final ArrayList<List<Property>> lists = new ArrayList<>(); lists.add( getPropertyClosure() ); lists.add( subclassProperties ); for ( var join : subclassJoins ) { lists.add( join.getProperties() ); } return new JoinedList<>( lists ); } public List<Join> getSubclassJoinClosure() { return new JoinedList<>( getJoinClosure(), subclassJoins ); } public List<Table> getSubclassTableClosure() { return new JoinedList<>( getTableClosure(), subclassTables ); } public boolean isClassOrSuperclassJoin(Join join) { return joins.contains( join ); } public boolean isClassOrSuperclassTable(Table closureTable) { return getTable() == closureTable; } public boolean isLazy() { return lazy; } public void setLazy(boolean lazy) { this.lazy = lazy; } public abstract boolean isConcreteProxy(); public abstract boolean hasEmbeddedIdentifier(); public abstract Table getRootTable(); public abstract RootClass getRootClass(); public abstract KeyValue getKey(); public void setDiscriminatorValue(String discriminatorValue) { this.discriminatorValue = discriminatorValue; } public void setEntityName(String entityName) { this.entityName = entityName == null ? null : entityName.intern(); } public void createPrimaryKey() { //Primary key constraint final var table = getTable(); final var primaryKey = new PrimaryKey( table ); primaryKey.setName( PK_ALIAS.toAliasString( table.getName() ) ); primaryKey.addColumns( getKey() ); if ( addPartitionKeyToPrimaryKey() ) { for ( var property : getProperties() ) { if ( property.getValue().isPartitionKey() ) { primaryKey.addColumns( property.getValue() ); } } } table.setPrimaryKey( primaryKey ); } private boolean addPartitionKeyToPrimaryKey() { return metadataBuildingContext.getMetadataCollector() .getDatabase().getDialect() .addPartitionKeyToPrimaryKey(); } public abstract String getWhere(); public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public boolean hasSelectBeforeUpdate() { return selectBeforeUpdate; } public void setSelectBeforeUpdate(boolean selectBeforeUpdate) { this.selectBeforeUpdate = selectBeforeUpdate; } /** * Build a list of properties which may be referenced in association mappings. * <p> * Includes properties defined in superclasses of the mapping inheritance. * Includes all properties defined as part of a join. * * @see #getReferencedProperty * @return The referenceable property iterator. */ public List<Property> getReferenceableProperties() { return getPropertyClosure(); } /** * Given a property path, locate the appropriate referenceable property reference. * <p> * A referenceable property is a property which can be a target of a foreign-key * mapping (e.g. {@code @ManyToOne}, {@code @OneToOne}). * * @param propertyPath The property path to resolve into a property reference. * * @return The property reference (never null). * * @throws MappingException If the property could not be found. */ public Property getReferencedProperty(String propertyPath) throws MappingException { try { return getRecursiveProperty( propertyPath, getReferenceableProperties() ); } catch ( MappingException e ) { throw new MappingException( "property-ref [" + propertyPath + "] not found on entity [" + getEntityName() + "]", e ); } } public Property getRecursiveProperty(String propertyPath) throws MappingException { try { return getRecursiveProperty( propertyPath, getPropertyClosure() ); } catch ( MappingException e ) { throw new MappingException( "property [" + propertyPath + "] not found on entity [" + getEntityName() + "]", e ); } } private Property getRecursiveProperty(String propertyPath, List<Property> properties) throws MappingException { Property property = null; var tokens = new StringTokenizer( propertyPath, ".", false ); try { while ( tokens.hasMoreElements() ) { final String element = (String) tokens.nextElement(); if ( property == null ) { Property identifierProperty = getIdentifierProperty(); if ( identifierProperty != null && identifierProperty.getName().equals( element ) ) { // we have a mapped identifier property and the root of // the incoming property path matched that identifier // property property = identifierProperty; } else if ( identifierProperty == null && getIdentifierMapper() != null ) { // we have an embedded composite identifier try { identifierProperty = getProperty( element, getIdentifierMapper().getProperties() ); // the root of the incoming property path matched one // of the embedded composite identifier properties property = identifierProperty; } catch ( MappingException ignore ) { // ignore it... } } if ( property == null ) { property = getProperty( element, properties ); } } else { //flat recursive algorithm final var value = (Component) property.getValue(); property = value.getProperty( element ); } } } catch ( MappingException e ) { throw new MappingException( "property [" + propertyPath + "] not found on entity [" + getEntityName() + "]" ); } return property; } private Property getProperty(String propertyName, List<Property> properties) throws MappingException { final String root = root( propertyName ); for ( var property : properties ) { if ( property.getName().equals( root ) || ( property instanceof Backref || property instanceof IndexBackref ) && property.getName().equals( propertyName ) ) { return property; } } throw new MappingException( "property [" + propertyName + "] not found on entity [" + getEntityName() + "]" ); } @Override public Property getProperty(String propertyName) throws MappingException { final var identifierProperty = getIdentifierProperty(); if ( identifierProperty != null && identifierProperty.getName().equals( root( propertyName ) ) ) { return identifierProperty; } else { List<Property> closure = getPropertyClosure(); final var identifierMapper = getIdentifierMapper(); if ( identifierMapper != null ) { closure = new JoinedList<>( identifierMapper.getProperties(), closure ); } return getProperty( propertyName, closure ); } } /** * Check to see if this PersistentClass defines a property with the given name. * * @param name The property name to check * * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean hasProperty(String name) { final var identifierProperty = getIdentifierProperty(); if ( identifierProperty != null && identifierProperty.getName().equals( name ) ) { return true; } else { for ( var property : getPropertyClosure() ) { if ( property.getName().equals( name ) ) { return true; } } return false; } } /** * Check to see if a property with the given name exists in the super hierarchy * of this PersistentClass. Does not check this PersistentClass, just up the * hierarchy * * @param name The property name to check * * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean isPropertyDefinedInSuperHierarchy(String name) { return getSuperclass() != null && getSuperclass().isPropertyDefinedInHierarchy( name ); } /** * Check to see if a property with the given name exists in this PersistentClass * or in any of its super hierarchy. Unlike {@link #isPropertyDefinedInSuperHierarchy}, * this method does check this PersistentClass * * @param name The property name to check * * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean isPropertyDefinedInHierarchy(String name) { return hasProperty( name ) || getSuperMappedSuperclass() != null && getSuperMappedSuperclass().isPropertyDefinedInHierarchy( name ) || getSuperclass() != null && getSuperclass().isPropertyDefinedInHierarchy( name ); } public OptimisticLockStyle getOptimisticLockStyle() { return optimisticLockStyle; } public void setOptimisticLockStyle(OptimisticLockStyle optimisticLockStyle) { this.optimisticLockStyle = optimisticLockStyle; } public void validate(Metadata mapping) throws MappingException { for ( var prop : getProperties() ) { if ( !prop.isValid( mapping ) ) { final var type = prop.getType(); final int actualColumns = prop.getColumnSpan(); final int requiredColumns = type.getColumnSpan( mapping ); throw new MappingException( "Property '" + qualify( getEntityName(), prop.getName() ) + "' maps to " + actualColumns + " columns but " + requiredColumns + " columns are required (type '" + type.getName() + "' spans " + requiredColumns + " columns)" ); } } checkPropertyDuplication(); checkColumnDuplication(); } private void checkPropertyDuplication() throws MappingException { final HashSet<String> names = new HashSet<>(); for ( var property : getProperties() ) { if ( !names.add( property.getName() ) ) { throw new MappingException( "Duplicate property mapping of " + property.getName() + " found in " + getEntityName() ); } } } public boolean isDiscriminatorValueNotNull() { return NOT_NULL_DISCRIMINATOR_MAPPING.equals( getDiscriminatorValue() ); } public boolean isDiscriminatorValueNull() { return NULL_DISCRIMINATOR_MAPPING.equals( getDiscriminatorValue() ); } public Map<String, MetaAttribute> getMetaAttributes() { return metaAttributes; } public void setMetaAttributes(java.util.Map<String,MetaAttribute> metas) { this.metaAttributes = metas; } public MetaAttribute getMetaAttribute(String name) { return metaAttributes == null ? null : metaAttributes.get( name ); } @Override public String toString() { return getClass().getSimpleName() + '(' + getEntityName() + ')'; } public List<Join> getJoins() { return joins; } public List<Join> getJoinClosure() { return joins; } public void addJoin(Join join) { if ( !joins.contains( join ) ) { joins.add( join ); } join.setPersistentClass( this ); } public int getJoinClosureSpan() { return joins.size(); } public int getPropertyClosureSpan() { int span = properties.size(); for ( var join : joins ) { span += join.getPropertySpan(); } return span; } public int getJoinNumber(Property prop) { int result = 1; for ( var join : getSubclassJoinClosure() ) { if ( join.containsProperty( prop ) ) { return result; } result++; } return 0; } /** * Build a list of the properties defined on this class. The returned * iterator only accounts for "normal" properties (i.e. non-identifier * properties). * <p> * Differs from {@link #getUnjoinedProperties} in that the returned list * will include properties defined as part of a join. * <p> * Differs from {@link #getReferenceableProperties} in that the properties * defined in superclasses of the mapping inheritance are not included. * * @return A list over the "normal" properties. */ public List<Property> getProperties() { final ArrayList<List<Property>> list = new ArrayList<>(); list.add( properties ); for ( var join : joins ) { list.add( join.getProperties() ); } return new JoinedList<>( list ); } /** * Get a list of the properties defined on this class <b>which * are not defined as part of a join</b>. As with {@link #getProperties}, * the returned iterator only accounts for non-identifier properties. * * @return An iterator over the non-joined "normal" properties. */ public List<Property> getUnjoinedProperties() { return properties; } public void setCustomSQLInsert(String customSQLInsert, boolean callable, ExecuteUpdateResultCheckStyle checkStyle) { this.customSQLInsert = customSQLInsert; this.customInsertCallable = callable; this.insertExpectation = expectationConstructor( checkStyle ); } public String getCustomSQLInsert() { return customSQLInsert; } public boolean isCustomInsertCallable() { return customInsertCallable; } public void setCustomSQLUpdate(String customSQLUpdate, boolean callable, ExecuteUpdateResultCheckStyle checkStyle) { this.customSQLUpdate = customSQLUpdate; this.customUpdateCallable = callable; this.updateExpectation = expectationConstructor( checkStyle ); } public String getCustomSQLUpdate() { return customSQLUpdate; } public boolean isCustomUpdateCallable() { return customUpdateCallable; } public void setCustomSQLDelete(String customSQLDelete, boolean callable, ExecuteUpdateResultCheckStyle checkStyle) { this.customSQLDelete = customSQLDelete; this.customDeleteCallable = callable; this.deleteExpectation = expectationConstructor( checkStyle ); } public String getCustomSQLDelete() { return customSQLDelete; } public boolean isCustomDeleteCallable() { return customDeleteCallable; } public void addFilter( String name, String condition, boolean autoAliasInjection, java.util.Map<String, String> aliasTableMap, java.util.Map<String, String> aliasEntityMap) { filters.add( new FilterConfiguration( name, condition, autoAliasInjection, aliasTableMap, aliasEntityMap, this ) ); } public java.util.List<FilterConfiguration> getFilters() { return filters; } public boolean isForceDiscriminator() { return false; } public abstract boolean isJoinedSubclass(); public String getLoaderName() { return loaderName; } public void setLoaderName(String loaderName) { this.loaderName = loaderName == null ? null : loaderName.intern(); } public abstract Set<String> getSynchronizedTables(); public void addSynchronizedTable(String table) { synchronizedTables.add( table ); } public Boolean isAbstract() { return isAbstract; } public void setAbstract(Boolean isAbstract) { this.isAbstract = isAbstract; } protected List<Property> getNonDuplicatedProperties() { return getUnjoinedProperties(); } protected void checkColumnDuplication() { final String owner = "entity '" + getEntityName() + "'"; final HashSet<String> cols = new HashSet<>(); if ( getIdentifierMapper() == null ) { //an identifier mapper => getKey will be included in the getNonDuplicatedPropertyIterator() //and checked later, so it needs to be excluded getKey().checkColumnDuplication( cols, owner ); } if ( isDiscriminatorInsertable() && getDiscriminator() != null ) { getDiscriminator().checkColumnDuplication( cols, owner ); } final var softDeleteColumn = getRootClass().getSoftDeleteColumn(); if ( softDeleteColumn != null ) { softDeleteColumn.getValue().checkColumnDuplication( cols, owner ); } checkPropertyColumnDuplication( cols, getNonDuplicatedProperties(), owner ); for ( var join : getJoins() ) { cols.clear(); join.getKey().checkColumnDuplication( cols, owner ); checkPropertyColumnDuplication( cols, join.getProperties(), owner ); } } public abstract Object accept(PersistentClassVisitor mv); public String getJpaEntityName() { return jpaEntityName; } public void setJpaEntityName(String jpaEntityName) { this.jpaEntityName = jpaEntityName; } public boolean hasPojoRepresentation() { return getClassName() != null; } public boolean hasSubselectLoadableCollections() { return hasSubselectLoadableCollections; } public void setSubselectLoadableCollections(boolean hasSubselectCollections) { this.hasSubselectLoadableCollections = hasSubselectCollections; } public boolean hasCollectionNotReferencingPK() { return hasCollectionNotReferencingPK( properties ); } private boolean hasCollectionNotReferencingPK(Collection<Property> properties) { for ( var property : properties ) { final var value = property.getValue(); if ( value instanceof Component component ) { if ( hasCollectionNotReferencingPK( component.getProperties() ) ) { return true; } } else if ( value instanceof org.hibernate.mapping.Collection collection ) { if ( !( (CollectionType) collection.getType() ).useLHSPrimaryKey() ) { return true; } } } return false; } public boolean hasPartitionedSelectionMapping() { final var superclass = getSuperclass(); if ( superclass != null && superclass.hasPartitionedSelectionMapping() ) { return true; } for ( var property : getProperties() ) { if ( property.getValue() instanceof BasicValue basicValue && basicValue.isPartitionKey() ) { return true; } } return false; } public Component getIdentifierMapper() { return identifierMapper; } public Component getDeclaredIdentifierMapper() { return declaredIdentifierMapper; } public void setDeclaredIdentifierMapper(Component declaredIdentifierMapper) { this.declaredIdentifierMapper = declaredIdentifierMapper; } public boolean hasIdentifierMapper() { return identifierMapper != null; } public void addCallbackDefinitions(java.util.List<CallbackDefinition> callbackDefinitions) { if ( callbackDefinitions != null && !callbackDefinitions.isEmpty() ) { if ( this.callbackDefinitions == null ) { this.callbackDefinitions = new ArrayList<>(); } this.callbackDefinitions.addAll( callbackDefinitions ); } } public java.util.List<CallbackDefinition> getCallbackDefinitions() { return callbackDefinitions == null ? emptyList() : unmodifiableList( callbackDefinitions ); } public void setIdentifierMapper(Component handle) { this.identifierMapper = handle; } private Boolean hasNaturalId; public boolean hasNaturalId() { if ( hasNaturalId == null ) { hasNaturalId = determineIfNaturalIdDefined(); } return hasNaturalId; } private boolean determineIfNaturalIdDefined() { final List<Property> properties = getRootClass().getProperties(); for ( var property : properties ) { if ( property.isNaturalIdentifier() ) { return true; } } return false; } // The following methods are added to support @MappedSuperclass in the metamodel public List<Property> getDeclaredProperties() { final ArrayList<List<Property>> lists = new ArrayList<>(); lists.add( declaredProperties ); for ( var join : joins ) { lists.add( join.getDeclaredProperties() ); } return new JoinedList<>( lists ); } public void addMappedSuperclassProperty(Property property) { properties.add( property ); property.setPersistentClass( this ); } public MappedSuperclass getSuperMappedSuperclass() { return superMappedSuperclass; } public void setSuperMappedSuperclass(MappedSuperclass superMappedSuperclass) { this.superMappedSuperclass = superMappedSuperclass; } public void assignCheckConstraintsToTable(Dialect dialect, TypeConfiguration types) { for ( var checkConstraint : checkConstraints ) { container( collectColumnNames( checkConstraint.getConstraint(), dialect, types ) ) .getTable().addCheck( checkConstraint ); } } // End of @MappedSuperclass support public void prepareForMappingModel(RuntimeModelCreationContext context) { if ( !joins.isEmpty() ) { // we need to deal with references to secondary tables // in SQL formulas final var dialect = context.getDialect(); final var types = context.getTypeConfiguration(); // now, move @Formulas to the correct AttributeContainers //TODO: skip this step for hbm.xml for ( var property : new ArrayList<>( properties ) ) { for ( var selectable : property.getSelectables() ) { if ( selectable.isFormula() && properties.contains( property ) ) { final var formula = (Formula) selectable; final var container = container( collectColumnNames( formula.getTemplate( dialect, types ) ) ); if ( !container.contains( property ) ) { properties.remove( property ); container.addProperty( property ); break; //TODO: embeddables } } } } } properties.sort( comparing( Property::getName ) ); } private AttributeContainer container(List<String> constrainedColumnNames) { final long matches = matchesInTable( constrainedColumnNames, getTable() ); if ( matches == constrainedColumnNames.size() ) { // perfect, all columns matched in the primary table return this; } else { // go searching for a secondary table which better matches AttributeContainer result = this; long max = matches; for ( var join : getJoins() ) { long secondaryMatches = matchesInTable( constrainedColumnNames, join.getTable() ); if ( secondaryMatches > max ) { result = join; max = secondaryMatches; } } return result; } } private static long matchesInTable(List<String> names, Table table) { return table.getColumns().stream() .filter( col -> col.isQuoted() ? names.contains( col.getName() ) : names.stream().anyMatch( name -> name.equalsIgnoreCase( col.getName() ) ) ) .count(); } public void addCheckConstraint(CheckConstraint checkConstraint) { checkConstraints.add( checkConstraint ); } public List<CheckConstraint> getCheckConstraints() { return checkConstraints; } public Table getImplicitTable() { return getTable(); } @Override public Table findTable(String name) { if ( getTable().getName().equals( name ) ) { return getTable(); } final var secondaryTable = findSecondaryTable( name ); if ( secondaryTable != null ) { return secondaryTable.getTable(); } return null; } @Override public Table getTable(String name) { final var table = findTable( name ); if ( table == null ) { throw new MappingException( "Could not locate Table : " + name ); } return table; } @Override public Join findSecondaryTable(String name) { for ( int i = 0; i < joins.size(); i++ ) { final var join = joins.get( i ); if ( join.getTable().getNameIdentifier().matches( name ) ) { return join; } } return null; } @Override public Join getSecondaryTable(String name) { final var secondaryTable = findSecondaryTable( name ); if ( secondaryTable == null ) { throw new MappingException( "Could not locate secondary Table : " + name ); } return secondaryTable; } @Override public IdentifiableTypeClass getSuperType() { final var superPersistentClass = getSuperclass(); if ( superPersistentClass != null ) { return superPersistentClass; } return superMappedSuperclass; } @Override public List<IdentifiableTypeClass> getSubTypes() { throw new UnsupportedOperationException( "Not implemented yet" ); } @Override @Deprecated(forRemoval = true) public void applyProperty(Property property) { final var table = property.getValue().getTable(); if ( table.equals( getImplicitTable() ) ) { addProperty( property ); } else { final var secondaryTable = getSecondaryTable( table.getName() ); secondaryTable.addProperty( property ); } } private boolean containsColumn(Column column) { for ( var declaredProperty : declaredProperties ) { if ( declaredProperty.getSelectables().contains( column ) ) { return true; } } return false; } @Internal public boolean isDefinedOnMultipleSubclasses(Column column) { PersistentClass declaringType = null; for ( var persistentClass : getSubclassClosure() ) { if ( persistentClass.containsColumn( column ) ) { if ( declaringType != null && declaringType != persistentClass ) { return true; } else { declaringType = persistentClass; } } } return false; } @Internal public PersistentClass getSuperPersistentClass() { final var superclass = getSuperclass(); return superclass == null ? getSuperPersistentClass( getSuperMappedSuperclass() ) : superclass; } private static PersistentClass getSuperPersistentClass(MappedSuperclass mappedSuperclass) { if ( mappedSuperclass != null ) { final var superclass = mappedSuperclass.getSuperPersistentClass(); return superclass == null ? getSuperPersistentClass( mappedSuperclass.getSuperMappedSuperclass() ) : superclass; } return null; } public Supplier<? extends Expectation> getInsertExpectation() { return insertExpectation; } public void setInsertExpectation(Supplier<? extends Expectation> insertExpectation) { this.insertExpectation = insertExpectation; } public Supplier<? extends Expectation> getUpdateExpectation() { return updateExpectation; } public void setUpdateExpectation(Supplier<? extends Expectation> updateExpectation) { this.updateExpectation = updateExpectation; } public Supplier<? extends Expectation> getDeleteExpectation() { return deleteExpectation; } public void setDeleteExpectation(Supplier<? extends Expectation> deleteExpectation) { this.deleteExpectation = deleteExpectation; } public void removeProperty(Property property) { if ( !declaredProperties.remove( property ) ) { throw new IllegalArgumentException( "Property not among declared properties: " + property.getName() ); } properties.remove( property ); } public void createConstraints(MetadataBuildingContext context) { } }
googleapis/google-cloud-java
37,833
java-analytics-admin/proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/ListGoogleAdsLinksResponse.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 ListGoogleAdsLinks RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.ListGoogleAdsLinksResponse} */ public final class ListGoogleAdsLinksResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.ListGoogleAdsLinksResponse) ListGoogleAdsLinksResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListGoogleAdsLinksResponse.newBuilder() to construct. private ListGoogleAdsLinksResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListGoogleAdsLinksResponse() { googleAdsLinks_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListGoogleAdsLinksResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListGoogleAdsLinksResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListGoogleAdsLinksResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.class, com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.Builder.class); } public static final int GOOGLE_ADS_LINKS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.analytics.admin.v1beta.GoogleAdsLink> googleAdsLinks_; /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ @java.lang.Override public java.util.List<com.google.analytics.admin.v1beta.GoogleAdsLink> getGoogleAdsLinksList() { return googleAdsLinks_; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder> getGoogleAdsLinksOrBuilderList() { return googleAdsLinks_; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ @java.lang.Override public int getGoogleAdsLinksCount() { return googleAdsLinks_.size(); } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1beta.GoogleAdsLink getGoogleAdsLinks(int index) { return googleAdsLinks_.get(index); } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder getGoogleAdsLinksOrBuilder( int index) { return googleAdsLinks_.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 < googleAdsLinks_.size(); i++) { output.writeMessage(1, googleAdsLinks_.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 < googleAdsLinks_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, googleAdsLinks_.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.ListGoogleAdsLinksResponse)) { return super.equals(obj); } com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse other = (com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse) obj; if (!getGoogleAdsLinksList().equals(other.getGoogleAdsLinksList())) 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 (getGoogleAdsLinksCount() > 0) { hash = (37 * hash) + GOOGLE_ADS_LINKS_FIELD_NUMBER; hash = (53 * hash) + getGoogleAdsLinksList().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.ListGoogleAdsLinksResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse 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 ListGoogleAdsLinks RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.ListGoogleAdsLinksResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.ListGoogleAdsLinksResponse) com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListGoogleAdsLinksResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListGoogleAdsLinksResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.class, com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.Builder.class); } // Construct using com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (googleAdsLinksBuilder_ == null) { googleAdsLinks_ = java.util.Collections.emptyList(); } else { googleAdsLinks_ = null; googleAdsLinksBuilder_.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_ListGoogleAdsLinksResponse_descriptor; } @java.lang.Override public com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse getDefaultInstanceForType() { return com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse build() { com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse buildPartial() { com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse result = new com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse result) { if (googleAdsLinksBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { googleAdsLinks_ = java.util.Collections.unmodifiableList(googleAdsLinks_); bitField0_ = (bitField0_ & ~0x00000001); } result.googleAdsLinks_ = googleAdsLinks_; } else { result.googleAdsLinks_ = googleAdsLinksBuilder_.build(); } } private void buildPartial0( com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse 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.ListGoogleAdsLinksResponse) { return mergeFrom((com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse other) { if (other == com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse.getDefaultInstance()) return this; if (googleAdsLinksBuilder_ == null) { if (!other.googleAdsLinks_.isEmpty()) { if (googleAdsLinks_.isEmpty()) { googleAdsLinks_ = other.googleAdsLinks_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.addAll(other.googleAdsLinks_); } onChanged(); } } else { if (!other.googleAdsLinks_.isEmpty()) { if (googleAdsLinksBuilder_.isEmpty()) { googleAdsLinksBuilder_.dispose(); googleAdsLinksBuilder_ = null; googleAdsLinks_ = other.googleAdsLinks_; bitField0_ = (bitField0_ & ~0x00000001); googleAdsLinksBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getGoogleAdsLinksFieldBuilder() : null; } else { googleAdsLinksBuilder_.addAllMessages(other.googleAdsLinks_); } } } 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.GoogleAdsLink m = input.readMessage( com.google.analytics.admin.v1beta.GoogleAdsLink.parser(), extensionRegistry); if (googleAdsLinksBuilder_ == null) { ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.add(m); } else { googleAdsLinksBuilder_.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.GoogleAdsLink> googleAdsLinks_ = java.util.Collections.emptyList(); private void ensureGoogleAdsLinksIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { googleAdsLinks_ = new java.util.ArrayList<com.google.analytics.admin.v1beta.GoogleAdsLink>( googleAdsLinks_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1beta.GoogleAdsLink, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder, com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder> googleAdsLinksBuilder_; /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public java.util.List<com.google.analytics.admin.v1beta.GoogleAdsLink> getGoogleAdsLinksList() { if (googleAdsLinksBuilder_ == null) { return java.util.Collections.unmodifiableList(googleAdsLinks_); } else { return googleAdsLinksBuilder_.getMessageList(); } } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public int getGoogleAdsLinksCount() { if (googleAdsLinksBuilder_ == null) { return googleAdsLinks_.size(); } else { return googleAdsLinksBuilder_.getCount(); } } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public com.google.analytics.admin.v1beta.GoogleAdsLink getGoogleAdsLinks(int index) { if (googleAdsLinksBuilder_ == null) { return googleAdsLinks_.get(index); } else { return googleAdsLinksBuilder_.getMessage(index); } } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder setGoogleAdsLinks( int index, com.google.analytics.admin.v1beta.GoogleAdsLink value) { if (googleAdsLinksBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.set(index, value); onChanged(); } else { googleAdsLinksBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder setGoogleAdsLinks( int index, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder builderForValue) { if (googleAdsLinksBuilder_ == null) { ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.set(index, builderForValue.build()); onChanged(); } else { googleAdsLinksBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder addGoogleAdsLinks(com.google.analytics.admin.v1beta.GoogleAdsLink value) { if (googleAdsLinksBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.add(value); onChanged(); } else { googleAdsLinksBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder addGoogleAdsLinks( int index, com.google.analytics.admin.v1beta.GoogleAdsLink value) { if (googleAdsLinksBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.add(index, value); onChanged(); } else { googleAdsLinksBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder addGoogleAdsLinks( com.google.analytics.admin.v1beta.GoogleAdsLink.Builder builderForValue) { if (googleAdsLinksBuilder_ == null) { ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.add(builderForValue.build()); onChanged(); } else { googleAdsLinksBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder addGoogleAdsLinks( int index, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder builderForValue) { if (googleAdsLinksBuilder_ == null) { ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.add(index, builderForValue.build()); onChanged(); } else { googleAdsLinksBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder addAllGoogleAdsLinks( java.lang.Iterable<? extends com.google.analytics.admin.v1beta.GoogleAdsLink> values) { if (googleAdsLinksBuilder_ == null) { ensureGoogleAdsLinksIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, googleAdsLinks_); onChanged(); } else { googleAdsLinksBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder clearGoogleAdsLinks() { if (googleAdsLinksBuilder_ == null) { googleAdsLinks_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { googleAdsLinksBuilder_.clear(); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public Builder removeGoogleAdsLinks(int index) { if (googleAdsLinksBuilder_ == null) { ensureGoogleAdsLinksIsMutable(); googleAdsLinks_.remove(index); onChanged(); } else { googleAdsLinksBuilder_.remove(index); } return this; } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public com.google.analytics.admin.v1beta.GoogleAdsLink.Builder getGoogleAdsLinksBuilder( int index) { return getGoogleAdsLinksFieldBuilder().getBuilder(index); } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder getGoogleAdsLinksOrBuilder( int index) { if (googleAdsLinksBuilder_ == null) { return googleAdsLinks_.get(index); } else { return googleAdsLinksBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public java.util.List<? extends com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder> getGoogleAdsLinksOrBuilderList() { if (googleAdsLinksBuilder_ != null) { return googleAdsLinksBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(googleAdsLinks_); } } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public com.google.analytics.admin.v1beta.GoogleAdsLink.Builder addGoogleAdsLinksBuilder() { return getGoogleAdsLinksFieldBuilder() .addBuilder(com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()); } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public com.google.analytics.admin.v1beta.GoogleAdsLink.Builder addGoogleAdsLinksBuilder( int index) { return getGoogleAdsLinksFieldBuilder() .addBuilder(index, com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()); } /** * * * <pre> * List of GoogleAdsLinks. * </pre> * * <code>repeated .google.analytics.admin.v1beta.GoogleAdsLink google_ads_links = 1;</code> */ public java.util.List<com.google.analytics.admin.v1beta.GoogleAdsLink.Builder> getGoogleAdsLinksBuilderList() { return getGoogleAdsLinksFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1beta.GoogleAdsLink, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder, com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder> getGoogleAdsLinksFieldBuilder() { if (googleAdsLinksBuilder_ == null) { googleAdsLinksBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1beta.GoogleAdsLink, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder, com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder>( googleAdsLinks_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); googleAdsLinks_ = null; } return googleAdsLinksBuilder_; } 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.ListGoogleAdsLinksResponse) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.ListGoogleAdsLinksResponse) private static final com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse(); } public static com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListGoogleAdsLinksResponse> PARSER = new com.google.protobuf.AbstractParser<ListGoogleAdsLinksResponse>() { @java.lang.Override public ListGoogleAdsLinksResponse 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<ListGoogleAdsLinksResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListGoogleAdsLinksResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1beta.ListGoogleAdsLinksResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/pulsar
38,261
pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/rest/api/SourcesImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.functions.worker.rest.api; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.pulsar.functions.auth.FunctionAuthUtils.getFunctionAuthData; import static org.apache.pulsar.functions.utils.FunctionCommon.isFunctionCodeBuiltin; import static org.apache.pulsar.functions.worker.rest.RestUtils.throwUnavailableException; import com.google.protobuf.ByteString; import java.io.File; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.pulsar.broker.authentication.AuthenticationParameters; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.common.functions.UpdateOptionsImpl; import org.apache.pulsar.common.functions.Utils; import org.apache.pulsar.common.io.ConfigFieldDefinition; import org.apache.pulsar.common.io.ConnectorDefinition; import org.apache.pulsar.common.io.SourceConfig; import org.apache.pulsar.common.policies.data.ExceptionInformation; import org.apache.pulsar.common.policies.data.SourceStatus; import org.apache.pulsar.common.util.RestException; import org.apache.pulsar.functions.auth.FunctionAuthData; import org.apache.pulsar.functions.instance.InstanceUtils; import org.apache.pulsar.functions.proto.Function; import org.apache.pulsar.functions.proto.InstanceCommunication; import org.apache.pulsar.functions.utils.ComponentTypeUtils; import org.apache.pulsar.functions.utils.FunctionFilePackage; import org.apache.pulsar.functions.utils.FunctionMetaDataUtils; import org.apache.pulsar.functions.utils.SourceConfigUtils; import org.apache.pulsar.functions.utils.ValidatableFunctionPackage; import org.apache.pulsar.functions.utils.io.Connector; import org.apache.pulsar.functions.worker.FunctionMetaDataManager; import org.apache.pulsar.functions.worker.PulsarWorkerService; import org.apache.pulsar.functions.worker.WorkerConfig; import org.apache.pulsar.functions.worker.WorkerUtils; import org.apache.pulsar.functions.worker.service.api.Sources; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; @Slf4j public class SourcesImpl extends ComponentImpl implements Sources<PulsarWorkerService> { public SourcesImpl(Supplier<PulsarWorkerService> workerServiceSupplier) { super(workerServiceSupplier, Function.FunctionDetails.ComponentType.SOURCE); } @Override public void registerSource(final String tenant, final String namespace, final String sourceName, final InputStream uploadedInputStream, final FormDataContentDisposition fileDetail, final String sourcePkgUrl, final SourceConfig sourceConfig, final AuthenticationParameters authParams) { if (!isWorkerServiceAvailable()) { throwUnavailableException(); } if (tenant == null) { throw new RestException(Response.Status.BAD_REQUEST, "Tenant is not provided"); } if (namespace == null) { throw new RestException(Response.Status.BAD_REQUEST, "Namespace is not provided"); } if (sourceName == null) { throw new RestException(Response.Status.BAD_REQUEST, "Source name is not provided"); } if (sourceConfig == null) { throw new RestException(Response.Status.BAD_REQUEST, "Source config is not provided"); } throwRestExceptionIfUnauthorizedForNamespace(tenant, namespace, sourceName, "register", authParams); try { // Check tenant exists worker().getBrokerAdmin().tenants().getTenantInfo(tenant); String qualifiedNamespace = tenant + "/" + namespace; List<String> namespaces = worker().getBrokerAdmin().namespaces().getNamespaces(tenant); if (namespaces != null && !namespaces.contains(qualifiedNamespace)) { String qualifiedNamespaceWithCluster = String.format("%s/%s/%s", tenant, worker().getWorkerConfig().getPulsarFunctionsCluster(), namespace); if (namespaces != null && !namespaces.contains(qualifiedNamespaceWithCluster)) { log.error("{}/{}/{} Namespace {} does not exist", tenant, namespace, sourceName, namespace); throw new RestException(Response.Status.BAD_REQUEST, "Namespace does not exist"); } } } catch (PulsarAdminException.NotAuthorizedException e) { log.error("{}/{}/{} Client is not authorized to operate {} on tenant", tenant, namespace, sourceName, ComponentTypeUtils.toString(componentType)); throw new RestException(Response.Status.UNAUTHORIZED, "Client is not authorized to perform operation"); } catch (PulsarAdminException.NotFoundException e) { log.error("{}/{}/{} Tenant {} does not exist", tenant, namespace, sourceName, tenant); throw new RestException(Response.Status.BAD_REQUEST, "Tenant does not exist"); } catch (PulsarAdminException e) { log.error("{}/{}/{} Issues getting tenant data", tenant, namespace, sourceName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); } FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager(); if (functionMetaDataManager.containsFunction(tenant, namespace, sourceName)) { log.error("{} {}/{}/{} already exists", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName); throw new RestException(Response.Status.BAD_REQUEST, String.format("%s %s already exists", ComponentTypeUtils.toString(componentType), sourceName)); } Function.FunctionDetails functionDetails = null; boolean isPkgUrlProvided = isNotBlank(sourcePkgUrl); File componentPackageFile = null; try { // validate parameters try { if (isPkgUrlProvided) { componentPackageFile = getPackageFile(componentType, sourcePkgUrl); functionDetails = validateUpdateRequestParams(tenant, namespace, sourceName, sourceConfig, componentPackageFile); } else { if (uploadedInputStream != null) { componentPackageFile = WorkerUtils.dumpToTmpFile(uploadedInputStream); } functionDetails = validateUpdateRequestParams(tenant, namespace, sourceName, sourceConfig, componentPackageFile); if (!isFunctionCodeBuiltin(functionDetails) && (componentPackageFile == null || fileDetail == null)) { throw new IllegalArgumentException( ComponentTypeUtils.toString(componentType) + " Package is not provided"); } } } catch (Exception e) { log.error("Invalid register {} request @ /{}/{}/{}", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName, e); throw new RestException(Response.Status.BAD_REQUEST, e.getMessage()); } try { worker().getFunctionRuntimeManager().getRuntimeFactory().doAdmissionChecks(functionDetails); } catch (Exception e) { log.error("{} {}/{}/{} cannot be admitted by the runtime factory", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName); throw new RestException(Response.Status.BAD_REQUEST, String.format("%s %s cannot be admitted:- %s", ComponentTypeUtils.toString(componentType), sourceName, e.getMessage())); } // function state Function.FunctionMetaData.Builder functionMetaDataBuilder = Function.FunctionMetaData.newBuilder() .setFunctionDetails(functionDetails) .setCreateTime(System.currentTimeMillis()) .setVersion(0); // cache auth if need if (worker().getWorkerConfig().isAuthenticationEnabled()) { Function.FunctionDetails finalFunctionDetails = functionDetails; worker().getFunctionRuntimeManager() .getRuntimeFactory() .getAuthProvider().ifPresent(functionAuthProvider -> { if (authParams.getClientAuthenticationDataSource() != null) { try { Optional<FunctionAuthData> functionAuthData = functionAuthProvider .cacheAuthData(finalFunctionDetails, authParams.getClientAuthenticationDataSource()); functionAuthData.ifPresent(authData -> functionMetaDataBuilder.setFunctionAuthSpec( Function.FunctionAuthenticationSpec.newBuilder() .setData(ByteString.copyFrom(authData.getData())) .build())); } catch (Exception e) { log.error("Error caching authentication data for {} {}/{}/{}", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, String.format("Error caching authentication data for %s %s:- %s", ComponentTypeUtils.toString(componentType), sourceName, e.getMessage())); } } }); } Function.PackageLocationMetaData.Builder packageLocationMetaDataBuilder; try { packageLocationMetaDataBuilder = getFunctionPackageLocation(functionMetaDataBuilder.build(), sourcePkgUrl, fileDetail, componentPackageFile); } catch (Exception e) { log.error("Failed process {} {}/{}/{} package: ", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); } functionMetaDataBuilder.setPackageLocation(packageLocationMetaDataBuilder); updateRequest(null, functionMetaDataBuilder.build()); } finally { if (componentPackageFile != null && componentPackageFile.exists()) { if (sourcePkgUrl == null || !sourcePkgUrl.startsWith(Utils.FILE)) { componentPackageFile.delete(); } } } } @Override public void updateSource(final String tenant, final String namespace, final String sourceName, final InputStream uploadedInputStream, final FormDataContentDisposition fileDetail, final String sourcePkgUrl, final SourceConfig sourceConfig, final AuthenticationParameters authParams, UpdateOptionsImpl updateOptions) { if (!isWorkerServiceAvailable()) { throwUnavailableException(); } if (tenant == null) { throw new RestException(Response.Status.BAD_REQUEST, "Tenant is not provided"); } if (namespace == null) { throw new RestException(Response.Status.BAD_REQUEST, "Namespace is not provided"); } if (sourceName == null) { throw new RestException(Response.Status.BAD_REQUEST, "Source name is not provided"); } if (sourceConfig == null) { throw new RestException(Response.Status.BAD_REQUEST, "Source config is not provided"); } throwRestExceptionIfUnauthorizedForNamespace(tenant, namespace, sourceName, "update", authParams); FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager(); if (!functionMetaDataManager.containsFunction(tenant, namespace, sourceName)) { throw new RestException(Response.Status.BAD_REQUEST, String.format("%s %s doesn't exist", ComponentTypeUtils.toString(componentType), sourceName)); } Function.FunctionMetaData existingComponent = functionMetaDataManager.getFunctionMetaData(tenant, namespace, sourceName); if (!InstanceUtils.calculateSubjectType(existingComponent.getFunctionDetails()).equals(componentType)) { log.error("{}/{}/{} is not a {}", tenant, namespace, sourceName, ComponentTypeUtils.toString(componentType)); throw new RestException(Response.Status.NOT_FOUND, String.format("%s %s doesn't exist", ComponentTypeUtils.toString(componentType), sourceName)); } SourceConfig existingSourceConfig = SourceConfigUtils.convertFromDetails(existingComponent.getFunctionDetails()); // The rest end points take precedence over whatever is there in functionconfig sourceConfig.setTenant(tenant); sourceConfig.setNamespace(namespace); sourceConfig.setName(sourceName); SourceConfig mergedConfig; try { mergedConfig = SourceConfigUtils.validateUpdate(existingSourceConfig, sourceConfig); } catch (Exception e) { throw new RestException(Response.Status.BAD_REQUEST, e.getMessage()); } if (existingSourceConfig.equals(mergedConfig) && isBlank(sourcePkgUrl) && uploadedInputStream == null && (updateOptions == null || !updateOptions.isUpdateAuthData())) { log.error("{}/{}/{} Update contains no changes", tenant, namespace, sourceName); throw new RestException(Response.Status.BAD_REQUEST, "Update contains no change"); } Function.FunctionDetails functionDetails; File componentPackageFile = null; try { // validate parameters try { componentPackageFile = getPackageFile( componentType, sourcePkgUrl, existingComponent.getPackageLocation().getPackagePath(), uploadedInputStream); functionDetails = validateUpdateRequestParams(tenant, namespace, sourceName, mergedConfig, componentPackageFile); if (existingComponent.getPackageLocation().getPackagePath().startsWith(Utils.BUILTIN) && !isFunctionCodeBuiltin(functionDetails) && (componentPackageFile == null || fileDetail == null)) { throw new IllegalArgumentException(ComponentTypeUtils.toString(componentType) + " Package is not provided"); } } catch (Exception e) { log.error("Invalid update {} request @ /{}/{}/{}", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName, e); throw new RestException(Response.Status.BAD_REQUEST, e.getMessage()); } try { worker().getFunctionRuntimeManager().getRuntimeFactory().doAdmissionChecks(functionDetails); } catch (Exception e) { log.error("Updated {} {}/{}/{} cannot be submitted to runtime factory", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName); throw new RestException(Response.Status.BAD_REQUEST, String.format("%s %s cannot be admitted:- %s", ComponentTypeUtils.toString(componentType), sourceName, e.getMessage())); } // merge from existing metadata Function.FunctionMetaData.Builder functionMetaDataBuilder = Function.FunctionMetaData.newBuilder().mergeFrom(existingComponent) .setFunctionDetails(functionDetails); // update auth data if need if (worker().getWorkerConfig().isAuthenticationEnabled()) { Function.FunctionDetails finalFunctionDetails = functionDetails; worker().getFunctionRuntimeManager() .getRuntimeFactory() .getAuthProvider().ifPresent(functionAuthProvider -> { if (authParams.getClientAuthenticationDataSource() != null && updateOptions != null && updateOptions.isUpdateAuthData()) { // get existing auth data if it exists Optional<FunctionAuthData> existingFunctionAuthData = Optional.empty(); if (functionMetaDataBuilder.hasFunctionAuthSpec()) { existingFunctionAuthData = Optional.ofNullable(getFunctionAuthData( Optional.ofNullable(functionMetaDataBuilder.getFunctionAuthSpec()))); } try { Optional<FunctionAuthData> newFunctionAuthData = functionAuthProvider .updateAuthData(finalFunctionDetails, existingFunctionAuthData, authParams.getClientAuthenticationDataSource()); if (newFunctionAuthData.isPresent()) { functionMetaDataBuilder.setFunctionAuthSpec( Function.FunctionAuthenticationSpec.newBuilder() .setData(ByteString.copyFrom(newFunctionAuthData.get().getData())) .build()); } else { functionMetaDataBuilder.clearFunctionAuthSpec(); } } catch (Exception e) { log.error("Error updating authentication data for {} {}/{}/{}", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, String.format("Error caching authentication data for %s %s:- %s", ComponentTypeUtils.toString(componentType), sourceName, e.getMessage())); } } }); } Function.PackageLocationMetaData.Builder packageLocationMetaDataBuilder; if (isNotBlank(sourcePkgUrl) || uploadedInputStream != null) { Function.FunctionMetaData metaData = functionMetaDataBuilder.build(); metaData = FunctionMetaDataUtils.incrMetadataVersion(metaData, metaData); try { packageLocationMetaDataBuilder = getFunctionPackageLocation(metaData, sourcePkgUrl, fileDetail, componentPackageFile); } catch (Exception e) { log.error("Failed process {} {}/{}/{} package: ", ComponentTypeUtils.toString(componentType), tenant, namespace, sourceName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); } } else { packageLocationMetaDataBuilder = Function.PackageLocationMetaData.newBuilder().mergeFrom(existingComponent.getPackageLocation()); } functionMetaDataBuilder.setPackageLocation(packageLocationMetaDataBuilder); updateRequest(existingComponent, functionMetaDataBuilder.build()); } finally { if (componentPackageFile != null && componentPackageFile.exists()) { if ((sourcePkgUrl != null && !sourcePkgUrl.startsWith(Utils.FILE)) || uploadedInputStream != null) { componentPackageFile.delete(); } } } } private class GetSourceStatus extends GetStatus<SourceStatus, SourceStatus.SourceInstanceStatus.SourceInstanceStatusData> { @Override public SourceStatus.SourceInstanceStatus.SourceInstanceStatusData notScheduledInstance() { SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData = new SourceStatus.SourceInstanceStatus.SourceInstanceStatusData(); sourceInstanceStatusData.setRunning(false); sourceInstanceStatusData.setError("Source has not been scheduled"); return sourceInstanceStatusData; } @Override public SourceStatus.SourceInstanceStatus.SourceInstanceStatusData fromFunctionStatusProto( InstanceCommunication.FunctionStatus status, String assignedWorkerId) { SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData = new SourceStatus.SourceInstanceStatus.SourceInstanceStatusData(); sourceInstanceStatusData.setRunning(status.getRunning()); sourceInstanceStatusData.setError(status.getFailureException()); sourceInstanceStatusData.setNumRestarts(status.getNumRestarts()); sourceInstanceStatusData.setNumReceivedFromSource(status.getNumReceived()); sourceInstanceStatusData.setNumSourceExceptions(status.getNumSourceExceptions()); List<ExceptionInformation> sourceExceptionInformationList = new LinkedList<>(); for (InstanceCommunication.FunctionStatus.ExceptionInformation exceptionEntry : status.getLatestSourceExceptionsList()) { ExceptionInformation exceptionInformation = new ExceptionInformation(); exceptionInformation.setTimestampMs(exceptionEntry.getMsSinceEpoch()); exceptionInformation.setExceptionString(exceptionEntry.getExceptionString()); sourceExceptionInformationList.add(exceptionInformation); } sourceInstanceStatusData.setLatestSourceExceptions(sourceExceptionInformationList); // Source treats all system and sink exceptions as system exceptions sourceInstanceStatusData.setNumSystemExceptions(status.getNumSystemExceptions() + status.getNumUserExceptions() + status.getNumSinkExceptions()); List<ExceptionInformation> systemExceptionInformationList = new LinkedList<>(); for (InstanceCommunication.FunctionStatus.ExceptionInformation exceptionEntry : status.getLatestUserExceptionsList()) { ExceptionInformation exceptionInformation = new ExceptionInformation(); exceptionInformation.setTimestampMs(exceptionEntry.getMsSinceEpoch()); exceptionInformation.setExceptionString(exceptionEntry.getExceptionString()); systemExceptionInformationList.add(exceptionInformation); } for (InstanceCommunication.FunctionStatus.ExceptionInformation exceptionEntry : status.getLatestSystemExceptionsList()) { ExceptionInformation exceptionInformation = new ExceptionInformation(); exceptionInformation.setTimestampMs(exceptionEntry.getMsSinceEpoch()); exceptionInformation.setExceptionString(exceptionEntry.getExceptionString()); systemExceptionInformationList.add(exceptionInformation); } for (InstanceCommunication.FunctionStatus.ExceptionInformation exceptionEntry : status.getLatestSinkExceptionsList()) { ExceptionInformation exceptionInformation = new ExceptionInformation(); exceptionInformation.setTimestampMs(exceptionEntry.getMsSinceEpoch()); exceptionInformation.setExceptionString(exceptionEntry.getExceptionString()); systemExceptionInformationList.add(exceptionInformation); } sourceInstanceStatusData.setLatestSystemExceptions(systemExceptionInformationList); sourceInstanceStatusData.setNumWritten(status.getNumSuccessfullyProcessed()); sourceInstanceStatusData.setLastReceivedTime(status.getLastInvocationTime()); sourceInstanceStatusData.setWorkerId(assignedWorkerId); return sourceInstanceStatusData; } @Override public SourceStatus.SourceInstanceStatus.SourceInstanceStatusData notRunning(String assignedWorkerId, String error) { SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData = new SourceStatus.SourceInstanceStatus.SourceInstanceStatusData(); sourceInstanceStatusData.setRunning(false); if (error != null) { sourceInstanceStatusData.setError(error); } sourceInstanceStatusData.setWorkerId(assignedWorkerId); return sourceInstanceStatusData; } @Override public SourceStatus getStatus(final String tenant, final String namespace, final String name, final Collection<Function.Assignment> assignments, final URI uri) throws PulsarAdminException { SourceStatus sourceStatus = new SourceStatus(); for (Function.Assignment assignment : assignments) { boolean isOwner = worker().getWorkerConfig().getWorkerId().equals(assignment.getWorkerId()); SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData; if (isOwner) { sourceInstanceStatusData = getComponentInstanceStatus(tenant, namespace, name, assignment.getInstance().getInstanceId(), null); } else { sourceInstanceStatusData = worker().getFunctionAdmin().sources().getSourceStatus( assignment.getInstance().getFunctionMetaData().getFunctionDetails().getTenant(), assignment.getInstance().getFunctionMetaData().getFunctionDetails().getNamespace(), assignment.getInstance().getFunctionMetaData().getFunctionDetails().getName(), assignment.getInstance().getInstanceId()); } SourceStatus.SourceInstanceStatus instanceStatus = new SourceStatus.SourceInstanceStatus(); instanceStatus.setInstanceId(assignment.getInstance().getInstanceId()); instanceStatus.setStatus(sourceInstanceStatusData); sourceStatus.addInstance(instanceStatus); } sourceStatus.setNumInstances(sourceStatus.instances.size()); sourceStatus.getInstances().forEach(sourceInstanceStatus -> { if (sourceInstanceStatus.getStatus().isRunning()) { sourceStatus.numRunning++; } }); return sourceStatus; } @Override public SourceStatus getStatusExternal(final String tenant, final String namespace, final String name, final int parallelism) { SourceStatus sinkStatus = new SourceStatus(); for (int i = 0; i < parallelism; ++i) { SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData = getComponentInstanceStatus(tenant, namespace, name, i, null); SourceStatus.SourceInstanceStatus sourceInstanceStatus = new SourceStatus.SourceInstanceStatus(); sourceInstanceStatus.setInstanceId(i); sourceInstanceStatus.setStatus(sourceInstanceStatusData); sinkStatus.addInstance(sourceInstanceStatus); } sinkStatus.setNumInstances(sinkStatus.instances.size()); sinkStatus.getInstances().forEach(sourceInstanceStatus -> { if (sourceInstanceStatus.getStatus().isRunning()) { sinkStatus.numRunning++; } }); return sinkStatus; } @Override public SourceStatus emptyStatus(final int parallelism) { SourceStatus sourceStatus = new SourceStatus(); sourceStatus.setNumInstances(parallelism); sourceStatus.setNumRunning(0); for (int i = 0; i < parallelism; i++) { SourceStatus.SourceInstanceStatus sourceInstanceStatus = new SourceStatus.SourceInstanceStatus(); sourceInstanceStatus.setInstanceId(i); SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData = new SourceStatus.SourceInstanceStatus.SourceInstanceStatusData(); sourceInstanceStatusData.setRunning(false); sourceInstanceStatusData.setError("Source has not been scheduled"); sourceInstanceStatus.setStatus(sourceInstanceStatusData); sourceStatus.addInstance(sourceInstanceStatus); } return sourceStatus; } } @Override public SourceStatus getSourceStatus(final String tenant, final String namespace, final String componentName, final URI uri, final AuthenticationParameters authParams) { // validate parameters componentStatusRequestValidate(tenant, namespace, componentName, authParams); SourceStatus sourceStatus; try { sourceStatus = new GetSourceStatus().getComponentStatus(tenant, namespace, componentName, uri); } catch (WebApplicationException we) { throw we; } catch (Exception e) { log.error("{}/{}/{} Got Exception Getting Status", tenant, namespace, componentName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); } return sourceStatus; } @Override public SourceStatus.SourceInstanceStatus.SourceInstanceStatusData getSourceInstanceStatus(final String tenant, final String namespace, final String sourceName, final String instanceId, final URI uri, final AuthenticationParameters authParams) { // validate parameters componentInstanceStatusRequestValidate(tenant, namespace, sourceName, Integer.parseInt(instanceId), authParams); SourceStatus.SourceInstanceStatus.SourceInstanceStatusData sourceInstanceStatusData; try { sourceInstanceStatusData = new GetSourceStatus().getComponentInstanceStatus(tenant, namespace, sourceName, Integer.parseInt(instanceId), uri); } catch (WebApplicationException we) { throw we; } catch (Exception e) { log.error("{}/{}/{} Got Exception Getting Status", tenant, namespace, sourceName, e); throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); } return sourceInstanceStatusData; } @Override public SourceConfig getSourceInfo(final String tenant, final String namespace, final String componentName, final AuthenticationParameters authParams) { componentStatusRequestValidate(tenant, namespace, componentName, authParams); Function.FunctionMetaData functionMetaData = worker().getFunctionMetaDataManager().getFunctionMetaData(tenant, namespace, componentName); return SourceConfigUtils.convertFromDetails(functionMetaData.getFunctionDetails()); } @Override public List<ConnectorDefinition> getSourceList() { List<ConnectorDefinition> connectorDefinitions = getListOfConnectors(); List<ConnectorDefinition> retval = new ArrayList<>(); for (ConnectorDefinition connectorDefinition : connectorDefinitions) { if (!org.apache.commons.lang3.StringUtils.isEmpty(connectorDefinition.getSourceClass())) { retval.add(connectorDefinition); } } return retval; } @Override public List<ConfigFieldDefinition> getSourceConfigDefinition(String name) { if (!isWorkerServiceAvailable()) { throwUnavailableException(); } List<ConfigFieldDefinition> retval = this.worker().getConnectorsManager().getSourceConfigDefinition(name); if (retval == null) { throw new RestException(Response.Status.NOT_FOUND, "builtin source does not exist"); } return retval; } private Function.FunctionDetails validateUpdateRequestParams(final String tenant, final String namespace, final String sourceName, final SourceConfig sourceConfig, final File sourcePackageFile) { // The rest end points take precedence over whatever is there in sourceconfig sourceConfig.setTenant(tenant); sourceConfig.setNamespace(namespace); sourceConfig.setName(sourceName); org.apache.pulsar.common.functions.Utils.inferMissingArguments(sourceConfig); ValidatableFunctionPackage connectorFunctionPackage = null; // check if source is builtin and extract classloader if (!StringUtils.isEmpty(sourceConfig.getArchive())) { String archive = sourceConfig.getArchive(); if (archive.startsWith(org.apache.pulsar.common.functions.Utils.BUILTIN)) { archive = archive.replaceFirst("^builtin://", ""); Connector connector = worker().getConnectorsManager().getConnector(archive); // check if builtin connector exists if (connector == null) { throw new IllegalArgumentException("Built-in source is not available"); } connectorFunctionPackage = connector.getConnectorFunctionPackage(); } } boolean shouldCloseFunctionPackage = false; try { // if source is not builtin, attempt to extract classloader from package file if it exists WorkerConfig workerConfig = worker().getWorkerConfig(); if (connectorFunctionPackage == null && sourcePackageFile != null) { connectorFunctionPackage = new FunctionFilePackage(sourcePackageFile, workerConfig.getNarExtractionDirectory(), workerConfig.getEnableClassloadingOfExternalFiles(), ConnectorDefinition.class); shouldCloseFunctionPackage = true; } if (connectorFunctionPackage == null) { throw new IllegalArgumentException("Source package is not provided"); } SourceConfigUtils.ExtractedSourceDetails sourceDetails = SourceConfigUtils.validateAndExtractDetails( sourceConfig, connectorFunctionPackage, workerConfig.getValidateConnectorConfig()); return SourceConfigUtils.convert(sourceConfig, sourceDetails); } finally { if (shouldCloseFunctionPackage && connectorFunctionPackage instanceof AutoCloseable) { try { ((AutoCloseable) connectorFunctionPackage).close(); } catch (Exception e) { log.error("Failed to connector function file", e); } } } } }
googleapis/google-cloud-java
37,770
java-gkehub/proto-google-cloud-gkehub-v1/src/main/java/com/google/cloud/gkehub/v1/FeatureState.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/gkehub/v1/feature.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.gkehub.v1; /** * * * <pre> * FeatureState describes the high-level state of a Feature. It may be used to * describe a Feature's state at the environ-level, or per-membershop, depending * on the context. * </pre> * * Protobuf type {@code google.cloud.gkehub.v1.FeatureState} */ public final class FeatureState extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.gkehub.v1.FeatureState) FeatureStateOrBuilder { private static final long serialVersionUID = 0L; // Use FeatureState.newBuilder() to construct. private FeatureState(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FeatureState() { code_ = 0; description_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FeatureState(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.v1.FeatureProto .internal_static_google_cloud_gkehub_v1_FeatureState_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.v1.FeatureProto .internal_static_google_cloud_gkehub_v1_FeatureState_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.v1.FeatureState.class, com.google.cloud.gkehub.v1.FeatureState.Builder.class); } /** * * * <pre> * Code represents a machine-readable, high-level status of the Feature. * </pre> * * Protobuf enum {@code google.cloud.gkehub.v1.FeatureState.Code} */ public enum Code implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unknown or not set. * </pre> * * <code>CODE_UNSPECIFIED = 0;</code> */ CODE_UNSPECIFIED(0), /** * * * <pre> * The Feature is operating normally. * </pre> * * <code>OK = 1;</code> */ OK(1), /** * * * <pre> * The Feature has encountered an issue, and is operating in a degraded * state. The Feature may need intervention to return to normal operation. * See the description and any associated Feature-specific details for more * information. * </pre> * * <code>WARNING = 2;</code> */ WARNING(2), /** * * * <pre> * The Feature is not operating or is in a severely degraded state. * The Feature may need intervention to return to normal operation. * See the description and any associated Feature-specific details for more * information. * </pre> * * <code>ERROR = 3;</code> */ ERROR(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Unknown or not set. * </pre> * * <code>CODE_UNSPECIFIED = 0;</code> */ public static final int CODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * The Feature is operating normally. * </pre> * * <code>OK = 1;</code> */ public static final int OK_VALUE = 1; /** * * * <pre> * The Feature has encountered an issue, and is operating in a degraded * state. The Feature may need intervention to return to normal operation. * See the description and any associated Feature-specific details for more * information. * </pre> * * <code>WARNING = 2;</code> */ public static final int WARNING_VALUE = 2; /** * * * <pre> * The Feature is not operating or is in a severely degraded state. * The Feature may need intervention to return to normal operation. * See the description and any associated Feature-specific details for more * information. * </pre> * * <code>ERROR = 3;</code> */ public static final int ERROR_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static 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 CODE_UNSPECIFIED; case 1: return OK; case 2: return WARNING; case 3: return ERROR; 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.cloud.gkehub.v1.FeatureState.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.cloud.gkehub.v1.FeatureState.Code) } private int bitField0_; public static final int CODE_FIELD_NUMBER = 1; private int code_ = 0; /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @return The enum numeric value on the wire for code. */ @java.lang.Override public int getCodeValue() { return code_; } /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @return The code. */ @java.lang.Override public com.google.cloud.gkehub.v1.FeatureState.Code getCode() { com.google.cloud.gkehub.v1.FeatureState.Code result = com.google.cloud.gkehub.v1.FeatureState.Code.forNumber(code_); return result == null ? com.google.cloud.gkehub.v1.FeatureState.Code.UNRECOGNIZED : result; } public static final int DESCRIPTION_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object description_ = ""; /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @return The description. */ @java.lang.Override public java.lang.String getDescription() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } } /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @return The bytes for description. */ @java.lang.Override public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int UPDATE_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp updateTime_; /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> * * @return Whether the updateTime field is set. */ @java.lang.Override public boolean hasUpdateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> * * @return The updateTime. */ @java.lang.Override public com.google.protobuf.Timestamp getUpdateTime() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (code_ != com.google.cloud.gkehub.v1.FeatureState.Code.CODE_UNSPECIFIED.getNumber()) { output.writeEnum(1, code_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, description_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getUpdateTime()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (code_ != com.google.cloud.gkehub.v1.FeatureState.Code.CODE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, code_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, description_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getUpdateTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.gkehub.v1.FeatureState)) { return super.equals(obj); } com.google.cloud.gkehub.v1.FeatureState other = (com.google.cloud.gkehub.v1.FeatureState) obj; if (code_ != other.code_) return false; if (!getDescription().equals(other.getDescription())) return false; if (hasUpdateTime() != other.hasUpdateTime()) return false; if (hasUpdateTime()) { if (!getUpdateTime().equals(other.getUpdateTime())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CODE_FIELD_NUMBER; hash = (53 * hash) + code_; hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER; hash = (53 * hash) + getDescription().hashCode(); if (hasUpdateTime()) { hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getUpdateTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.gkehub.v1.FeatureState parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.gkehub.v1.FeatureState parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1.FeatureState parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.v1.FeatureState parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.gkehub.v1.FeatureState 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> * FeatureState describes the high-level state of a Feature. It may be used to * describe a Feature's state at the environ-level, or per-membershop, depending * on the context. * </pre> * * Protobuf type {@code google.cloud.gkehub.v1.FeatureState} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.gkehub.v1.FeatureState) com.google.cloud.gkehub.v1.FeatureStateOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.v1.FeatureProto .internal_static_google_cloud_gkehub_v1_FeatureState_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.v1.FeatureProto .internal_static_google_cloud_gkehub_v1_FeatureState_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.v1.FeatureState.class, com.google.cloud.gkehub.v1.FeatureState.Builder.class); } // Construct using com.google.cloud.gkehub.v1.FeatureState.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getUpdateTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; code_ = 0; description_ = ""; updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.gkehub.v1.FeatureProto .internal_static_google_cloud_gkehub_v1_FeatureState_descriptor; } @java.lang.Override public com.google.cloud.gkehub.v1.FeatureState getDefaultInstanceForType() { return com.google.cloud.gkehub.v1.FeatureState.getDefaultInstance(); } @java.lang.Override public com.google.cloud.gkehub.v1.FeatureState build() { com.google.cloud.gkehub.v1.FeatureState result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.gkehub.v1.FeatureState buildPartial() { com.google.cloud.gkehub.v1.FeatureState result = new com.google.cloud.gkehub.v1.FeatureState(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.gkehub.v1.FeatureState result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.code_ = code_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.description_ = description_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.updateTime_ = updateTimeBuilder_ == null ? updateTime_ : updateTimeBuilder_.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.gkehub.v1.FeatureState) { return mergeFrom((com.google.cloud.gkehub.v1.FeatureState) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.gkehub.v1.FeatureState other) { if (other == com.google.cloud.gkehub.v1.FeatureState.getDefaultInstance()) return this; if (other.code_ != 0) { setCodeValue(other.getCodeValue()); } if (!other.getDescription().isEmpty()) { description_ = other.description_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasUpdateTime()) { mergeUpdateTime(other.getUpdateTime()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { code_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { description_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getUpdateTimeFieldBuilder().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 int code_ = 0; /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @return The enum numeric value on the wire for code. */ @java.lang.Override public int getCodeValue() { return code_; } /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @param value The enum numeric value on the wire for code to set. * @return This builder for chaining. */ public Builder setCodeValue(int value) { code_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @return The code. */ @java.lang.Override public com.google.cloud.gkehub.v1.FeatureState.Code getCode() { com.google.cloud.gkehub.v1.FeatureState.Code result = com.google.cloud.gkehub.v1.FeatureState.Code.forNumber(code_); return result == null ? com.google.cloud.gkehub.v1.FeatureState.Code.UNRECOGNIZED : result; } /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @param value The code to set. * @return This builder for chaining. */ public Builder setCode(com.google.cloud.gkehub.v1.FeatureState.Code value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; code_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * The high-level, machine-readable status of this Feature. * </pre> * * <code>.google.cloud.gkehub.v1.FeatureState.Code code = 1;</code> * * @return This builder for chaining. */ public Builder clearCode() { bitField0_ = (bitField0_ & ~0x00000001); code_ = 0; onChanged(); return this; } private java.lang.Object description_ = ""; /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @return The description. */ public java.lang.String getDescription() { java.lang.Object ref = description_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @return The bytes for description. */ public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @param value The description to set. * @return This builder for chaining. */ public Builder setDescription(java.lang.String value) { if (value == null) { throw new NullPointerException(); } description_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @return This builder for chaining. */ public Builder clearDescription() { description_ = getDefaultInstance().getDescription(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A human-readable description of the current status. * </pre> * * <code>string description = 2;</code> * * @param value The bytes for description to set. * @return This builder for chaining. */ public Builder setDescriptionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); description_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.protobuf.Timestamp updateTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> updateTimeBuilder_; /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> * * @return Whether the updateTime field is set. */ public boolean hasUpdateTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> * * @return The updateTime. */ public com.google.protobuf.Timestamp getUpdateTime() { if (updateTimeBuilder_ == null) { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } else { return updateTimeBuilder_.getMessage(); } } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateTime_ = value; } else { updateTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (updateTimeBuilder_ == null) { updateTime_ = builderForValue.build(); } else { updateTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && updateTime_ != null && updateTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getUpdateTimeBuilder().mergeFrom(value); } else { updateTime_ = value; } } else { updateTimeBuilder_.mergeFrom(value); } if (updateTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ public Builder clearUpdateTime() { bitField0_ = (bitField0_ & ~0x00000004); updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getUpdateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { if (updateTimeBuilder_ != null) { return updateTimeBuilder_.getMessageOrBuilder(); } else { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } } /** * * * <pre> * The time this status and any related Feature-specific details were updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getUpdateTimeFieldBuilder() { if (updateTimeBuilder_ == null) { updateTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getUpdateTime(), getParentForChildren(), isClean()); updateTime_ = null; } return updateTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.gkehub.v1.FeatureState) } // @@protoc_insertion_point(class_scope:google.cloud.gkehub.v1.FeatureState) private static final com.google.cloud.gkehub.v1.FeatureState DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.gkehub.v1.FeatureState(); } public static com.google.cloud.gkehub.v1.FeatureState getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FeatureState> PARSER = new com.google.protobuf.AbstractParser<FeatureState>() { @java.lang.Override public FeatureState 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<FeatureState> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FeatureState> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.gkehub.v1.FeatureState getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/metron
34,530
metron-analytics/metron-profiler-client/src/main/java/org/apache/metron/profiler/client/window/generated/WindowParser.java
// Generated from org/apache/metron/profiler/client/window/generated/Window.g4 by ANTLR 4.5 package org.apache.metron.profiler.client.window.generated; //CHECKSTYLE:OFF /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class WindowParser extends Parser { static { RuntimeMetaData.checkVersion("4.5", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int COMMA=1, COLON=2, WINDOW=3, INCLUDE=4, EXCLUDE=5, FROM=6, EVERY=7, TO=8, AGO=9, NUMBER=10, IDENTIFIER=11, DAY_SPECIFIER=12, TIME_UNIT=13, WS=14; public static final int RULE_window = 0, RULE_window_expression = 1, RULE_excluding_specifier = 2, RULE_including_specifier = 3, RULE_specifier = 4, RULE_specifier_arg_list = 5, RULE_day_specifier = 6, RULE_identifier = 7, RULE_specifier_list = 8, RULE_duration = 9, RULE_skip_distance = 10, RULE_window_width = 11, RULE_time_interval = 12, RULE_time_amount = 13, RULE_time_unit = 14; public static final String[] ruleNames = { "window", "window_expression", "excluding_specifier", "including_specifier", "specifier", "specifier_arg_list", "day_specifier", "identifier", "specifier_list", "duration", "skip_distance", "window_width", "time_interval", "time_amount", "time_unit" }; private static final String[] _LITERAL_NAMES = { null, "','", "':'" }; private static final String[] _SYMBOLIC_NAMES = { null, "COMMA", "COLON", "WINDOW", "INCLUDE", "EXCLUDE", "FROM", "EVERY", "TO", "AGO", "NUMBER", "IDENTIFIER", "DAY_SPECIFIER", "TIME_UNIT", "WS" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "Window.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public WindowParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class WindowContext extends ParserRuleContext { public Window_expressionContext window_expression() { return getRuleContext(Window_expressionContext.class,0); } public TerminalNode EOF() { return getToken(WindowParser.EOF, 0); } public WindowContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_window; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterWindow(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitWindow(this); } } public final WindowContext window() throws RecognitionException { WindowContext _localctx = new WindowContext(_ctx, getState()); enterRule(_localctx, 0, RULE_window); try { enterOuterAlt(_localctx, 1); { setState(30); window_expression(); setState(31); match(EOF); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Window_expressionContext extends ParserRuleContext { public Window_expressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_window_expression; } public Window_expressionContext() { } public void copyFrom(Window_expressionContext ctx) { super.copyFrom(ctx); } } public static class RepeatingWindowContext extends Window_expressionContext { public Window_widthContext window_width() { return getRuleContext(Window_widthContext.class,0); } public Skip_distanceContext skip_distance() { return getRuleContext(Skip_distanceContext.class,0); } public DurationContext duration() { return getRuleContext(DurationContext.class,0); } public Including_specifierContext including_specifier() { return getRuleContext(Including_specifierContext.class,0); } public Excluding_specifierContext excluding_specifier() { return getRuleContext(Excluding_specifierContext.class,0); } public RepeatingWindowContext(Window_expressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterRepeatingWindow(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitRepeatingWindow(this); } } public static class DenseWindowContext extends Window_expressionContext { public DurationContext duration() { return getRuleContext(DurationContext.class,0); } public DenseWindowContext(Window_expressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterDenseWindow(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitDenseWindow(this); } } public static class NonRepeatingWindowContext extends Window_expressionContext { public Window_widthContext window_width() { return getRuleContext(Window_widthContext.class,0); } public Including_specifierContext including_specifier() { return getRuleContext(Including_specifierContext.class,0); } public Excluding_specifierContext excluding_specifier() { return getRuleContext(Excluding_specifierContext.class,0); } public NonRepeatingWindowContext(Window_expressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterNonRepeatingWindow(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitNonRepeatingWindow(this); } } public final Window_expressionContext window_expression() throws RecognitionException { Window_expressionContext _localctx = new Window_expressionContext(_ctx, getState()); enterRule(_localctx, 2, RULE_window_expression); int _la; try { setState(50); switch ( getInterpreter().adaptivePredict(_input,4,_ctx) ) { case 1: _localctx = new NonRepeatingWindowContext(_localctx); enterOuterAlt(_localctx, 1); { setState(33); window_width(); setState(35); _la = _input.LA(1); if (_la==INCLUDE) { { setState(34); including_specifier(); } } setState(38); _la = _input.LA(1); if (_la==EXCLUDE) { { setState(37); excluding_specifier(); } } } break; case 2: _localctx = new RepeatingWindowContext(_localctx); enterOuterAlt(_localctx, 2); { setState(40); window_width(); setState(41); skip_distance(); setState(42); duration(); setState(44); _la = _input.LA(1); if (_la==INCLUDE) { { setState(43); including_specifier(); } } setState(47); _la = _input.LA(1); if (_la==EXCLUDE) { { setState(46); excluding_specifier(); } } } break; case 3: _localctx = new DenseWindowContext(_localctx); enterOuterAlt(_localctx, 3); { setState(49); duration(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Excluding_specifierContext extends ParserRuleContext { public TerminalNode EXCLUDE() { return getToken(WindowParser.EXCLUDE, 0); } public Specifier_listContext specifier_list() { return getRuleContext(Specifier_listContext.class,0); } public Excluding_specifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_excluding_specifier; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterExcluding_specifier(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitExcluding_specifier(this); } } public final Excluding_specifierContext excluding_specifier() throws RecognitionException { Excluding_specifierContext _localctx = new Excluding_specifierContext(_ctx, getState()); enterRule(_localctx, 4, RULE_excluding_specifier); try { enterOuterAlt(_localctx, 1); { setState(52); match(EXCLUDE); setState(53); specifier_list(0); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Including_specifierContext extends ParserRuleContext { public TerminalNode INCLUDE() { return getToken(WindowParser.INCLUDE, 0); } public Specifier_listContext specifier_list() { return getRuleContext(Specifier_listContext.class,0); } public Including_specifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_including_specifier; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterIncluding_specifier(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitIncluding_specifier(this); } } public final Including_specifierContext including_specifier() throws RecognitionException { Including_specifierContext _localctx = new Including_specifierContext(_ctx, getState()); enterRule(_localctx, 6, RULE_including_specifier); try { enterOuterAlt(_localctx, 1); { setState(55); match(INCLUDE); setState(56); specifier_list(0); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SpecifierContext extends ParserRuleContext { public Day_specifierContext day_specifier() { return getRuleContext(Day_specifierContext.class,0); } public Specifier_arg_listContext specifier_arg_list() { return getRuleContext(Specifier_arg_listContext.class,0); } public SpecifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_specifier; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterSpecifier(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitSpecifier(this); } } public final SpecifierContext specifier() throws RecognitionException { SpecifierContext _localctx = new SpecifierContext(_ctx, getState()); enterRule(_localctx, 8, RULE_specifier); try { setState(62); switch ( getInterpreter().adaptivePredict(_input,5,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(58); day_specifier(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(59); day_specifier(); setState(60); specifier_arg_list(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Specifier_arg_listContext extends ParserRuleContext { public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public Specifier_arg_listContext specifier_arg_list() { return getRuleContext(Specifier_arg_listContext.class,0); } public Specifier_arg_listContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_specifier_arg_list; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterSpecifier_arg_list(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitSpecifier_arg_list(this); } } public final Specifier_arg_listContext specifier_arg_list() throws RecognitionException { Specifier_arg_listContext _localctx = new Specifier_arg_listContext(_ctx, getState()); enterRule(_localctx, 10, RULE_specifier_arg_list); try { setState(68); switch ( getInterpreter().adaptivePredict(_input,6,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(64); identifier(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(65); identifier(); setState(66); specifier_arg_list(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Day_specifierContext extends ParserRuleContext { public TerminalNode DAY_SPECIFIER() { return getToken(WindowParser.DAY_SPECIFIER, 0); } public Day_specifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_day_specifier; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterDay_specifier(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitDay_specifier(this); } } public final Day_specifierContext day_specifier() throws RecognitionException { Day_specifierContext _localctx = new Day_specifierContext(_ctx, getState()); enterRule(_localctx, 12, RULE_day_specifier); try { enterOuterAlt(_localctx, 1); { setState(70); match(DAY_SPECIFIER); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class IdentifierContext extends ParserRuleContext { public TerminalNode NUMBER() { return getToken(WindowParser.NUMBER, 0); } public TerminalNode IDENTIFIER() { return getToken(WindowParser.IDENTIFIER, 0); } public IdentifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_identifier; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterIdentifier(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitIdentifier(this); } } public final IdentifierContext identifier() throws RecognitionException { IdentifierContext _localctx = new IdentifierContext(_ctx, getState()); enterRule(_localctx, 14, RULE_identifier); int _la; try { enterOuterAlt(_localctx, 1); { setState(72); _la = _input.LA(1); if ( !(_la==NUMBER || _la==IDENTIFIER) ) { _errHandler.recoverInline(this); } else { consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Specifier_listContext extends ParserRuleContext { public SpecifierContext specifier() { return getRuleContext(SpecifierContext.class,0); } public Specifier_listContext specifier_list() { return getRuleContext(Specifier_listContext.class,0); } public TerminalNode COMMA() { return getToken(WindowParser.COMMA, 0); } public Specifier_listContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_specifier_list; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterSpecifier_list(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitSpecifier_list(this); } } public final Specifier_listContext specifier_list() throws RecognitionException { return specifier_list(0); } private Specifier_listContext specifier_list(int _p) throws RecognitionException { ParserRuleContext _parentctx = _ctx; int _parentState = getState(); Specifier_listContext _localctx = new Specifier_listContext(_ctx, _parentState); Specifier_listContext _prevctx = _localctx; int _startState = 16; enterRecursionRule(_localctx, 16, RULE_specifier_list, _p); try { int _alt; enterOuterAlt(_localctx, 1); { { setState(75); specifier(); } _ctx.stop = _input.LT(-1); setState(82); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,7,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { if ( _parseListeners!=null ) triggerExitRuleEvent(); _prevctx = _localctx; { { _localctx = new Specifier_listContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_specifier_list); setState(77); if (!(precpred(_ctx, 1))) throw new FailedPredicateException(this, "precpred(_ctx, 1)"); setState(78); match(COMMA); setState(79); specifier(); } } } setState(84); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,7,_ctx); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { unrollRecursionContexts(_parentctx); } return _localctx; } public static class DurationContext extends ParserRuleContext { public DurationContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_duration; } public DurationContext() { } public void copyFrom(DurationContext ctx) { super.copyFrom(ctx); } } public static class FromToDurationContext extends DurationContext { public TerminalNode FROM() { return getToken(WindowParser.FROM, 0); } public List<Time_intervalContext> time_interval() { return getRuleContexts(Time_intervalContext.class); } public Time_intervalContext time_interval(int i) { return getRuleContext(Time_intervalContext.class,i); } public TerminalNode TO() { return getToken(WindowParser.TO, 0); } public List<TerminalNode> AGO() { return getTokens(WindowParser.AGO); } public TerminalNode AGO(int i) { return getToken(WindowParser.AGO, i); } public FromToDurationContext(DurationContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterFromToDuration(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitFromToDuration(this); } } public static class FromDurationContext extends DurationContext { public TerminalNode FROM() { return getToken(WindowParser.FROM, 0); } public Time_intervalContext time_interval() { return getRuleContext(Time_intervalContext.class,0); } public TerminalNode AGO() { return getToken(WindowParser.AGO, 0); } public FromDurationContext(DurationContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterFromDuration(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitFromDuration(this); } } public final DurationContext duration() throws RecognitionException { DurationContext _localctx = new DurationContext(_ctx, getState()); enterRule(_localctx, 18, RULE_duration); int _la; try { setState(100); switch ( getInterpreter().adaptivePredict(_input,11,_ctx) ) { case 1: _localctx = new FromToDurationContext(_localctx); enterOuterAlt(_localctx, 1); { setState(85); match(FROM); setState(86); time_interval(); setState(88); _la = _input.LA(1); if (_la==AGO) { { setState(87); match(AGO); } } setState(90); match(TO); setState(91); time_interval(); setState(93); _la = _input.LA(1); if (_la==AGO) { { setState(92); match(AGO); } } } break; case 2: _localctx = new FromDurationContext(_localctx); enterOuterAlt(_localctx, 2); { setState(95); match(FROM); setState(96); time_interval(); setState(98); _la = _input.LA(1); if (_la==AGO) { { setState(97); match(AGO); } } } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Skip_distanceContext extends ParserRuleContext { public Skip_distanceContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_skip_distance; } public Skip_distanceContext() { } public void copyFrom(Skip_distanceContext ctx) { super.copyFrom(ctx); } } public static class SkipDistanceContext extends Skip_distanceContext { public TerminalNode EVERY() { return getToken(WindowParser.EVERY, 0); } public Time_intervalContext time_interval() { return getRuleContext(Time_intervalContext.class,0); } public SkipDistanceContext(Skip_distanceContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterSkipDistance(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitSkipDistance(this); } } public final Skip_distanceContext skip_distance() throws RecognitionException { Skip_distanceContext _localctx = new Skip_distanceContext(_ctx, getState()); enterRule(_localctx, 20, RULE_skip_distance); try { _localctx = new SkipDistanceContext(_localctx); enterOuterAlt(_localctx, 1); { setState(102); match(EVERY); setState(103); time_interval(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Window_widthContext extends ParserRuleContext { public Window_widthContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_window_width; } public Window_widthContext() { } public void copyFrom(Window_widthContext ctx) { super.copyFrom(ctx); } } public static class WindowWidthContext extends Window_widthContext { public Time_intervalContext time_interval() { return getRuleContext(Time_intervalContext.class,0); } public TerminalNode WINDOW() { return getToken(WindowParser.WINDOW, 0); } public WindowWidthContext(Window_widthContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterWindowWidth(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitWindowWidth(this); } } public final Window_widthContext window_width() throws RecognitionException { Window_widthContext _localctx = new Window_widthContext(_ctx, getState()); enterRule(_localctx, 22, RULE_window_width); int _la; try { _localctx = new WindowWidthContext(_localctx); enterOuterAlt(_localctx, 1); { setState(105); time_interval(); setState(107); _la = _input.LA(1); if (_la==WINDOW) { { setState(106); match(WINDOW); } } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Time_intervalContext extends ParserRuleContext { public Time_intervalContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_time_interval; } public Time_intervalContext() { } public void copyFrom(Time_intervalContext ctx) { super.copyFrom(ctx); } } public static class TimeIntervalContext extends Time_intervalContext { public Time_amountContext time_amount() { return getRuleContext(Time_amountContext.class,0); } public Time_unitContext time_unit() { return getRuleContext(Time_unitContext.class,0); } public TimeIntervalContext(Time_intervalContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterTimeInterval(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitTimeInterval(this); } } public final Time_intervalContext time_interval() throws RecognitionException { Time_intervalContext _localctx = new Time_intervalContext(_ctx, getState()); enterRule(_localctx, 24, RULE_time_interval); try { _localctx = new TimeIntervalContext(_localctx); enterOuterAlt(_localctx, 1); { setState(109); time_amount(); setState(110); time_unit(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Time_amountContext extends ParserRuleContext { public Time_amountContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_time_amount; } public Time_amountContext() { } public void copyFrom(Time_amountContext ctx) { super.copyFrom(ctx); } } public static class TimeAmountContext extends Time_amountContext { public TerminalNode NUMBER() { return getToken(WindowParser.NUMBER, 0); } public TimeAmountContext(Time_amountContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterTimeAmount(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitTimeAmount(this); } } public final Time_amountContext time_amount() throws RecognitionException { Time_amountContext _localctx = new Time_amountContext(_ctx, getState()); enterRule(_localctx, 26, RULE_time_amount); try { _localctx = new TimeAmountContext(_localctx); enterOuterAlt(_localctx, 1); { setState(112); match(NUMBER); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Time_unitContext extends ParserRuleContext { public Time_unitContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_time_unit; } public Time_unitContext() { } public void copyFrom(Time_unitContext ctx) { super.copyFrom(ctx); } } public static class TimeUnitContext extends Time_unitContext { public TerminalNode TIME_UNIT() { return getToken(WindowParser.TIME_UNIT, 0); } public TimeUnitContext(Time_unitContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).enterTimeUnit(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof WindowListener ) ((WindowListener)listener).exitTimeUnit(this); } } public final Time_unitContext time_unit() throws RecognitionException { Time_unitContext _localctx = new Time_unitContext(_ctx, getState()); enterRule(_localctx, 28, RULE_time_unit); try { _localctx = new TimeUnitContext(_localctx); enterOuterAlt(_localctx, 1); { setState(114); match(TIME_UNIT); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 8: return specifier_list_sempred((Specifier_listContext)_localctx, predIndex); } return true; } private boolean specifier_list_sempred(Specifier_listContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 1); } return true; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\20w\4\2\t\2\4\3\t"+ "\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4"+ "\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\3\2\3\2\3\2\3\3\3\3\5\3&"+ "\n\3\3\3\5\3)\n\3\3\3\3\3\3\3\3\3\5\3/\n\3\3\3\5\3\62\n\3\3\3\5\3\65\n"+ "\3\3\4\3\4\3\4\3\5\3\5\3\5\3\6\3\6\3\6\3\6\5\6A\n\6\3\7\3\7\3\7\3\7\5"+ "\7G\n\7\3\b\3\b\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\7\nS\n\n\f\n\16\nV\13"+ "\n\3\13\3\13\3\13\5\13[\n\13\3\13\3\13\3\13\5\13`\n\13\3\13\3\13\3\13"+ "\5\13e\n\13\5\13g\n\13\3\f\3\f\3\f\3\r\3\r\5\rn\n\r\3\16\3\16\3\16\3\17"+ "\3\17\3\20\3\20\3\20\2\3\22\21\2\4\6\b\n\f\16\20\22\24\26\30\32\34\36"+ "\2\3\3\2\f\ru\2 \3\2\2\2\4\64\3\2\2\2\6\66\3\2\2\2\b9\3\2\2\2\n@\3\2\2"+ "\2\fF\3\2\2\2\16H\3\2\2\2\20J\3\2\2\2\22L\3\2\2\2\24f\3\2\2\2\26h\3\2"+ "\2\2\30k\3\2\2\2\32o\3\2\2\2\34r\3\2\2\2\36t\3\2\2\2 !\5\4\3\2!\"\7\2"+ "\2\3\"\3\3\2\2\2#%\5\30\r\2$&\5\b\5\2%$\3\2\2\2%&\3\2\2\2&(\3\2\2\2\'"+ ")\5\6\4\2(\'\3\2\2\2()\3\2\2\2)\65\3\2\2\2*+\5\30\r\2+,\5\26\f\2,.\5\24"+ "\13\2-/\5\b\5\2.-\3\2\2\2./\3\2\2\2/\61\3\2\2\2\60\62\5\6\4\2\61\60\3"+ "\2\2\2\61\62\3\2\2\2\62\65\3\2\2\2\63\65\5\24\13\2\64#\3\2\2\2\64*\3\2"+ "\2\2\64\63\3\2\2\2\65\5\3\2\2\2\66\67\7\7\2\2\678\5\22\n\28\7\3\2\2\2"+ "9:\7\6\2\2:;\5\22\n\2;\t\3\2\2\2<A\5\16\b\2=>\5\16\b\2>?\5\f\7\2?A\3\2"+ "\2\2@<\3\2\2\2@=\3\2\2\2A\13\3\2\2\2BG\5\20\t\2CD\5\20\t\2DE\5\f\7\2E"+ "G\3\2\2\2FB\3\2\2\2FC\3\2\2\2G\r\3\2\2\2HI\7\16\2\2I\17\3\2\2\2JK\t\2"+ "\2\2K\21\3\2\2\2LM\b\n\1\2MN\5\n\6\2NT\3\2\2\2OP\f\3\2\2PQ\7\3\2\2QS\5"+ "\n\6\2RO\3\2\2\2SV\3\2\2\2TR\3\2\2\2TU\3\2\2\2U\23\3\2\2\2VT\3\2\2\2W"+ "X\7\b\2\2XZ\5\32\16\2Y[\7\13\2\2ZY\3\2\2\2Z[\3\2\2\2[\\\3\2\2\2\\]\7\n"+ "\2\2]_\5\32\16\2^`\7\13\2\2_^\3\2\2\2_`\3\2\2\2`g\3\2\2\2ab\7\b\2\2bd"+ "\5\32\16\2ce\7\13\2\2dc\3\2\2\2de\3\2\2\2eg\3\2\2\2fW\3\2\2\2fa\3\2\2"+ "\2g\25\3\2\2\2hi\7\t\2\2ij\5\32\16\2j\27\3\2\2\2km\5\32\16\2ln\7\5\2\2"+ "ml\3\2\2\2mn\3\2\2\2n\31\3\2\2\2op\5\34\17\2pq\5\36\20\2q\33\3\2\2\2r"+ "s\7\f\2\2s\35\3\2\2\2tu\7\17\2\2u\37\3\2\2\2\17%(.\61\64@FTZ_dfm"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
googleapis/google-cloud-java
37,830
java-telcoautomation/proto-google-cloud-telcoautomation-v1/src/main/java/com/google/cloud/telcoautomation/v1/ListDeploymentRevisionsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/telcoautomation/v1/telcoautomation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.telcoautomation.v1; /** * * * <pre> * List of deployment revisions for a given deployment. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse} */ public final class ListDeploymentRevisionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) ListDeploymentRevisionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDeploymentRevisionsResponse.newBuilder() to construct. private ListDeploymentRevisionsResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDeploymentRevisionsResponse() { deployments_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDeploymentRevisionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_ListDeploymentRevisionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_ListDeploymentRevisionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse.class, com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse.Builder.class); } public static final int DEPLOYMENTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.telcoautomation.v1.Deployment> deployments_; /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.telcoautomation.v1.Deployment> getDeploymentsList() { return deployments_; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.telcoautomation.v1.DeploymentOrBuilder> getDeploymentsOrBuilderList() { return deployments_; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ @java.lang.Override public int getDeploymentsCount() { return deployments_.size(); } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1.Deployment getDeployments(int index) { return deployments_.get(index); } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1.DeploymentOrBuilder getDeploymentsOrBuilder( int index) { return deployments_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < deployments_.size(); i++) { output.writeMessage(1, deployments_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < deployments_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, deployments_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse)) { return super.equals(obj); } com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse other = (com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) obj; if (!getDeploymentsList().equals(other.getDeploymentsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getDeploymentsCount() > 0) { hash = (37 * hash) + DEPLOYMENTS_FIELD_NUMBER; hash = (53 * hash) + getDeploymentsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse 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 deployment revisions for a given deployment. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_ListDeploymentRevisionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_ListDeploymentRevisionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse.class, com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse.Builder.class); } // Construct using // com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (deploymentsBuilder_ == null) { deployments_ = java.util.Collections.emptyList(); } else { deployments_ = null; deploymentsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_ListDeploymentRevisionsResponse_descriptor; } @java.lang.Override public com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse getDefaultInstanceForType() { return com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse build() { com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse buildPartial() { com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse result = new com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse result) { if (deploymentsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { deployments_ = java.util.Collections.unmodifiableList(deployments_); bitField0_ = (bitField0_ & ~0x00000001); } result.deployments_ = deployments_; } else { result.deployments_ = deploymentsBuilder_.build(); } } private void buildPartial0( com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) { return mergeFrom( (com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse other) { if (other == com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse .getDefaultInstance()) return this; if (deploymentsBuilder_ == null) { if (!other.deployments_.isEmpty()) { if (deployments_.isEmpty()) { deployments_ = other.deployments_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDeploymentsIsMutable(); deployments_.addAll(other.deployments_); } onChanged(); } } else { if (!other.deployments_.isEmpty()) { if (deploymentsBuilder_.isEmpty()) { deploymentsBuilder_.dispose(); deploymentsBuilder_ = null; deployments_ = other.deployments_; bitField0_ = (bitField0_ & ~0x00000001); deploymentsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDeploymentsFieldBuilder() : null; } else { deploymentsBuilder_.addAllMessages(other.deployments_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.telcoautomation.v1.Deployment m = input.readMessage( com.google.cloud.telcoautomation.v1.Deployment.parser(), extensionRegistry); if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.add(m); } else { deploymentsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.telcoautomation.v1.Deployment> deployments_ = java.util.Collections.emptyList(); private void ensureDeploymentsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { deployments_ = new java.util.ArrayList<com.google.cloud.telcoautomation.v1.Deployment>(deployments_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.telcoautomation.v1.Deployment, com.google.cloud.telcoautomation.v1.Deployment.Builder, com.google.cloud.telcoautomation.v1.DeploymentOrBuilder> deploymentsBuilder_; /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public java.util.List<com.google.cloud.telcoautomation.v1.Deployment> getDeploymentsList() { if (deploymentsBuilder_ == null) { return java.util.Collections.unmodifiableList(deployments_); } else { return deploymentsBuilder_.getMessageList(); } } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public int getDeploymentsCount() { if (deploymentsBuilder_ == null) { return deployments_.size(); } else { return deploymentsBuilder_.getCount(); } } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public com.google.cloud.telcoautomation.v1.Deployment getDeployments(int index) { if (deploymentsBuilder_ == null) { return deployments_.get(index); } else { return deploymentsBuilder_.getMessage(index); } } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder setDeployments(int index, com.google.cloud.telcoautomation.v1.Deployment value) { if (deploymentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDeploymentsIsMutable(); deployments_.set(index, value); onChanged(); } else { deploymentsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder setDeployments( int index, com.google.cloud.telcoautomation.v1.Deployment.Builder builderForValue) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.set(index, builderForValue.build()); onChanged(); } else { deploymentsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder addDeployments(com.google.cloud.telcoautomation.v1.Deployment value) { if (deploymentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDeploymentsIsMutable(); deployments_.add(value); onChanged(); } else { deploymentsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder addDeployments(int index, com.google.cloud.telcoautomation.v1.Deployment value) { if (deploymentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDeploymentsIsMutable(); deployments_.add(index, value); onChanged(); } else { deploymentsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder addDeployments( com.google.cloud.telcoautomation.v1.Deployment.Builder builderForValue) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.add(builderForValue.build()); onChanged(); } else { deploymentsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder addDeployments( int index, com.google.cloud.telcoautomation.v1.Deployment.Builder builderForValue) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.add(index, builderForValue.build()); onChanged(); } else { deploymentsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder addAllDeployments( java.lang.Iterable<? extends com.google.cloud.telcoautomation.v1.Deployment> values) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, deployments_); onChanged(); } else { deploymentsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder clearDeployments() { if (deploymentsBuilder_ == null) { deployments_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { deploymentsBuilder_.clear(); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public Builder removeDeployments(int index) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.remove(index); onChanged(); } else { deploymentsBuilder_.remove(index); } return this; } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public com.google.cloud.telcoautomation.v1.Deployment.Builder getDeploymentsBuilder(int index) { return getDeploymentsFieldBuilder().getBuilder(index); } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public com.google.cloud.telcoautomation.v1.DeploymentOrBuilder getDeploymentsOrBuilder( int index) { if (deploymentsBuilder_ == null) { return deployments_.get(index); } else { return deploymentsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public java.util.List<? extends com.google.cloud.telcoautomation.v1.DeploymentOrBuilder> getDeploymentsOrBuilderList() { if (deploymentsBuilder_ != null) { return deploymentsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(deployments_); } } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public com.google.cloud.telcoautomation.v1.Deployment.Builder addDeploymentsBuilder() { return getDeploymentsFieldBuilder() .addBuilder(com.google.cloud.telcoautomation.v1.Deployment.getDefaultInstance()); } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public com.google.cloud.telcoautomation.v1.Deployment.Builder addDeploymentsBuilder(int index) { return getDeploymentsFieldBuilder() .addBuilder(index, com.google.cloud.telcoautomation.v1.Deployment.getDefaultInstance()); } /** * * * <pre> * The revisions of the deployment. * </pre> * * <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code> */ public java.util.List<com.google.cloud.telcoautomation.v1.Deployment.Builder> getDeploymentsBuilderList() { return getDeploymentsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.telcoautomation.v1.Deployment, com.google.cloud.telcoautomation.v1.Deployment.Builder, com.google.cloud.telcoautomation.v1.DeploymentOrBuilder> getDeploymentsFieldBuilder() { if (deploymentsBuilder_ == null) { deploymentsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.telcoautomation.v1.Deployment, com.google.cloud.telcoautomation.v1.Deployment.Builder, com.google.cloud.telcoautomation.v1.DeploymentOrBuilder>( deployments_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); deployments_ = null; } return deploymentsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse) private static final com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse(); } public static com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDeploymentRevisionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListDeploymentRevisionsResponse>() { @java.lang.Override public ListDeploymentRevisionsResponse 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<ListDeploymentRevisionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDeploymentRevisionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.telcoautomation.v1.ListDeploymentRevisionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,833
java-essential-contacts/proto-google-cloud-essential-contacts-v1/src/main/java/com/google/cloud/essentialcontacts/v1/ListContactsResponse.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/essentialcontacts/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.essentialcontacts.v1; /** * * * <pre> * Response message for the ListContacts method. * </pre> * * Protobuf type {@code google.cloud.essentialcontacts.v1.ListContactsResponse} */ public final class ListContactsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.essentialcontacts.v1.ListContactsResponse) ListContactsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListContactsResponse.newBuilder() to construct. private ListContactsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListContactsResponse() { contacts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListContactsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.essentialcontacts.v1.Service .internal_static_google_cloud_essentialcontacts_v1_ListContactsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.essentialcontacts.v1.Service .internal_static_google_cloud_essentialcontacts_v1_ListContactsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.essentialcontacts.v1.ListContactsResponse.class, com.google.cloud.essentialcontacts.v1.ListContactsResponse.Builder.class); } public static final int CONTACTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.essentialcontacts.v1.Contact> contacts_; /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.essentialcontacts.v1.Contact> getContactsList() { return contacts_; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.essentialcontacts.v1.ContactOrBuilder> getContactsOrBuilderList() { return contacts_; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ @java.lang.Override public int getContactsCount() { return contacts_.size(); } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ @java.lang.Override public com.google.cloud.essentialcontacts.v1.Contact getContacts(int index) { return contacts_.get(index); } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ @java.lang.Override public com.google.cloud.essentialcontacts.v1.ContactOrBuilder getContactsOrBuilder(int index) { return contacts_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < contacts_.size(); i++) { output.writeMessage(1, contacts_.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 < contacts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, contacts_.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.essentialcontacts.v1.ListContactsResponse)) { return super.equals(obj); } com.google.cloud.essentialcontacts.v1.ListContactsResponse other = (com.google.cloud.essentialcontacts.v1.ListContactsResponse) obj; if (!getContactsList().equals(other.getContactsList())) 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 (getContactsCount() > 0) { hash = (37 * hash) + CONTACTS_FIELD_NUMBER; hash = (53 * hash) + getContactsList().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.essentialcontacts.v1.ListContactsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse 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.essentialcontacts.v1.ListContactsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse 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.essentialcontacts.v1.ListContactsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse 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.essentialcontacts.v1.ListContactsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse 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.essentialcontacts.v1.ListContactsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse 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.essentialcontacts.v1.ListContactsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for the ListContacts method. * </pre> * * Protobuf type {@code google.cloud.essentialcontacts.v1.ListContactsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.essentialcontacts.v1.ListContactsResponse) com.google.cloud.essentialcontacts.v1.ListContactsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.essentialcontacts.v1.Service .internal_static_google_cloud_essentialcontacts_v1_ListContactsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.essentialcontacts.v1.Service .internal_static_google_cloud_essentialcontacts_v1_ListContactsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.essentialcontacts.v1.ListContactsResponse.class, com.google.cloud.essentialcontacts.v1.ListContactsResponse.Builder.class); } // Construct using com.google.cloud.essentialcontacts.v1.ListContactsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (contactsBuilder_ == null) { contacts_ = java.util.Collections.emptyList(); } else { contacts_ = null; contactsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.essentialcontacts.v1.Service .internal_static_google_cloud_essentialcontacts_v1_ListContactsResponse_descriptor; } @java.lang.Override public com.google.cloud.essentialcontacts.v1.ListContactsResponse getDefaultInstanceForType() { return com.google.cloud.essentialcontacts.v1.ListContactsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.essentialcontacts.v1.ListContactsResponse build() { com.google.cloud.essentialcontacts.v1.ListContactsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.essentialcontacts.v1.ListContactsResponse buildPartial() { com.google.cloud.essentialcontacts.v1.ListContactsResponse result = new com.google.cloud.essentialcontacts.v1.ListContactsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.essentialcontacts.v1.ListContactsResponse result) { if (contactsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { contacts_ = java.util.Collections.unmodifiableList(contacts_); bitField0_ = (bitField0_ & ~0x00000001); } result.contacts_ = contacts_; } else { result.contacts_ = contactsBuilder_.build(); } } private void buildPartial0(com.google.cloud.essentialcontacts.v1.ListContactsResponse 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.essentialcontacts.v1.ListContactsResponse) { return mergeFrom((com.google.cloud.essentialcontacts.v1.ListContactsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.essentialcontacts.v1.ListContactsResponse other) { if (other == com.google.cloud.essentialcontacts.v1.ListContactsResponse.getDefaultInstance()) return this; if (contactsBuilder_ == null) { if (!other.contacts_.isEmpty()) { if (contacts_.isEmpty()) { contacts_ = other.contacts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureContactsIsMutable(); contacts_.addAll(other.contacts_); } onChanged(); } } else { if (!other.contacts_.isEmpty()) { if (contactsBuilder_.isEmpty()) { contactsBuilder_.dispose(); contactsBuilder_ = null; contacts_ = other.contacts_; bitField0_ = (bitField0_ & ~0x00000001); contactsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getContactsFieldBuilder() : null; } else { contactsBuilder_.addAllMessages(other.contacts_); } } } 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.essentialcontacts.v1.Contact m = input.readMessage( com.google.cloud.essentialcontacts.v1.Contact.parser(), extensionRegistry); if (contactsBuilder_ == null) { ensureContactsIsMutable(); contacts_.add(m); } else { contactsBuilder_.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.essentialcontacts.v1.Contact> contacts_ = java.util.Collections.emptyList(); private void ensureContactsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { contacts_ = new java.util.ArrayList<com.google.cloud.essentialcontacts.v1.Contact>(contacts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.essentialcontacts.v1.Contact, com.google.cloud.essentialcontacts.v1.Contact.Builder, com.google.cloud.essentialcontacts.v1.ContactOrBuilder> contactsBuilder_; /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public java.util.List<com.google.cloud.essentialcontacts.v1.Contact> getContactsList() { if (contactsBuilder_ == null) { return java.util.Collections.unmodifiableList(contacts_); } else { return contactsBuilder_.getMessageList(); } } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public int getContactsCount() { if (contactsBuilder_ == null) { return contacts_.size(); } else { return contactsBuilder_.getCount(); } } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public com.google.cloud.essentialcontacts.v1.Contact getContacts(int index) { if (contactsBuilder_ == null) { return contacts_.get(index); } else { return contactsBuilder_.getMessage(index); } } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder setContacts(int index, com.google.cloud.essentialcontacts.v1.Contact value) { if (contactsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContactsIsMutable(); contacts_.set(index, value); onChanged(); } else { contactsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder setContacts( int index, com.google.cloud.essentialcontacts.v1.Contact.Builder builderForValue) { if (contactsBuilder_ == null) { ensureContactsIsMutable(); contacts_.set(index, builderForValue.build()); onChanged(); } else { contactsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder addContacts(com.google.cloud.essentialcontacts.v1.Contact value) { if (contactsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContactsIsMutable(); contacts_.add(value); onChanged(); } else { contactsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder addContacts(int index, com.google.cloud.essentialcontacts.v1.Contact value) { if (contactsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContactsIsMutable(); contacts_.add(index, value); onChanged(); } else { contactsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder addContacts( com.google.cloud.essentialcontacts.v1.Contact.Builder builderForValue) { if (contactsBuilder_ == null) { ensureContactsIsMutable(); contacts_.add(builderForValue.build()); onChanged(); } else { contactsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder addContacts( int index, com.google.cloud.essentialcontacts.v1.Contact.Builder builderForValue) { if (contactsBuilder_ == null) { ensureContactsIsMutable(); contacts_.add(index, builderForValue.build()); onChanged(); } else { contactsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder addAllContacts( java.lang.Iterable<? extends com.google.cloud.essentialcontacts.v1.Contact> values) { if (contactsBuilder_ == null) { ensureContactsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, contacts_); onChanged(); } else { contactsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder clearContacts() { if (contactsBuilder_ == null) { contacts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { contactsBuilder_.clear(); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public Builder removeContacts(int index) { if (contactsBuilder_ == null) { ensureContactsIsMutable(); contacts_.remove(index); onChanged(); } else { contactsBuilder_.remove(index); } return this; } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public com.google.cloud.essentialcontacts.v1.Contact.Builder getContactsBuilder(int index) { return getContactsFieldBuilder().getBuilder(index); } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public com.google.cloud.essentialcontacts.v1.ContactOrBuilder getContactsOrBuilder(int index) { if (contactsBuilder_ == null) { return contacts_.get(index); } else { return contactsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public java.util.List<? extends com.google.cloud.essentialcontacts.v1.ContactOrBuilder> getContactsOrBuilderList() { if (contactsBuilder_ != null) { return contactsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(contacts_); } } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public com.google.cloud.essentialcontacts.v1.Contact.Builder addContactsBuilder() { return getContactsFieldBuilder() .addBuilder(com.google.cloud.essentialcontacts.v1.Contact.getDefaultInstance()); } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public com.google.cloud.essentialcontacts.v1.Contact.Builder addContactsBuilder(int index) { return getContactsFieldBuilder() .addBuilder(index, com.google.cloud.essentialcontacts.v1.Contact.getDefaultInstance()); } /** * * * <pre> * The contacts for the specified resource. * </pre> * * <code>repeated .google.cloud.essentialcontacts.v1.Contact contacts = 1;</code> */ public java.util.List<com.google.cloud.essentialcontacts.v1.Contact.Builder> getContactsBuilderList() { return getContactsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.essentialcontacts.v1.Contact, com.google.cloud.essentialcontacts.v1.Contact.Builder, com.google.cloud.essentialcontacts.v1.ContactOrBuilder> getContactsFieldBuilder() { if (contactsBuilder_ == null) { contactsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.essentialcontacts.v1.Contact, com.google.cloud.essentialcontacts.v1.Contact.Builder, com.google.cloud.essentialcontacts.v1.ContactOrBuilder>( contacts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); contacts_ = null; } return contactsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * If there are more results than those appearing in this response, then * `next_page_token` is included. To get the next set of results, call this * method again using the value of `next_page_token` as `page_token` and the * rest of the parameters the same as the original request. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.essentialcontacts.v1.ListContactsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.essentialcontacts.v1.ListContactsResponse) private static final com.google.cloud.essentialcontacts.v1.ListContactsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.essentialcontacts.v1.ListContactsResponse(); } public static com.google.cloud.essentialcontacts.v1.ListContactsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListContactsResponse> PARSER = new com.google.protobuf.AbstractParser<ListContactsResponse>() { @java.lang.Override public ListContactsResponse 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<ListContactsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListContactsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.essentialcontacts.v1.ListContactsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/j2objc
38,160
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationFastLatin.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) 2013-2015, International Business Machines * Corporation and others. All Rights Reserved. ******************************************************************************* * CollationFastLatin.java, ported from collationfastlatin.h/.cpp * * C++ version created on: 2013aug09 * created by: Markus W. Scherer */ package android.icu.impl.coll; import android.icu.lang.UScript; import android.icu.text.Collator; /** * @hide Only a subset of ICU is exposed in Android */ public final class CollationFastLatin /* all static */ { /** * Fast Latin format version (one byte 1..FF). * Must be incremented for any runtime-incompatible changes, * in particular, for changes to any of the following constants. * * When the major version number of the main data format changes, * we can reset this fast Latin version to 1. */ public static final int VERSION = 2; public static final int LATIN_MAX = 0x17f; public static final int LATIN_LIMIT = LATIN_MAX + 1; static final int LATIN_MAX_UTF8_LEAD = 0xc5; // UTF-8 lead byte of LATIN_MAX static final int PUNCT_START = 0x2000; static final int PUNCT_LIMIT = 0x2040; // excludes U+FFFE & U+FFFF static final int NUM_FAST_CHARS = LATIN_LIMIT + (PUNCT_LIMIT - PUNCT_START); // Note on the supported weight ranges: // Analysis of UCA 6.3 and CLDR 23 non-search tailorings shows that // the CEs for characters in the above ranges, excluding expansions with length >2, // excluding contractions of >2 characters, and other restrictions // (see the builder's getCEsFromCE32()), // use at most about 150 primary weights, // where about 94 primary weights are possibly-variable (space/punct/symbol/currency), // at most 4 secondary before-common weights, // at most 4 secondary after-common weights, // at most 16 secondary high weights (in secondary CEs), and // at most 4 tertiary after-common weights. // The following ranges are designed to support slightly more weights than that. // (en_US_POSIX is unusual: It creates about 64 variable + 116 Latin primaries.) // Digits may use long primaries (preserving more short ones) // or short primaries (faster) without changing this data structure. // (If we supported numeric collation, then digits would have to have long primaries // so that special handling does not affect the fast path.) static final int SHORT_PRIMARY_MASK = 0xfc00; // bits 15..10 static final int INDEX_MASK = 0x3ff; // bits 9..0 for expansions & contractions static final int SECONDARY_MASK = 0x3e0; // bits 9..5 static final int CASE_MASK = 0x18; // bits 4..3 static final int LONG_PRIMARY_MASK = 0xfff8; // bits 15..3 static final int TERTIARY_MASK = 7; // bits 2..0 static final int CASE_AND_TERTIARY_MASK = CASE_MASK | TERTIARY_MASK; static final int TWO_SHORT_PRIMARIES_MASK = (SHORT_PRIMARY_MASK << 16) | SHORT_PRIMARY_MASK; // 0xfc00fc00 static final int TWO_LONG_PRIMARIES_MASK = (LONG_PRIMARY_MASK << 16) | LONG_PRIMARY_MASK; // 0xfff8fff8 static final int TWO_SECONDARIES_MASK = (SECONDARY_MASK << 16) | SECONDARY_MASK; // 0x3e003e0 static final int TWO_CASES_MASK = (CASE_MASK << 16) | CASE_MASK; // 0x180018 static final int TWO_TERTIARIES_MASK = (TERTIARY_MASK << 16) | TERTIARY_MASK; // 0x70007 /** * Contraction with one fast Latin character. * Use INDEX_MASK to find the start of the contraction list after the fixed table. * The first entry contains the default mapping. * Otherwise use CONTR_CHAR_MASK for the contraction character index * (in ascending order). * Use CONTR_LENGTH_SHIFT for the length of the entry * (1=BAIL_OUT, 2=one CE, 3=two CEs). * * Also, U+0000 maps to a contraction entry, so that the fast path need not * check for NUL termination. * It usually maps to a contraction list with only the completely ignorable default value. */ static final int CONTRACTION = 0x400; /** * An expansion encodes two CEs. * Use INDEX_MASK to find the pair of CEs after the fixed table. * * The higher a mini CE value, the easier it is to process. * For expansions and higher, no context needs to be considered. */ static final int EXPANSION = 0x800; /** * Encodes one CE with a long/low mini primary (there are 128). * All potentially-variable primaries must be in this range, * to make the short-primary path as fast as possible. */ static final int MIN_LONG = 0xc00; static final int LONG_INC = 8; static final int MAX_LONG = 0xff8; /** * Encodes one CE with a short/high primary (there are 60), * plus a secondary CE if the secondary weight is high. * Fast handling: At least all letter primaries should be in this range. */ static final int MIN_SHORT = 0x1000; static final int SHORT_INC = 0x400; /** The highest primary weight is reserved for U+FFFF. */ static final int MAX_SHORT = SHORT_PRIMARY_MASK; static final int MIN_SEC_BEFORE = 0; // must add SEC_OFFSET static final int SEC_INC = 0x20; static final int MAX_SEC_BEFORE = MIN_SEC_BEFORE + 4 * SEC_INC; // 5 before common static final int COMMON_SEC = MAX_SEC_BEFORE + SEC_INC; static final int MIN_SEC_AFTER = COMMON_SEC + SEC_INC; static final int MAX_SEC_AFTER = MIN_SEC_AFTER + 5 * SEC_INC; // 6 after common static final int MIN_SEC_HIGH = MAX_SEC_AFTER + SEC_INC; // 20 high secondaries static final int MAX_SEC_HIGH = SECONDARY_MASK; /** * Lookup: Add this offset to secondary weights, except for completely ignorable CEs. * Must be greater than any special value, e.g., MERGE_WEIGHT. * The exact value is not relevant for the format version. */ static final int SEC_OFFSET = SEC_INC; static final int COMMON_SEC_PLUS_OFFSET = COMMON_SEC + SEC_OFFSET; static final int TWO_SEC_OFFSETS = (SEC_OFFSET << 16) | SEC_OFFSET; // 0x200020 static final int TWO_COMMON_SEC_PLUS_OFFSET = (COMMON_SEC_PLUS_OFFSET << 16) | COMMON_SEC_PLUS_OFFSET; static final int LOWER_CASE = 8; // case bits include this offset static final int TWO_LOWER_CASES = (LOWER_CASE << 16) | LOWER_CASE; // 0x80008 static final int COMMON_TER = 0; // must add TER_OFFSET static final int MAX_TER_AFTER = 7; // 7 after common /** * Lookup: Add this offset to tertiary weights, except for completely ignorable CEs. * Must be greater than any special value, e.g., MERGE_WEIGHT. * Must be greater than case bits as well, so that with combined case+tertiary weights * plus the offset the tertiary bits does not spill over into the case bits. * The exact value is not relevant for the format version. */ static final int TER_OFFSET = SEC_OFFSET; static final int COMMON_TER_PLUS_OFFSET = COMMON_TER + TER_OFFSET; static final int TWO_TER_OFFSETS = (TER_OFFSET << 16) | TER_OFFSET; static final int TWO_COMMON_TER_PLUS_OFFSET = (COMMON_TER_PLUS_OFFSET << 16) | COMMON_TER_PLUS_OFFSET; static final int MERGE_WEIGHT = 3; static final int EOS = 2; // end of string static final int BAIL_OUT = 1; /** * Contraction result first word bits 8..0 contain the * second contraction character, as a char index 0..NUM_FAST_CHARS-1. * Each contraction list is terminated with a word containing CONTR_CHAR_MASK. */ static final int CONTR_CHAR_MASK = 0x1ff; /** * Contraction result first word bits 10..9 contain the result length: * 1=bail out, 2=one mini CE, 3=two mini CEs */ static final int CONTR_LENGTH_SHIFT = 9; /** * Comparison return value when the regular comparison must be used. * The exact value is not relevant for the format version. */ public static final int BAIL_OUT_RESULT = -2; static int getCharIndex(char c) { if(c <= LATIN_MAX) { return c; } else if(PUNCT_START <= c && c < PUNCT_LIMIT) { return c - (PUNCT_START - LATIN_LIMIT); } else { // Not a fast Latin character. // Note: U+FFFE & U+FFFF are forbidden in tailorings // and thus do not occur in any contractions. return -1; } } /** * Computes the options value for the compare functions * and writes the precomputed primary weights. * Returns -1 if the Latin fastpath is not supported for the data and settings. * The capacity must be LATIN_LIMIT. */ public static int getOptions(CollationData data, CollationSettings settings, char[] primaries) { char[] header = data.fastLatinTableHeader; if(header == null) { return -1; } assert((header[0] >> 8) == VERSION); if(primaries.length != LATIN_LIMIT) { assert false; return -1; } int miniVarTop; if((settings.options & CollationSettings.ALTERNATE_MASK) == 0) { // No mini primaries are variable, set a variableTop just below the // lowest long mini primary. miniVarTop = MIN_LONG - 1; } else { int headerLength = header[0] & 0xff; int i = 1 + settings.getMaxVariable(); if(i >= headerLength) { return -1; // variableTop >= digits, should not occur } miniVarTop = header[i]; } boolean digitsAreReordered = false; if(settings.hasReordering()) { long prevStart = 0; long beforeDigitStart = 0; long digitStart = 0; long afterDigitStart = 0; for(int group = Collator.ReorderCodes.FIRST; group < Collator.ReorderCodes.FIRST + CollationData.MAX_NUM_SPECIAL_REORDER_CODES; ++group) { long start = data.getFirstPrimaryForGroup(group); start = settings.reorder(start); if(group == Collator.ReorderCodes.DIGIT) { beforeDigitStart = prevStart; digitStart = start; } else if(start != 0) { if(start < prevStart) { // The permutation affects the groups up to Latin. return -1; } // In the future, there might be a special group between digits & Latin. if(digitStart != 0 && afterDigitStart == 0 && prevStart == beforeDigitStart) { afterDigitStart = start; } prevStart = start; } } long latinStart = data.getFirstPrimaryForGroup(UScript.LATIN); latinStart = settings.reorder(latinStart); if(latinStart < prevStart) { return -1; } if(afterDigitStart == 0) { afterDigitStart = latinStart; } if(!(beforeDigitStart < digitStart && digitStart < afterDigitStart)) { digitsAreReordered = true; } } char[] table = data.fastLatinTable; // skip the header for(int c = 0; c < LATIN_LIMIT; ++c) { int p = table[c]; if(p >= MIN_SHORT) { p &= SHORT_PRIMARY_MASK; } else if(p > miniVarTop) { p &= LONG_PRIMARY_MASK; } else { p = 0; } primaries[c] = (char)p; } if(digitsAreReordered || (settings.options & CollationSettings.NUMERIC) != 0) { // Bail out for digits. for(int c = 0x30; c <= 0x39; ++c) { primaries[c] = 0; } } // Shift the miniVarTop above other options. return (miniVarTop << 16) | settings.options; } public static int compareUTF16(char[] table, char[] primaries, int options, CharSequence left, CharSequence right, int startIndex) { // This is a modified copy of CollationCompare.compareUpToQuaternary(), // optimized for common Latin text. // Keep them in sync! int variableTop = options >> 16; // see getOptions() options &= 0xffff; // needed for CollationSettings.getStrength() to work // Check for supported characters, fetch mini CEs, and compare primaries. int leftIndex = startIndex, rightIndex = startIndex; /** * Single mini CE or a pair. * The current mini CE is in the lower 16 bits, the next one is in the upper 16 bits. * If there is only one, then it is in the lower bits, and the upper bits are 0. */ int leftPair = 0, rightPair = 0; for(;;) { // We fetch CEs until we get a non-ignorable primary or reach the end. while(leftPair == 0) { if(leftIndex == left.length()) { leftPair = EOS; break; } int c = left.charAt(leftIndex++); if(c <= LATIN_MAX) { leftPair = primaries[c]; if(leftPair != 0) { break; } if(c <= 0x39 && c >= 0x30 && (options & CollationSettings.NUMERIC) != 0) { return BAIL_OUT_RESULT; } leftPair = table[c]; } else if(PUNCT_START <= c && c < PUNCT_LIMIT) { leftPair = table[c - PUNCT_START + LATIN_LIMIT]; } else { leftPair = lookup(table, c); } if(leftPair >= MIN_SHORT) { leftPair &= SHORT_PRIMARY_MASK; break; } else if(leftPair > variableTop) { leftPair &= LONG_PRIMARY_MASK; break; } else { long pairAndInc = nextPair(table, c, leftPair, left, leftIndex); if(pairAndInc < 0) { ++leftIndex; pairAndInc = ~pairAndInc; } leftPair = (int)pairAndInc; if(leftPair == BAIL_OUT) { return BAIL_OUT_RESULT; } leftPair = getPrimaries(variableTop, leftPair); } } while(rightPair == 0) { if(rightIndex == right.length()) { rightPair = EOS; break; } int c = right.charAt(rightIndex++); if(c <= LATIN_MAX) { rightPair = primaries[c]; if(rightPair != 0) { break; } if(c <= 0x39 && c >= 0x30 && (options & CollationSettings.NUMERIC) != 0) { return BAIL_OUT_RESULT; } rightPair = table[c]; } else if(PUNCT_START <= c && c < PUNCT_LIMIT) { rightPair = table[c - PUNCT_START + LATIN_LIMIT]; } else { rightPair = lookup(table, c); } if(rightPair >= MIN_SHORT) { rightPair &= SHORT_PRIMARY_MASK; break; } else if(rightPair > variableTop) { rightPair &= LONG_PRIMARY_MASK; break; } else { long pairAndInc = nextPair(table, c, rightPair, right, rightIndex); if(pairAndInc < 0) { ++rightIndex; pairAndInc = ~pairAndInc; } rightPair = (int)pairAndInc; if(rightPair == BAIL_OUT) { return BAIL_OUT_RESULT; } rightPair = getPrimaries(variableTop, rightPair); } } if(leftPair == rightPair) { if(leftPair == EOS) { break; } leftPair = rightPair = 0; continue; } int leftPrimary = leftPair & 0xffff; int rightPrimary = rightPair & 0xffff; if(leftPrimary != rightPrimary) { // Return the primary difference. return (leftPrimary < rightPrimary) ? Collation.LESS : Collation.GREATER; } if(leftPair == EOS) { break; } leftPair >>>= 16; rightPair >>>= 16; } // In the following, we need to re-fetch each character because we did not buffer the CEs, // but we know that the string is well-formed and // only contains supported characters and mappings. // We might skip the secondary level but continue with the case level // which is turned on separately. if(CollationSettings.getStrength(options) >= Collator.SECONDARY) { leftIndex = rightIndex = startIndex; leftPair = rightPair = 0; for(;;) { while(leftPair == 0) { if(leftIndex == left.length()) { leftPair = EOS; break; } int c = left.charAt(leftIndex++); if(c <= LATIN_MAX) { leftPair = table[c]; } else if(PUNCT_START <= c && c < PUNCT_LIMIT) { leftPair = table[c - PUNCT_START + LATIN_LIMIT]; } else { leftPair = lookup(table, c); } if(leftPair >= MIN_SHORT) { leftPair = getSecondariesFromOneShortCE(leftPair); break; } else if(leftPair > variableTop) { leftPair = COMMON_SEC_PLUS_OFFSET; break; } else { long pairAndInc = nextPair(table, c, leftPair, left, leftIndex); if(pairAndInc < 0) { ++leftIndex; pairAndInc = ~pairAndInc; } leftPair = getSecondaries(variableTop, (int)pairAndInc); } } while(rightPair == 0) { if(rightIndex == right.length()) { rightPair = EOS; break; } int c = right.charAt(rightIndex++); if(c <= LATIN_MAX) { rightPair = table[c]; } else if(PUNCT_START <= c && c < PUNCT_LIMIT) { rightPair = table[c - PUNCT_START + LATIN_LIMIT]; } else { rightPair = lookup(table, c); } if(rightPair >= MIN_SHORT) { rightPair = getSecondariesFromOneShortCE(rightPair); break; } else if(rightPair > variableTop) { rightPair = COMMON_SEC_PLUS_OFFSET; break; } else { long pairAndInc = nextPair(table, c, rightPair, right, rightIndex); if(pairAndInc < 0) { ++rightIndex; pairAndInc = ~pairAndInc; } rightPair = getSecondaries(variableTop, (int)pairAndInc); } } if(leftPair == rightPair) { if(leftPair == EOS) { break; } leftPair = rightPair = 0; continue; } int leftSecondary = leftPair & 0xffff; int rightSecondary = rightPair & 0xffff; if(leftSecondary != rightSecondary) { if((options & CollationSettings.BACKWARD_SECONDARY) != 0) { // Full support for backwards secondary requires backwards contraction matching // and moving backwards between merge separators. return BAIL_OUT_RESULT; } return (leftSecondary < rightSecondary) ? Collation.LESS : Collation.GREATER; } if(leftPair == EOS) { break; } leftPair >>>= 16; rightPair >>>= 16; } } if((options & CollationSettings.CASE_LEVEL) != 0) { boolean strengthIsPrimary = CollationSettings.getStrength(options) == Collator.PRIMARY; leftIndex = rightIndex = startIndex; leftPair = rightPair = 0; for(;;) { while(leftPair == 0) { if(leftIndex == left.length()) { leftPair = EOS; break; } int c = left.charAt(leftIndex++); leftPair = (c <= LATIN_MAX) ? table[c] : lookup(table, c); if(leftPair < MIN_LONG) { long pairAndInc = nextPair(table, c, leftPair, left, leftIndex); if(pairAndInc < 0) { ++leftIndex; pairAndInc = ~pairAndInc; } leftPair = (int)pairAndInc; } leftPair = getCases(variableTop, strengthIsPrimary, leftPair); } while(rightPair == 0) { if(rightIndex == right.length()) { rightPair = EOS; break; } int c = right.charAt(rightIndex++); rightPair = (c <= LATIN_MAX) ? table[c] : lookup(table, c); if(rightPair < MIN_LONG) { long pairAndInc = nextPair(table, c, rightPair, right, rightIndex); if(pairAndInc < 0) { ++rightIndex; pairAndInc = ~pairAndInc; } rightPair = (int)pairAndInc; } rightPair = getCases(variableTop, strengthIsPrimary, rightPair); } if(leftPair == rightPair) { if(leftPair == EOS) { break; } leftPair = rightPair = 0; continue; } int leftCase = leftPair & 0xffff; int rightCase = rightPair & 0xffff; if(leftCase != rightCase) { if((options & CollationSettings.UPPER_FIRST) == 0) { return (leftCase < rightCase) ? Collation.LESS : Collation.GREATER; } else { return (leftCase < rightCase) ? Collation.GREATER : Collation.LESS; } } if(leftPair == EOS) { break; } leftPair >>>= 16; rightPair >>>= 16; } } if(CollationSettings.getStrength(options) <= Collator.SECONDARY) { return Collation.EQUAL; } // Remove the case bits from the tertiary weight when caseLevel is on or caseFirst is off. boolean withCaseBits = CollationSettings.isTertiaryWithCaseBits(options); leftIndex = rightIndex = startIndex; leftPair = rightPair = 0; for(;;) { while(leftPair == 0) { if(leftIndex == left.length()) { leftPair = EOS; break; } int c = left.charAt(leftIndex++); leftPair = (c <= LATIN_MAX) ? table[c] : lookup(table, c); if(leftPair < MIN_LONG) { long pairAndInc = nextPair(table, c, leftPair, left, leftIndex); if(pairAndInc < 0) { ++leftIndex; pairAndInc = ~pairAndInc; } leftPair = (int)pairAndInc; } leftPair = getTertiaries(variableTop, withCaseBits, leftPair); } while(rightPair == 0) { if(rightIndex == right.length()) { rightPair = EOS; break; } int c = right.charAt(rightIndex++); rightPair = (c <= LATIN_MAX) ? table[c] : lookup(table, c); if(rightPair < MIN_LONG) { long pairAndInc = nextPair(table, c, rightPair, right, rightIndex); if(pairAndInc < 0) { ++rightIndex; pairAndInc = ~pairAndInc; } rightPair = (int)pairAndInc; } rightPair = getTertiaries(variableTop, withCaseBits, rightPair); } if(leftPair == rightPair) { if(leftPair == EOS) { break; } leftPair = rightPair = 0; continue; } int leftTertiary = leftPair & 0xffff; int rightTertiary = rightPair & 0xffff; if(leftTertiary != rightTertiary) { if(CollationSettings.sortsTertiaryUpperCaseFirst(options)) { // Pass through EOS and MERGE_WEIGHT // and keep real tertiary weights larger than the MERGE_WEIGHT. // Tertiary CEs (secondary ignorables) are not supported in fast Latin. if(leftTertiary > MERGE_WEIGHT) { leftTertiary ^= CASE_MASK; } if(rightTertiary > MERGE_WEIGHT) { rightTertiary ^= CASE_MASK; } } return (leftTertiary < rightTertiary) ? Collation.LESS : Collation.GREATER; } if(leftPair == EOS) { break; } leftPair >>>= 16; rightPair >>>= 16; } if(CollationSettings.getStrength(options) <= Collator.TERTIARY) { return Collation.EQUAL; } leftIndex = rightIndex = startIndex; leftPair = rightPair = 0; for(;;) { while(leftPair == 0) { if(leftIndex == left.length()) { leftPair = EOS; break; } int c = left.charAt(leftIndex++); leftPair = (c <= LATIN_MAX) ? table[c] : lookup(table, c); if(leftPair < MIN_LONG) { long pairAndInc = nextPair(table, c, leftPair, left, leftIndex); if(pairAndInc < 0) { ++leftIndex; pairAndInc = ~pairAndInc; } leftPair = (int)pairAndInc; } leftPair = getQuaternaries(variableTop, leftPair); } while(rightPair == 0) { if(rightIndex == right.length()) { rightPair = EOS; break; } int c = right.charAt(rightIndex++); rightPair = (c <= LATIN_MAX) ? table[c] : lookup(table, c); if(rightPair < MIN_LONG) { long pairAndInc = nextPair(table, c, rightPair, right, rightIndex); if(pairAndInc < 0) { ++rightIndex; pairAndInc = ~pairAndInc; } rightPair = (int)pairAndInc; } rightPair = getQuaternaries(variableTop, rightPair); } if(leftPair == rightPair) { if(leftPair == EOS) { break; } leftPair = rightPair = 0; continue; } int leftQuaternary = leftPair & 0xffff; int rightQuaternary = rightPair & 0xffff; if(leftQuaternary != rightQuaternary) { return (leftQuaternary < rightQuaternary) ? Collation.LESS : Collation.GREATER; } if(leftPair == EOS) { break; } leftPair >>>= 16; rightPair >>>= 16; } return Collation.EQUAL; } private static int lookup(char[] table, int c) { assert(c > LATIN_MAX); if(PUNCT_START <= c && c < PUNCT_LIMIT) { return table[c - PUNCT_START + LATIN_LIMIT]; } else if(c == 0xfffe) { return MERGE_WEIGHT; } else if(c == 0xffff) { return MAX_SHORT | COMMON_SEC | LOWER_CASE | COMMON_TER; } else { return BAIL_OUT; } } /** * Java returns a negative result (use the '~' operator) if sIndex is to be incremented. * C++ modifies sIndex. */ private static long nextPair(char[] table, int c, int ce, CharSequence s16, int sIndex) { if(ce >= MIN_LONG || ce < CONTRACTION) { return ce; // simple or special mini CE } else if(ce >= EXPANSION) { int index = NUM_FAST_CHARS + (ce & INDEX_MASK); return ((long)table[index + 1] << 16) | table[index]; } else /* ce >= CONTRACTION */ { // Contraction list: Default mapping followed by // 0 or more single-character contraction suffix mappings. int index = NUM_FAST_CHARS + (ce & INDEX_MASK); boolean inc = false; // true if the next char is consumed. if(sIndex != s16.length()) { // Read the next character. int c2; int nextIndex = sIndex; c2 = s16.charAt(nextIndex++); if(c2 > LATIN_MAX) { if(PUNCT_START <= c2 && c2 < PUNCT_LIMIT) { c2 = c2 - PUNCT_START + LATIN_LIMIT; // 2000..203F -> 0180..01BF } else if(c2 == 0xfffe || c2 == 0xffff) { c2 = -1; // U+FFFE & U+FFFF cannot occur in contractions. } else { return BAIL_OUT; } } // Look for the next character in the contraction suffix list, // which is in ascending order of single suffix characters. int i = index; int head = table[i]; // first skip the default mapping int x; do { i += head >> CONTR_LENGTH_SHIFT; head = table[i]; x = head & CONTR_CHAR_MASK; } while(x < c2); if(x == c2) { index = i; inc = true; } } // Return the CE or CEs for the default or contraction mapping. int length = table[index] >> CONTR_LENGTH_SHIFT; if(length == 1) { return BAIL_OUT; } ce = table[index + 1]; long result; if(length == 2) { result = ce; } else { result = ((long)table[index + 2] << 16) | ce; } return inc ? ~result : result; } } private static int getPrimaries(int variableTop, int pair) { int ce = pair & 0xffff; if(ce >= MIN_SHORT) { return pair & TWO_SHORT_PRIMARIES_MASK; } if(ce > variableTop) { return pair & TWO_LONG_PRIMARIES_MASK; } if(ce >= MIN_LONG) { return 0; } // variable return pair; // special mini CE } private static int getSecondariesFromOneShortCE(int ce) { ce &= SECONDARY_MASK; if(ce < MIN_SEC_HIGH) { return ce + SEC_OFFSET; } else { return ((ce + SEC_OFFSET) << 16) | COMMON_SEC_PLUS_OFFSET; } } private static int getSecondaries(int variableTop, int pair) { if(pair <= 0xffff) { // one mini CE if(pair >= MIN_SHORT) { pair = getSecondariesFromOneShortCE(pair); } else if(pair > variableTop) { pair = COMMON_SEC_PLUS_OFFSET; } else if(pair >= MIN_LONG) { pair = 0; // variable } // else special mini CE } else { int ce = pair & 0xffff; if(ce >= MIN_SHORT) { pair = (pair & TWO_SECONDARIES_MASK) + TWO_SEC_OFFSETS; } else if(ce > variableTop) { pair = TWO_COMMON_SEC_PLUS_OFFSET; } else { assert(ce >= MIN_LONG); pair = 0; // variable } } return pair; } private static int getCases(int variableTop, boolean strengthIsPrimary, int pair) { // Primary+caseLevel: Ignore case level weights of primary ignorables. // Otherwise: Ignore case level weights of secondary ignorables. // For details see the comments in the CollationCompare class. // Tertiary CEs (secondary ignorables) are not supported in fast Latin. if(pair <= 0xffff) { // one mini CE if(pair >= MIN_SHORT) { // A high secondary weight means we really have two CEs, // a primary CE and a secondary CE. int ce = pair; pair &= CASE_MASK; // explicit weight of primary CE if(!strengthIsPrimary && (ce & SECONDARY_MASK) >= MIN_SEC_HIGH) { pair |= LOWER_CASE << 16; // implied weight of secondary CE } } else if(pair > variableTop) { pair = LOWER_CASE; } else if(pair >= MIN_LONG) { pair = 0; // variable } // else special mini CE } else { // two mini CEs, same primary groups, neither expands like above int ce = pair & 0xffff; if(ce >= MIN_SHORT) { if(strengthIsPrimary && (pair & (SHORT_PRIMARY_MASK << 16)) == 0) { pair &= CASE_MASK; } else { pair &= TWO_CASES_MASK; } } else if(ce > variableTop) { pair = TWO_LOWER_CASES; } else { assert(ce >= MIN_LONG); pair = 0; // variable } } return pair; } private static int getTertiaries(int variableTop, boolean withCaseBits, int pair) { if(pair <= 0xffff) { // one mini CE if(pair >= MIN_SHORT) { // A high secondary weight means we really have two CEs, // a primary CE and a secondary CE. int ce = pair; if(withCaseBits) { pair = (pair & CASE_AND_TERTIARY_MASK) + TER_OFFSET; if((ce & SECONDARY_MASK) >= MIN_SEC_HIGH) { pair |= (LOWER_CASE | COMMON_TER_PLUS_OFFSET) << 16; } } else { pair = (pair & TERTIARY_MASK) + TER_OFFSET; if((ce & SECONDARY_MASK) >= MIN_SEC_HIGH) { pair |= COMMON_TER_PLUS_OFFSET << 16; } } } else if(pair > variableTop) { pair = (pair & TERTIARY_MASK) + TER_OFFSET; if(withCaseBits) { pair |= LOWER_CASE; } } else if(pair >= MIN_LONG) { pair = 0; // variable } // else special mini CE } else { // two mini CEs, same primary groups, neither expands like above int ce = pair & 0xffff; if(ce >= MIN_SHORT) { if(withCaseBits) { pair &= TWO_CASES_MASK | TWO_TERTIARIES_MASK; } else { pair &= TWO_TERTIARIES_MASK; } pair += TWO_TER_OFFSETS; } else if(ce > variableTop) { pair = (pair & TWO_TERTIARIES_MASK) + TWO_TER_OFFSETS; if(withCaseBits) { pair |= TWO_LOWER_CASES; } } else { assert(ce >= MIN_LONG); pair = 0; // variable } } return pair; } private static int getQuaternaries(int variableTop, int pair) { // Return the primary weight of a variable CE, // or the maximum primary weight for a non-variable, not-completely-ignorable CE. if(pair <= 0xffff) { // one mini CE if(pair >= MIN_SHORT) { // A high secondary weight means we really have two CEs, // a primary CE and a secondary CE. if((pair & SECONDARY_MASK) >= MIN_SEC_HIGH) { pair = TWO_SHORT_PRIMARIES_MASK; } else { pair = SHORT_PRIMARY_MASK; } } else if(pair > variableTop) { pair = SHORT_PRIMARY_MASK; } else if(pair >= MIN_LONG) { pair &= LONG_PRIMARY_MASK; // variable } // else special mini CE } else { // two mini CEs, same primary groups, neither expands like above int ce = pair & 0xffff; if(ce > variableTop) { pair = TWO_SHORT_PRIMARIES_MASK; } else { assert(ce >= MIN_LONG); pair &= TWO_LONG_PRIMARIES_MASK; // variable } } return pair; } private CollationFastLatin() {} // no constructor }
googleapis/google-api-java-client-services
38,095
clients/google-api-services-compute/alpha/1.28.0/com/google/api/services/compute/model/Subnetwork.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.compute.model; /** * Represents a Subnetwork resource. * * A subnetwork (also known as a subnet) is a logical partition of a Virtual Private Cloud network * with one primary IP range and zero or more secondary IP ranges. For more information, read * Virtual Private Cloud (VPC) Network. (== resource_for beta.subnetworks ==) (== resource_for * v1.subnetworks ==) * * <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 Compute Engine 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 Subnetwork extends com.google.api.client.json.GenericJson { /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Sets the aggregation * interval for collecting flow logs. Increasing the interval time reduces the amount of generated * flow logs for long-lasting connections. Default is an interval of 5 seconds per connection. * Valid values: INTERVAL_5_SEC, INTERVAL_30_SEC, INTERVAL_1_MIN, INTERVAL_5_MIN, INTERVAL_10_MIN, * INTERVAL_15_MIN. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String aggregationInterval; /** * Whether this subnetwork can conflict with static routes. Setting this to true allows this * subnetwork's primary and secondary ranges to conflict with routes that have already been * configured on the corresponding network. Static routes will take precedence over the subnetwork * route if the route prefix length is at least as large as the subnetwork prefix length. * * Also, packets destined to IPs within subnetwork may contain private/sensitive data and are * prevented from leaving the virtual network. Setting this field to true will disable this * feature. * * The default value is false and applies to all existing subnetworks and automatically created * subnetworks. * * This field cannot be set to true at resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean allowSubnetCidrRoutesOverlap; /** * [Output Only] Creation timestamp in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * An optional description of this resource. Provide this property when you create the resource. * This field can be set only at resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it * will not appear in get listings. If not set the default behavior is to disable flow logging. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableFlowLogs; /** * Deprecated in favor of enable in PrivateIpv6GoogleAccess. Whether the VMs in this subnet can * directly access Google services via internal IPv6 addresses. This field can be both set at * resource creation time and updated using patch. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enablePrivateV6Access; /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the * field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 * means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5, which * means half of all collected logs are reported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float flowSampling; /** * [Output Only] The gateway address for default routes to reach destination addresses outside * this subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String gatewayAddress; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * The range of internal addresses that are owned by this subnetwork. Provide this property when * you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and * non-overlapping within a network. Only IPv4 is supported. This field can be set only at * resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ipCidrRange; /** * [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ipv6CidrRange; /** * [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, * logs are exported to Stackdriver. * The value may be {@code null}. */ @com.google.api.client.util.Key private SubnetworkLogConfig logConfig; /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether * metadata fields should be added to the reported VPC flow logs. Default is INCLUDE_ALL_METADATA. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String metadata; /** * The name of the resource, provided by the client when initially creating the resource. The name * must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 * characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the * first character must be a lowercase letter, and all following characters must be a dash, * lowercase letter, or digit, except the last character, which cannot be a dash. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The URL of the network to which this subnetwork belongs, provided by the client when initially * creating the subnetwork. Only networks that are in the distributed mode can have subnetworks. * This field can be set only at resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * Whether the VMs in this subnet can access Google services without assigned external IP * addresses. This field can be both set at resource creation time and updated using * setPrivateIpGoogleAccess. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean privateIpGoogleAccess; /** * The private IPv6 google access type for the VMs in this subnet. This is an expanded field of * enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. * * This field can be both set at resource creation time and updated using patch. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String privateIpv6GoogleAccess; /** * The service accounts can be used to selectively turn on Private IPv6 Google Access only on the * VMs primary service account matching the value. This value only takes effect when * PrivateIpv6GoogleAccess is ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS or * ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> privateIpv6GoogleAccessServiceAccounts; /** * The purpose of the resource. This field can be either PRIVATE_RFC_1918 or * INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is * a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, * the purpose defaults to PRIVATE_RFC_1918. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String purpose; /** * The type of IP CIDR range to associate with this subnetwork. The default is RFC_1918. When * creating a subnetwork in non-RFC 1918 range, this field must be set to NON_RFC_1918. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String rangeType; /** * URL of the region where the Subnetwork resides. This field can be set only at resource creation * time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String region; /** * The role of subnetwork. Currenly, this field is only used when purpose = * INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is * one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is * one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated * with a patch request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String role; /** * An array of configurations for secondary IP ranges for VM instances contained in this * subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. * The alias IPs may belong to either primary or secondary ranges. This field can be updated with * a patch request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<SubnetworkSecondaryRange> secondaryIpRanges; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * [Output Only] The state of the subnetwork, which can be one of READY or DRAINING. A subnetwork * that is READY is ready to be used. The state of DRAINING is only applicable to subnetworks that * have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load * balancer are being drained. A subnetwork that is draining cannot be used or modified until it * reaches a status of READY. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String state; /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Sets the aggregation * interval for collecting flow logs. Increasing the interval time reduces the amount of generated * flow logs for long-lasting connections. Default is an interval of 5 seconds per connection. * Valid values: INTERVAL_5_SEC, INTERVAL_30_SEC, INTERVAL_1_MIN, INTERVAL_5_MIN, INTERVAL_10_MIN, * INTERVAL_15_MIN. * @return value or {@code null} for none */ public java.lang.String getAggregationInterval() { return aggregationInterval; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Sets the aggregation * interval for collecting flow logs. Increasing the interval time reduces the amount of generated * flow logs for long-lasting connections. Default is an interval of 5 seconds per connection. * Valid values: INTERVAL_5_SEC, INTERVAL_30_SEC, INTERVAL_1_MIN, INTERVAL_5_MIN, INTERVAL_10_MIN, * INTERVAL_15_MIN. * @param aggregationInterval aggregationInterval or {@code null} for none */ public Subnetwork setAggregationInterval(java.lang.String aggregationInterval) { this.aggregationInterval = aggregationInterval; return this; } /** * Whether this subnetwork can conflict with static routes. Setting this to true allows this * subnetwork's primary and secondary ranges to conflict with routes that have already been * configured on the corresponding network. Static routes will take precedence over the subnetwork * route if the route prefix length is at least as large as the subnetwork prefix length. * * Also, packets destined to IPs within subnetwork may contain private/sensitive data and are * prevented from leaving the virtual network. Setting this field to true will disable this * feature. * * The default value is false and applies to all existing subnetworks and automatically created * subnetworks. * * This field cannot be set to true at resource creation time. * @return value or {@code null} for none */ public java.lang.Boolean getAllowSubnetCidrRoutesOverlap() { return allowSubnetCidrRoutesOverlap; } /** * Whether this subnetwork can conflict with static routes. Setting this to true allows this * subnetwork's primary and secondary ranges to conflict with routes that have already been * configured on the corresponding network. Static routes will take precedence over the subnetwork * route if the route prefix length is at least as large as the subnetwork prefix length. * * Also, packets destined to IPs within subnetwork may contain private/sensitive data and are * prevented from leaving the virtual network. Setting this field to true will disable this * feature. * * The default value is false and applies to all existing subnetworks and automatically created * subnetworks. * * This field cannot be set to true at resource creation time. * @param allowSubnetCidrRoutesOverlap allowSubnetCidrRoutesOverlap or {@code null} for none */ public Subnetwork setAllowSubnetCidrRoutesOverlap(java.lang.Boolean allowSubnetCidrRoutesOverlap) { this.allowSubnetCidrRoutesOverlap = allowSubnetCidrRoutesOverlap; return this; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Subnetwork setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * An optional description of this resource. Provide this property when you create the resource. * This field can be set only at resource creation time. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this property when you create the resource. * This field can be set only at resource creation time. * @param description description or {@code null} for none */ public Subnetwork setDescription(java.lang.String description) { this.description = description; return this; } /** * Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it * will not appear in get listings. If not set the default behavior is to disable flow logging. * @return value or {@code null} for none */ public java.lang.Boolean getEnableFlowLogs() { return enableFlowLogs; } /** * Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it * will not appear in get listings. If not set the default behavior is to disable flow logging. * @param enableFlowLogs enableFlowLogs or {@code null} for none */ public Subnetwork setEnableFlowLogs(java.lang.Boolean enableFlowLogs) { this.enableFlowLogs = enableFlowLogs; return this; } /** * Deprecated in favor of enable in PrivateIpv6GoogleAccess. Whether the VMs in this subnet can * directly access Google services via internal IPv6 addresses. This field can be both set at * resource creation time and updated using patch. * @return value or {@code null} for none */ public java.lang.Boolean getEnablePrivateV6Access() { return enablePrivateV6Access; } /** * Deprecated in favor of enable in PrivateIpv6GoogleAccess. Whether the VMs in this subnet can * directly access Google services via internal IPv6 addresses. This field can be both set at * resource creation time and updated using patch. * @param enablePrivateV6Access enablePrivateV6Access or {@code null} for none */ public Subnetwork setEnablePrivateV6Access(java.lang.Boolean enablePrivateV6Access) { this.enablePrivateV6Access = enablePrivateV6Access; return this; } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #decodeFingerprint() * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #getFingerprint() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeFingerprint() { return com.google.api.client.util.Base64.decodeBase64(fingerprint); } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #encodeFingerprint() * @param fingerprint fingerprint or {@code null} for none */ public Subnetwork setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #setFingerprint() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public Subnetwork encodeFingerprint(byte[] fingerprint) { this.fingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(fingerprint); return this; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the * field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 * means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5, which * means half of all collected logs are reported. * @return value or {@code null} for none */ public java.lang.Float getFlowSampling() { return flowSampling; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the * field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 * means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5, which * means half of all collected logs are reported. * @param flowSampling flowSampling or {@code null} for none */ public Subnetwork setFlowSampling(java.lang.Float flowSampling) { this.flowSampling = flowSampling; return this; } /** * [Output Only] The gateway address for default routes to reach destination addresses outside * this subnetwork. * @return value or {@code null} for none */ public java.lang.String getGatewayAddress() { return gatewayAddress; } /** * [Output Only] The gateway address for default routes to reach destination addresses outside * this subnetwork. * @param gatewayAddress gatewayAddress or {@code null} for none */ public Subnetwork setGatewayAddress(java.lang.String gatewayAddress) { this.gatewayAddress = gatewayAddress; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Subnetwork setId(java.math.BigInteger id) { this.id = id; return this; } /** * The range of internal addresses that are owned by this subnetwork. Provide this property when * you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and * non-overlapping within a network. Only IPv4 is supported. This field can be set only at * resource creation time. * @return value or {@code null} for none */ public java.lang.String getIpCidrRange() { return ipCidrRange; } /** * The range of internal addresses that are owned by this subnetwork. Provide this property when * you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and * non-overlapping within a network. Only IPv4 is supported. This field can be set only at * resource creation time. * @param ipCidrRange ipCidrRange or {@code null} for none */ public Subnetwork setIpCidrRange(java.lang.String ipCidrRange) { this.ipCidrRange = ipCidrRange; return this; } /** * [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. * @return value or {@code null} for none */ public java.lang.String getIpv6CidrRange() { return ipv6CidrRange; } /** * [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. * @param ipv6CidrRange ipv6CidrRange or {@code null} for none */ public Subnetwork setIpv6CidrRange(java.lang.String ipv6CidrRange) { this.ipv6CidrRange = ipv6CidrRange; return this; } /** * [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. * @param kind kind or {@code null} for none */ public Subnetwork setKind(java.lang.String kind) { this.kind = kind; return this; } /** * This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, * logs are exported to Stackdriver. * @return value or {@code null} for none */ public SubnetworkLogConfig getLogConfig() { return logConfig; } /** * This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, * logs are exported to Stackdriver. * @param logConfig logConfig or {@code null} for none */ public Subnetwork setLogConfig(SubnetworkLogConfig logConfig) { this.logConfig = logConfig; return this; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether * metadata fields should be added to the reported VPC flow logs. Default is INCLUDE_ALL_METADATA. * @return value or {@code null} for none */ public java.lang.String getMetadata() { return metadata; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether * metadata fields should be added to the reported VPC flow logs. Default is INCLUDE_ALL_METADATA. * @param metadata metadata or {@code null} for none */ public Subnetwork setMetadata(java.lang.String metadata) { this.metadata = metadata; return this; } /** * The name of the resource, provided by the client when initially creating the resource. The name * must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 * characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the * first character must be a lowercase letter, and all following characters must be a dash, * lowercase letter, or digit, except the last character, which cannot be a dash. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * The name of the resource, provided by the client when initially creating the resource. The name * must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 * characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the * first character must be a lowercase letter, and all following characters must be a dash, * lowercase letter, or digit, except the last character, which cannot be a dash. * @param name name or {@code null} for none */ public Subnetwork setName(java.lang.String name) { this.name = name; return this; } /** * The URL of the network to which this subnetwork belongs, provided by the client when initially * creating the subnetwork. Only networks that are in the distributed mode can have subnetworks. * This field can be set only at resource creation time. * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * The URL of the network to which this subnetwork belongs, provided by the client when initially * creating the subnetwork. Only networks that are in the distributed mode can have subnetworks. * This field can be set only at resource creation time. * @param network network or {@code null} for none */ public Subnetwork setNetwork(java.lang.String network) { this.network = network; return this; } /** * Whether the VMs in this subnet can access Google services without assigned external IP * addresses. This field can be both set at resource creation time and updated using * setPrivateIpGoogleAccess. * @return value or {@code null} for none */ public java.lang.Boolean getPrivateIpGoogleAccess() { return privateIpGoogleAccess; } /** * Whether the VMs in this subnet can access Google services without assigned external IP * addresses. This field can be both set at resource creation time and updated using * setPrivateIpGoogleAccess. * @param privateIpGoogleAccess privateIpGoogleAccess or {@code null} for none */ public Subnetwork setPrivateIpGoogleAccess(java.lang.Boolean privateIpGoogleAccess) { this.privateIpGoogleAccess = privateIpGoogleAccess; return this; } /** * The private IPv6 google access type for the VMs in this subnet. This is an expanded field of * enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. * * This field can be both set at resource creation time and updated using patch. * @return value or {@code null} for none */ public java.lang.String getPrivateIpv6GoogleAccess() { return privateIpv6GoogleAccess; } /** * The private IPv6 google access type for the VMs in this subnet. This is an expanded field of * enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. * * This field can be both set at resource creation time and updated using patch. * @param privateIpv6GoogleAccess privateIpv6GoogleAccess or {@code null} for none */ public Subnetwork setPrivateIpv6GoogleAccess(java.lang.String privateIpv6GoogleAccess) { this.privateIpv6GoogleAccess = privateIpv6GoogleAccess; return this; } /** * The service accounts can be used to selectively turn on Private IPv6 Google Access only on the * VMs primary service account matching the value. This value only takes effect when * PrivateIpv6GoogleAccess is ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS or * ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPrivateIpv6GoogleAccessServiceAccounts() { return privateIpv6GoogleAccessServiceAccounts; } /** * The service accounts can be used to selectively turn on Private IPv6 Google Access only on the * VMs primary service account matching the value. This value only takes effect when * PrivateIpv6GoogleAccess is ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS or * ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS. * @param privateIpv6GoogleAccessServiceAccounts privateIpv6GoogleAccessServiceAccounts or {@code null} for none */ public Subnetwork setPrivateIpv6GoogleAccessServiceAccounts(java.util.List<java.lang.String> privateIpv6GoogleAccessServiceAccounts) { this.privateIpv6GoogleAccessServiceAccounts = privateIpv6GoogleAccessServiceAccounts; return this; } /** * The purpose of the resource. This field can be either PRIVATE_RFC_1918 or * INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is * a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, * the purpose defaults to PRIVATE_RFC_1918. * @return value or {@code null} for none */ public java.lang.String getPurpose() { return purpose; } /** * The purpose of the resource. This field can be either PRIVATE_RFC_1918 or * INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is * a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, * the purpose defaults to PRIVATE_RFC_1918. * @param purpose purpose or {@code null} for none */ public Subnetwork setPurpose(java.lang.String purpose) { this.purpose = purpose; return this; } /** * The type of IP CIDR range to associate with this subnetwork. The default is RFC_1918. When * creating a subnetwork in non-RFC 1918 range, this field must be set to NON_RFC_1918. * @return value or {@code null} for none */ public java.lang.String getRangeType() { return rangeType; } /** * The type of IP CIDR range to associate with this subnetwork. The default is RFC_1918. When * creating a subnetwork in non-RFC 1918 range, this field must be set to NON_RFC_1918. * @param rangeType rangeType or {@code null} for none */ public Subnetwork setRangeType(java.lang.String rangeType) { this.rangeType = rangeType; return this; } /** * URL of the region where the Subnetwork resides. This field can be set only at resource creation * time. * @return value or {@code null} for none */ public java.lang.String getRegion() { return region; } /** * URL of the region where the Subnetwork resides. This field can be set only at resource creation * time. * @param region region or {@code null} for none */ public Subnetwork setRegion(java.lang.String region) { this.region = region; return this; } /** * The role of subnetwork. Currenly, this field is only used when purpose = * INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is * one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is * one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated * with a patch request. * @return value or {@code null} for none */ public java.lang.String getRole() { return role; } /** * The role of subnetwork. Currenly, this field is only used when purpose = * INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is * one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is * one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated * with a patch request. * @param role role or {@code null} for none */ public Subnetwork setRole(java.lang.String role) { this.role = role; return this; } /** * An array of configurations for secondary IP ranges for VM instances contained in this * subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. * The alias IPs may belong to either primary or secondary ranges. This field can be updated with * a patch request. * @return value or {@code null} for none */ public java.util.List<SubnetworkSecondaryRange> getSecondaryIpRanges() { return secondaryIpRanges; } /** * An array of configurations for secondary IP ranges for VM instances contained in this * subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. * The alias IPs may belong to either primary or secondary ranges. This field can be updated with * a patch request. * @param secondaryIpRanges secondaryIpRanges or {@code null} for none */ public Subnetwork setSecondaryIpRanges(java.util.List<SubnetworkSecondaryRange> secondaryIpRanges) { this.secondaryIpRanges = secondaryIpRanges; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Subnetwork setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Subnetwork setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; return this; } /** * [Output Only] The state of the subnetwork, which can be one of READY or DRAINING. A subnetwork * that is READY is ready to be used. The state of DRAINING is only applicable to subnetworks that * have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load * balancer are being drained. A subnetwork that is draining cannot be used or modified until it * reaches a status of READY. * @return value or {@code null} for none */ public java.lang.String getState() { return state; } /** * [Output Only] The state of the subnetwork, which can be one of READY or DRAINING. A subnetwork * that is READY is ready to be used. The state of DRAINING is only applicable to subnetworks that * have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load * balancer are being drained. A subnetwork that is draining cannot be used or modified until it * reaches a status of READY. * @param state state or {@code null} for none */ public Subnetwork setState(java.lang.String state) { this.state = state; return this; } @Override public Subnetwork set(String fieldName, Object value) { return (Subnetwork) super.set(fieldName, value); } @Override public Subnetwork clone() { return (Subnetwork) super.clone(); } }
googleapis/google-api-java-client-services
38,095
clients/google-api-services-compute/alpha/1.29.2/com/google/api/services/compute/model/Subnetwork.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.compute.model; /** * Represents a Subnetwork resource. * * A subnetwork (also known as a subnet) is a logical partition of a Virtual Private Cloud network * with one primary IP range and zero or more secondary IP ranges. For more information, read * Virtual Private Cloud (VPC) Network. (== resource_for beta.subnetworks ==) (== resource_for * v1.subnetworks ==) * * <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 Compute Engine 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 Subnetwork extends com.google.api.client.json.GenericJson { /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Sets the aggregation * interval for collecting flow logs. Increasing the interval time reduces the amount of generated * flow logs for long-lasting connections. Default is an interval of 5 seconds per connection. * Valid values: INTERVAL_5_SEC, INTERVAL_30_SEC, INTERVAL_1_MIN, INTERVAL_5_MIN, INTERVAL_10_MIN, * INTERVAL_15_MIN. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String aggregationInterval; /** * Whether this subnetwork can conflict with static routes. Setting this to true allows this * subnetwork's primary and secondary ranges to conflict with routes that have already been * configured on the corresponding network. Static routes will take precedence over the subnetwork * route if the route prefix length is at least as large as the subnetwork prefix length. * * Also, packets destined to IPs within subnetwork may contain private/sensitive data and are * prevented from leaving the virtual network. Setting this field to true will disable this * feature. * * The default value is false and applies to all existing subnetworks and automatically created * subnetworks. * * This field cannot be set to true at resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean allowSubnetCidrRoutesOverlap; /** * [Output Only] Creation timestamp in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * An optional description of this resource. Provide this property when you create the resource. * This field can be set only at resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it * will not appear in get listings. If not set the default behavior is to disable flow logging. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableFlowLogs; /** * Deprecated in favor of enable in PrivateIpv6GoogleAccess. Whether the VMs in this subnet can * directly access Google services via internal IPv6 addresses. This field can be both set at * resource creation time and updated using patch. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enablePrivateV6Access; /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String fingerprint; /** * Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the * field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 * means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5, which * means half of all collected logs are reported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float flowSampling; /** * [Output Only] The gateway address for default routes to reach destination addresses outside * this subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String gatewayAddress; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * The range of internal addresses that are owned by this subnetwork. Provide this property when * you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and * non-overlapping within a network. Only IPv4 is supported. This field can be set only at * resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ipCidrRange; /** * [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ipv6CidrRange; /** * [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, * logs are exported to Stackdriver. * The value may be {@code null}. */ @com.google.api.client.util.Key private SubnetworkLogConfig logConfig; /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether * metadata fields should be added to the reported VPC flow logs. Default is INCLUDE_ALL_METADATA. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String metadata; /** * The name of the resource, provided by the client when initially creating the resource. The name * must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 * characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the * first character must be a lowercase letter, and all following characters must be a dash, * lowercase letter, or digit, except the last character, which cannot be a dash. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The URL of the network to which this subnetwork belongs, provided by the client when initially * creating the subnetwork. Only networks that are in the distributed mode can have subnetworks. * This field can be set only at resource creation time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * Whether the VMs in this subnet can access Google services without assigned external IP * addresses. This field can be both set at resource creation time and updated using * setPrivateIpGoogleAccess. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean privateIpGoogleAccess; /** * The private IPv6 google access type for the VMs in this subnet. This is an expanded field of * enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. * * This field can be both set at resource creation time and updated using patch. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String privateIpv6GoogleAccess; /** * The service accounts can be used to selectively turn on Private IPv6 Google Access only on the * VMs primary service account matching the value. This value only takes effect when * PrivateIpv6GoogleAccess is ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS or * ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> privateIpv6GoogleAccessServiceAccounts; /** * The purpose of the resource. This field can be either PRIVATE_RFC_1918 or * INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is * a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, * the purpose defaults to PRIVATE_RFC_1918. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String purpose; /** * The type of IP CIDR range to associate with this subnetwork. The default is RFC_1918. When * creating a subnetwork in non-RFC 1918 range, this field must be set to NON_RFC_1918. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String rangeType; /** * URL of the region where the Subnetwork resides. This field can be set only at resource creation * time. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String region; /** * The role of subnetwork. Currenly, this field is only used when purpose = * INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is * one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is * one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated * with a patch request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String role; /** * An array of configurations for secondary IP ranges for VM instances contained in this * subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. * The alias IPs may belong to either primary or secondary ranges. This field can be updated with * a patch request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<SubnetworkSecondaryRange> secondaryIpRanges; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * [Output Only] The state of the subnetwork, which can be one of READY or DRAINING. A subnetwork * that is READY is ready to be used. The state of DRAINING is only applicable to subnetworks that * have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load * balancer are being drained. A subnetwork that is draining cannot be used or modified until it * reaches a status of READY. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String state; /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Sets the aggregation * interval for collecting flow logs. Increasing the interval time reduces the amount of generated * flow logs for long-lasting connections. Default is an interval of 5 seconds per connection. * Valid values: INTERVAL_5_SEC, INTERVAL_30_SEC, INTERVAL_1_MIN, INTERVAL_5_MIN, INTERVAL_10_MIN, * INTERVAL_15_MIN. * @return value or {@code null} for none */ public java.lang.String getAggregationInterval() { return aggregationInterval; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Sets the aggregation * interval for collecting flow logs. Increasing the interval time reduces the amount of generated * flow logs for long-lasting connections. Default is an interval of 5 seconds per connection. * Valid values: INTERVAL_5_SEC, INTERVAL_30_SEC, INTERVAL_1_MIN, INTERVAL_5_MIN, INTERVAL_10_MIN, * INTERVAL_15_MIN. * @param aggregationInterval aggregationInterval or {@code null} for none */ public Subnetwork setAggregationInterval(java.lang.String aggregationInterval) { this.aggregationInterval = aggregationInterval; return this; } /** * Whether this subnetwork can conflict with static routes. Setting this to true allows this * subnetwork's primary and secondary ranges to conflict with routes that have already been * configured on the corresponding network. Static routes will take precedence over the subnetwork * route if the route prefix length is at least as large as the subnetwork prefix length. * * Also, packets destined to IPs within subnetwork may contain private/sensitive data and are * prevented from leaving the virtual network. Setting this field to true will disable this * feature. * * The default value is false and applies to all existing subnetworks and automatically created * subnetworks. * * This field cannot be set to true at resource creation time. * @return value or {@code null} for none */ public java.lang.Boolean getAllowSubnetCidrRoutesOverlap() { return allowSubnetCidrRoutesOverlap; } /** * Whether this subnetwork can conflict with static routes. Setting this to true allows this * subnetwork's primary and secondary ranges to conflict with routes that have already been * configured on the corresponding network. Static routes will take precedence over the subnetwork * route if the route prefix length is at least as large as the subnetwork prefix length. * * Also, packets destined to IPs within subnetwork may contain private/sensitive data and are * prevented from leaving the virtual network. Setting this field to true will disable this * feature. * * The default value is false and applies to all existing subnetworks and automatically created * subnetworks. * * This field cannot be set to true at resource creation time. * @param allowSubnetCidrRoutesOverlap allowSubnetCidrRoutesOverlap or {@code null} for none */ public Subnetwork setAllowSubnetCidrRoutesOverlap(java.lang.Boolean allowSubnetCidrRoutesOverlap) { this.allowSubnetCidrRoutesOverlap = allowSubnetCidrRoutesOverlap; return this; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Subnetwork setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * An optional description of this resource. Provide this property when you create the resource. * This field can be set only at resource creation time. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this property when you create the resource. * This field can be set only at resource creation time. * @param description description or {@code null} for none */ public Subnetwork setDescription(java.lang.String description) { this.description = description; return this; } /** * Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it * will not appear in get listings. If not set the default behavior is to disable flow logging. * @return value or {@code null} for none */ public java.lang.Boolean getEnableFlowLogs() { return enableFlowLogs; } /** * Whether to enable flow logging for this subnetwork. If this field is not explicitly set, it * will not appear in get listings. If not set the default behavior is to disable flow logging. * @param enableFlowLogs enableFlowLogs or {@code null} for none */ public Subnetwork setEnableFlowLogs(java.lang.Boolean enableFlowLogs) { this.enableFlowLogs = enableFlowLogs; return this; } /** * Deprecated in favor of enable in PrivateIpv6GoogleAccess. Whether the VMs in this subnet can * directly access Google services via internal IPv6 addresses. This field can be both set at * resource creation time and updated using patch. * @return value or {@code null} for none */ public java.lang.Boolean getEnablePrivateV6Access() { return enablePrivateV6Access; } /** * Deprecated in favor of enable in PrivateIpv6GoogleAccess. Whether the VMs in this subnet can * directly access Google services via internal IPv6 addresses. This field can be both set at * resource creation time and updated using patch. * @param enablePrivateV6Access enablePrivateV6Access or {@code null} for none */ public Subnetwork setEnablePrivateV6Access(java.lang.Boolean enablePrivateV6Access) { this.enablePrivateV6Access = enablePrivateV6Access; return this; } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #decodeFingerprint() * @return value or {@code null} for none */ public java.lang.String getFingerprint() { return fingerprint; } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #getFingerprint() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeFingerprint() { return com.google.api.client.util.Base64.decodeBase64(fingerprint); } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #encodeFingerprint() * @param fingerprint fingerprint or {@code null} for none */ public Subnetwork setFingerprint(java.lang.String fingerprint) { this.fingerprint = fingerprint; return this; } /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used * in optimistic locking. This field will be ignored when inserting a Subnetwork. An up-to-date * fingerprint must be provided in order to update the Subnetwork, otherwise the request will fail * with error 412 conditionNotMet. * * To see the latest fingerprint, make a get() request to retrieve a Subnetwork. * @see #setFingerprint() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public Subnetwork encodeFingerprint(byte[] fingerprint) { this.fingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(fingerprint); return this; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the * field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 * means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5, which * means half of all collected logs are reported. * @return value or {@code null} for none */ public java.lang.Float getFlowSampling() { return flowSampling; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. The value of the * field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 * means all collected logs are reported and 0.0 means no logs are reported. Default is 0.5, which * means half of all collected logs are reported. * @param flowSampling flowSampling or {@code null} for none */ public Subnetwork setFlowSampling(java.lang.Float flowSampling) { this.flowSampling = flowSampling; return this; } /** * [Output Only] The gateway address for default routes to reach destination addresses outside * this subnetwork. * @return value or {@code null} for none */ public java.lang.String getGatewayAddress() { return gatewayAddress; } /** * [Output Only] The gateway address for default routes to reach destination addresses outside * this subnetwork. * @param gatewayAddress gatewayAddress or {@code null} for none */ public Subnetwork setGatewayAddress(java.lang.String gatewayAddress) { this.gatewayAddress = gatewayAddress; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Subnetwork setId(java.math.BigInteger id) { this.id = id; return this; } /** * The range of internal addresses that are owned by this subnetwork. Provide this property when * you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and * non-overlapping within a network. Only IPv4 is supported. This field can be set only at * resource creation time. * @return value or {@code null} for none */ public java.lang.String getIpCidrRange() { return ipCidrRange; } /** * The range of internal addresses that are owned by this subnetwork. Provide this property when * you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and * non-overlapping within a network. Only IPv4 is supported. This field can be set only at * resource creation time. * @param ipCidrRange ipCidrRange or {@code null} for none */ public Subnetwork setIpCidrRange(java.lang.String ipCidrRange) { this.ipCidrRange = ipCidrRange; return this; } /** * [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. * @return value or {@code null} for none */ public java.lang.String getIpv6CidrRange() { return ipv6CidrRange; } /** * [Output Only] The range of internal IPv6 addresses that are owned by this subnetwork. * @param ipv6CidrRange ipv6CidrRange or {@code null} for none */ public Subnetwork setIpv6CidrRange(java.lang.String ipv6CidrRange) { this.ipv6CidrRange = ipv6CidrRange; return this; } /** * [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. * @param kind kind or {@code null} for none */ public Subnetwork setKind(java.lang.String kind) { this.kind = kind; return this; } /** * This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, * logs are exported to Stackdriver. * @return value or {@code null} for none */ public SubnetworkLogConfig getLogConfig() { return logConfig; } /** * This field denotes the VPC flow logging options for this subnetwork. If logging is enabled, * logs are exported to Stackdriver. * @param logConfig logConfig or {@code null} for none */ public Subnetwork setLogConfig(SubnetworkLogConfig logConfig) { this.logConfig = logConfig; return this; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether * metadata fields should be added to the reported VPC flow logs. Default is INCLUDE_ALL_METADATA. * @return value or {@code null} for none */ public java.lang.String getMetadata() { return metadata; } /** * Can only be specified if VPC flow logging for this subnetwork is enabled. Configures whether * metadata fields should be added to the reported VPC flow logs. Default is INCLUDE_ALL_METADATA. * @param metadata metadata or {@code null} for none */ public Subnetwork setMetadata(java.lang.String metadata) { this.metadata = metadata; return this; } /** * The name of the resource, provided by the client when initially creating the resource. The name * must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 * characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the * first character must be a lowercase letter, and all following characters must be a dash, * lowercase letter, or digit, except the last character, which cannot be a dash. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * The name of the resource, provided by the client when initially creating the resource. The name * must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 * characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the * first character must be a lowercase letter, and all following characters must be a dash, * lowercase letter, or digit, except the last character, which cannot be a dash. * @param name name or {@code null} for none */ public Subnetwork setName(java.lang.String name) { this.name = name; return this; } /** * The URL of the network to which this subnetwork belongs, provided by the client when initially * creating the subnetwork. Only networks that are in the distributed mode can have subnetworks. * This field can be set only at resource creation time. * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * The URL of the network to which this subnetwork belongs, provided by the client when initially * creating the subnetwork. Only networks that are in the distributed mode can have subnetworks. * This field can be set only at resource creation time. * @param network network or {@code null} for none */ public Subnetwork setNetwork(java.lang.String network) { this.network = network; return this; } /** * Whether the VMs in this subnet can access Google services without assigned external IP * addresses. This field can be both set at resource creation time and updated using * setPrivateIpGoogleAccess. * @return value or {@code null} for none */ public java.lang.Boolean getPrivateIpGoogleAccess() { return privateIpGoogleAccess; } /** * Whether the VMs in this subnet can access Google services without assigned external IP * addresses. This field can be both set at resource creation time and updated using * setPrivateIpGoogleAccess. * @param privateIpGoogleAccess privateIpGoogleAccess or {@code null} for none */ public Subnetwork setPrivateIpGoogleAccess(java.lang.Boolean privateIpGoogleAccess) { this.privateIpGoogleAccess = privateIpGoogleAccess; return this; } /** * The private IPv6 google access type for the VMs in this subnet. This is an expanded field of * enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. * * This field can be both set at resource creation time and updated using patch. * @return value or {@code null} for none */ public java.lang.String getPrivateIpv6GoogleAccess() { return privateIpv6GoogleAccess; } /** * The private IPv6 google access type for the VMs in this subnet. This is an expanded field of * enablePrivateV6Access. If both fields are set, privateIpv6GoogleAccess will take priority. * * This field can be both set at resource creation time and updated using patch. * @param privateIpv6GoogleAccess privateIpv6GoogleAccess or {@code null} for none */ public Subnetwork setPrivateIpv6GoogleAccess(java.lang.String privateIpv6GoogleAccess) { this.privateIpv6GoogleAccess = privateIpv6GoogleAccess; return this; } /** * The service accounts can be used to selectively turn on Private IPv6 Google Access only on the * VMs primary service account matching the value. This value only takes effect when * PrivateIpv6GoogleAccess is ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS or * ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPrivateIpv6GoogleAccessServiceAccounts() { return privateIpv6GoogleAccessServiceAccounts; } /** * The service accounts can be used to selectively turn on Private IPv6 Google Access only on the * VMs primary service account matching the value. This value only takes effect when * PrivateIpv6GoogleAccess is ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS or * ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE_FOR_SERVICE_ACCOUNTS. * @param privateIpv6GoogleAccessServiceAccounts privateIpv6GoogleAccessServiceAccounts or {@code null} for none */ public Subnetwork setPrivateIpv6GoogleAccessServiceAccounts(java.util.List<java.lang.String> privateIpv6GoogleAccessServiceAccounts) { this.privateIpv6GoogleAccessServiceAccounts = privateIpv6GoogleAccessServiceAccounts; return this; } /** * The purpose of the resource. This field can be either PRIVATE_RFC_1918 or * INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is * a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, * the purpose defaults to PRIVATE_RFC_1918. * @return value or {@code null} for none */ public java.lang.String getPurpose() { return purpose; } /** * The purpose of the resource. This field can be either PRIVATE_RFC_1918 or * INTERNAL_HTTPS_LOAD_BALANCER. A subnetwork with purpose set to INTERNAL_HTTPS_LOAD_BALANCER is * a user-created subnetwork that is reserved for Internal HTTP(S) Load Balancing. If unspecified, * the purpose defaults to PRIVATE_RFC_1918. * @param purpose purpose or {@code null} for none */ public Subnetwork setPurpose(java.lang.String purpose) { this.purpose = purpose; return this; } /** * The type of IP CIDR range to associate with this subnetwork. The default is RFC_1918. When * creating a subnetwork in non-RFC 1918 range, this field must be set to NON_RFC_1918. * @return value or {@code null} for none */ public java.lang.String getRangeType() { return rangeType; } /** * The type of IP CIDR range to associate with this subnetwork. The default is RFC_1918. When * creating a subnetwork in non-RFC 1918 range, this field must be set to NON_RFC_1918. * @param rangeType rangeType or {@code null} for none */ public Subnetwork setRangeType(java.lang.String rangeType) { this.rangeType = rangeType; return this; } /** * URL of the region where the Subnetwork resides. This field can be set only at resource creation * time. * @return value or {@code null} for none */ public java.lang.String getRegion() { return region; } /** * URL of the region where the Subnetwork resides. This field can be set only at resource creation * time. * @param region region or {@code null} for none */ public Subnetwork setRegion(java.lang.String region) { this.region = region; return this; } /** * The role of subnetwork. Currenly, this field is only used when purpose = * INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is * one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is * one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated * with a patch request. * @return value or {@code null} for none */ public java.lang.String getRole() { return role; } /** * The role of subnetwork. Currenly, this field is only used when purpose = * INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to ACTIVE or BACKUP. An ACTIVE subnetwork is * one that is currently being used for Internal HTTP(S) Load Balancing. A BACKUP subnetwork is * one that is ready to be promoted to ACTIVE or is currently draining. This field can be updated * with a patch request. * @param role role or {@code null} for none */ public Subnetwork setRole(java.lang.String role) { this.role = role; return this; } /** * An array of configurations for secondary IP ranges for VM instances contained in this * subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. * The alias IPs may belong to either primary or secondary ranges. This field can be updated with * a patch request. * @return value or {@code null} for none */ public java.util.List<SubnetworkSecondaryRange> getSecondaryIpRanges() { return secondaryIpRanges; } /** * An array of configurations for secondary IP ranges for VM instances contained in this * subnetwork. The primary IP of such VM must belong to the primary ipCidrRange of the subnetwork. * The alias IPs may belong to either primary or secondary ranges. This field can be updated with * a patch request. * @param secondaryIpRanges secondaryIpRanges or {@code null} for none */ public Subnetwork setSecondaryIpRanges(java.util.List<SubnetworkSecondaryRange> secondaryIpRanges) { this.secondaryIpRanges = secondaryIpRanges; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Subnetwork setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Subnetwork setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; return this; } /** * [Output Only] The state of the subnetwork, which can be one of READY or DRAINING. A subnetwork * that is READY is ready to be used. The state of DRAINING is only applicable to subnetworks that * have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load * balancer are being drained. A subnetwork that is draining cannot be used or modified until it * reaches a status of READY. * @return value or {@code null} for none */ public java.lang.String getState() { return state; } /** * [Output Only] The state of the subnetwork, which can be one of READY or DRAINING. A subnetwork * that is READY is ready to be used. The state of DRAINING is only applicable to subnetworks that * have the purpose set to INTERNAL_HTTPS_LOAD_BALANCER and indicates that connections to the load * balancer are being drained. A subnetwork that is draining cannot be used or modified until it * reaches a status of READY. * @param state state or {@code null} for none */ public Subnetwork setState(java.lang.String state) { this.state = state; return this; } @Override public Subnetwork set(String fieldName, Object value) { return (Subnetwork) super.set(fieldName, value); } @Override public Subnetwork clone() { return (Subnetwork) super.clone(); } }
apache/derby
35,905
java/org.apache.derby.engine/org/apache/derby/iapi/sql/dictionary/SPSDescriptor.java
/* Derby - Class org.apache.derby.iapi.sql.dictionary.SPSDescriptor 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.sql.dictionary; import java.security.PrivilegedAction; import java.security.AccessController; import java.security.AccessControlException; import java.security.AccessControlContext; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import org.apache.derby.catalog.Dependable; import org.apache.derby.catalog.DependableFinder; import org.apache.derby.catalog.UUID; import org.apache.derby.shared.common.error.StandardException; import org.apache.derby.shared.common.reference.SQLState; import org.apache.derby.iapi.services.context.ContextManager; import org.apache.derby.iapi.services.context.ContextService; import org.apache.derby.shared.common.util.ArrayUtil; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.monitor.Monitor; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.iapi.services.uuid.UUIDFactory; import org.apache.derby.iapi.sql.Statement; import org.apache.derby.iapi.sql.StorablePreparedStatement; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.sql.conn.LanguageConnectionFactory; import org.apache.derby.iapi.sql.depend.DependencyManager; import org.apache.derby.iapi.sql.depend.Dependent; import org.apache.derby.iapi.sql.depend.Provider; import org.apache.derby.iapi.sql.execute.ExecPreparedStatement; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.types.DataTypeDescriptor; import org.apache.derby.iapi.types.DataTypeUtilities; import org.apache.derby.iapi.types.DataValueDescriptor; /** * A SPSDescriptor describes a Stored Prepared Statement. * It correlates to a row in SYS.SYSSTATEMENTS. * * <B>SYNCHRONIZATION</B>: Stored prepared statements * may be cached. Thus they may be shared by multiple * threads. It is very hard for two threads to try * to muck with an sps simultaeously because all ddl * (including sps recompilation) clears out the sps * cache and invalidates whatever statement held a * cached sps. But it is possible for two statements * to do a prepare execute statment at the exact * same time, so both try to do an sps.prepare() at the * same time during code generation, so we synchronize * most everything except getters on immutable objects * just to be on the safe side. * * */ public class SPSDescriptor extends UniqueSQLObjectDescriptor implements Dependent, Provider { /** * Statement types. * <UL> * <LI> SPS_TYPE_TRIGGER - trigger</LI> * <LI> SPS_TYPE_EXPLAIN - explain (<B>NOT IMPLEMENTED</B>) </LI> * <LI> SPS_TYPE_REGULAR - catchall</LI> * </UL> */ public static final char SPS_TYPE_TRIGGER = 'T'; public static final char SPS_TYPE_REGULAR = 'S'; public static final char SPS_TYPE_EXPLAIN = 'X'; /** interface to this class is: <ol> <li>public void prepare() throws StandardException; <li>public void prepareAndRelease(LanguageConnectionContext lcc) throws StandardException; <li>public void prepareAndRelease(...); <li>public String getQualifiedName(); <li>public char getType(); <li>public String getTypeAsString(); <li>public boolean isValid(); <li>public boolean initiallyCompilable(); <li>public java.sql.Timestamp getCompileTime(); <li>public void setCompileTime(); <li>public String getText(); <li>public String getUsingText(); <li>public void setUsingText(String usingText); <li>public void setUUID(UUID uuid); <li>public DataTypeDescriptor[] getParams() throws StandardException; <li>public void setParams(DataTypeDescriptor[] params); <li>Object[] getParameterDefaults() throws StandardException; <li>void setParameterDefaults(Object[] values); <li>public UUID getCompSchemaId(); <li>public ExecPreparedStatement getPreparedStatement() throws StandardException; <li>public ExecPreparedStatement getPreparedStatement(boolean recompIfInvalid) throws StandardException; <li>public void revalidate(LanguageConnectionContext lcc) throws StandardException; </ol> */ private static final int RECOMPILE = 1; private static final int INVALIDATE = 0; // Class contents private final SchemaDescriptor sd; private final String name; private final UUID compSchemaId; private final char type; private String text; private final String usingText; private final UUID uuid; private boolean valid; private ExecPreparedStatement preparedStatement; private DataTypeDescriptor params[]; private Timestamp compileTime; /** * Old code - never used. */ private Object paramDefaults[]; private final boolean initiallyCompilable; private boolean lookedUpParams; private UUIDFactory uuidFactory; // constructors /** * Constructor for a SPS Descriptor * * @param dataDictionary The data dictionary that this descriptor lives in * @param name the SPS name * @param uuid the UUID * @param suuid the schema UUID * @param compSchemaUUID the schema UUID at compilation time * @param type type * @param valid is the sps valid * @param text the text for this statement * @param initiallyCompilable is the statement initially compilable? * * @exception StandardException on error */ public SPSDescriptor (DataDictionary dataDictionary, String name, UUID uuid, UUID suuid, UUID compSchemaUUID, char type, boolean valid, String text, boolean initiallyCompilable ) throws StandardException { this( dataDictionary, name, uuid, suuid, compSchemaUUID, type, valid, text, (String) null, null, null, initiallyCompilable ); } /** * Constructor for a SPS Descriptor. Used when * constructing an SPS descriptor from a row * in SYSSTATEMENTS. * * @param dataDictionary The data dictionary that this descriptor lives in * @param name the SPS name * @param uuid the UUID * @param suuid the schema UUID * @param compSchemaUUID the schema UUID at compilation time * @param type type * @param valid is the sps valid * @param text the text for this statement * @param usingText the text for the USING clause supplied to * CREATE or ALTER STATEMENT * @param compileTime the time this was compiled * @param preparedStatement the PreparedStatement * @param initiallyCompilable is the statement initially compilable? * * @exception StandardException on error */ public SPSDescriptor (DataDictionary dataDictionary, String name, UUID uuid, UUID suuid, UUID compSchemaUUID, char type, boolean valid, String text, String usingText, Timestamp compileTime, ExecPreparedStatement preparedStatement, boolean initiallyCompilable ) throws StandardException { super( dataDictionary ); // Added this check when setUUID was removed, see DERBY-4918. if (uuid == null) { throw new IllegalArgumentException("UUID is null"); } this.name = name; this.uuid = uuid; this.type = type; this.text = text; this.usingText = usingText; this.valid = valid; this.compileTime = DataTypeUtilities.clone( compileTime ); this.sd = dataDictionary.getSchemaDescriptor(suuid, null); this.preparedStatement = preparedStatement; this.compSchemaId = compSchemaUUID; this.initiallyCompilable = initiallyCompilable; } /** * FOR TRIGGERS ONLY * <p> * Generate the class for this SPS and immediately * release it. This is useful for cases where we * don't want to immediately execute the statement * corresponding to this sps (e.g. CREATE STATEMENT). * <p> * <I>SIDE EFFECTS</I>: will update and SYSDEPENDS * with the prepared statement dependency info. * * @param lcc the language connection context * @param triggerTable the table descriptor to bind against. Had * better be null if this isn't a trigger sps. * @param tc the transaction controller * * @exception StandardException on error */ public final synchronized void prepareAndRelease ( LanguageConnectionContext lcc, TableDescriptor triggerTable, TransactionController tc ) throws StandardException { if (SanityManager.DEBUG) { if (triggerTable != null) { SanityManager.ASSERT(type == SPS_TYPE_TRIGGER, "only expect a table descriptor when we have a trigger"); } } compileStatement(lcc, triggerTable, tc); preparedStatement.makeInvalid(DependencyManager.PREPARED_STATEMENT_RELEASE, lcc); } /** * FOR TRIGGERS ONLY * <p> * Generate the class for this SPS and immediately * release it. This is useful for cases where we * don't want to immediately execute the statement * corresponding to this sps (e.g. CREATE STATEMENT). * <p> * <I>SIDE EFFECTS</I>: will update and SYSDEPENDS * with the prepared statement dependency info. * * @param lcc the language connection context * @param triggerTable the table descriptor to bind against. Had * better be null if this isn't a trigger sps. * * @exception StandardException on error */ public final synchronized void prepareAndRelease ( LanguageConnectionContext lcc, TableDescriptor triggerTable ) throws StandardException { prepareAndRelease(lcc, triggerTable, (TransactionController)null); } /** * Generate the class for this SPS and immediately * release it. This is useful for cases where we * don't want to immediately execute the statement * corresponding to this sps (e.g. CREATE STATEMENT). * <p> * <I>SIDE EFFECTS</I>: will update and SYSDEPENDS * with the prepared statement dependency info. * * @param lcc the language connection context * * @exception StandardException on error */ public final synchronized void prepareAndRelease(LanguageConnectionContext lcc) throws StandardException { prepareAndRelease(lcc, (TableDescriptor)null, (TransactionController)null); } /** * Compiles this SPS. * <p> * <em>Note:</em> This SPS may still be marked as invalid after this method * has completed, because an invalidation request may have been received * while compiling. * * @param lcc connection * @param triggerTable subject table (may be {@code null}) * @param tc transaction controller to use (may be {@code null}) * @throws StandardException if something fails */ //@GuardedBy("this") private void compileStatement ( LanguageConnectionContext lcc, TableDescriptor triggerTable, TransactionController tc ) throws StandardException { ContextManager cm = lcc.getContextManager(); LanguageConnectionFactory lcf = lcc.getLanguageConnectionFactory(); DataDictionary dd = getDataDictionary(); /* ** If we are a trigger, then we have to go ahead ** and locate the trigger's table descriptor and ** push it on the lcc. This is expensive, but ** pretty atypical since trigger actions aren't ** likely to be invalidated too often. Also, when ** possible, we already have the triggerTable. */ if (type == SPS_TYPE_TRIGGER && triggerTable == null) { // 49 because name consists of (see CreateTriggerConstantAction): // TRIGGER<ACTN|WHEN>_<UUID:36>_<UUID:36> String uuidStr = name.substring(49); triggerTable = dd.getTableDescriptor(recreateUUID(uuidStr)); if (SanityManager.DEBUG) { if (triggerTable == null) { SanityManager.THROWASSERT("couldn't find trigger table for trigger sps "+name); } } } if (triggerTable != null) { lcc.pushTriggerTable(triggerTable); } // stored statements always stored as unicode. Statement stmt = lcf.getStatement(dd.getSchemaDescriptor(compSchemaId, null), text, true); try { preparedStatement = (ExecPreparedStatement) stmt.prepareStorable( lcc, preparedStatement, getParameterDefaults(), getSchemaDescriptor(), type == SPS_TYPE_TRIGGER); } finally { if (triggerTable != null) { lcc.popTriggerTable(triggerTable); } } //If this references a SESSION schema table (temporary or permanent), then throw an exception //This is if EXECUTE STATEMENT executing a statement that was created with NOCOMPILE. Because //of NOCOMPILE, we could not catch SESSION schema table reference by the statement at //CREATE STATEMENT time. And hence need to catch such statements at EXECUTE STATEMENT time //when the query is getting compiled. if (preparedStatement.referencesSessionSchema()) throw StandardException.newException(SQLState.LANG_OPERATION_NOT_ALLOWED_ON_SESSION_SCHEMA_TABLES); setCompileTime(); setParams(preparedStatement.getParameterTypes()); if (!dd.isReadOnlyUpgrade()) { /* ** Indicate that we are going to write the data ** dictionary. We have probably already done this ** but it is ok to call startWriting more than once. */ dd.startWriting(lcc); DependencyManager dm = dd.getDependencyManager(); /* ** Clear out all the dependencies that exist ** before we recreate them so we don't grow ** SYS.SYSDEPENDS forever. */ dm.clearDependencies(lcc, this, tc); /* ** Copy over all the dependencies to me */ dm.copyDependencies(preparedStatement, // from this, // to false, // persistent only cm, tc); //If this sps is for a trigger action, then add the depenency // between this sps and the trigger table DERBY-5120 if (triggerTable != null) dm.addDependency(this, triggerTable, lcc.getContextManager()); } // mark it as valid valid = true; } /** * Gets the name of the sps. * * @return A String containing the name of the statement. */ public final String getName() { return name; } /** * Gets the full, qualified name of the statement. * * @return A String containing the name of the statement. */ public final String getQualifiedName() { return sd.getSchemaName() + "." + name; } /** * Gets the SchemaDescriptor for this SPS Descriptor. * * @return SchemaDescriptor The SchemaDescriptor. */ public final SchemaDescriptor getSchemaDescriptor() { return sd; } /** * Gets an identifier telling what type of table this is. * Types match final ints in this interface. Currently * returns SPS_TYPE_REGULAR or SPS_TYPE_TRIGGER. * * @return An identifier telling what type of statement * we are. */ public final char getType() { return type; } /** * Simple little helper function to convert your type * to a string, which is easier to use. * * @return type as a string */ public final String getTypeAsString() { return String.valueOf(type); } /** * Is the statement initially compilable? * * @return false if statement was created with the NOCOMPILE flag * true otherwise */ public boolean initiallyCompilable() { return initiallyCompilable; } /** * Validate the type. <B>NOTE</B>: Only SPS_TYPE_REGULAR * and SPS_TYPE_TRIGGER are currently valid. * * @param type the type * * @return true/false */ public static boolean validType(char type) { return (type == SPSDescriptor.SPS_TYPE_REGULAR) || (type == SPSDescriptor.SPS_TYPE_TRIGGER); } /** * The time this prepared statement was compiled * * @return the time this class was last compiled */ public final synchronized Timestamp getCompileTime() { return DataTypeUtilities.clone( compileTime ); } /** * Set the compile time to now * */ public final synchronized void setCompileTime() { compileTime = new Timestamp(System.currentTimeMillis()); } /** * Get the text used to create this statement. * Returns original text in a cleartext string. * * @return The text */ public final synchronized String getText() { return text; } /** * It is possible that when a trigger is invalidated, the generated trigger * action sql associated with it needs to be regenerated. One example * of such a case would be when ALTER TABLE on the trigger table * changes the length of a column. The need for this code was found * as part of DERBY-4874 where the Alter table had changed the length * of a varchar column from varchar(30) to varchar(64) but the generated * trigger action plan continued to use varchar(30). To fix varchar(30) in * in trigger action sql to varchar(64), we need to regenerate the * trigger action sql which is saved as stored prepared statement. This * new trigger action sql will then get updated into SYSSTATEMENTS table. * DERBY-4874 * * @param newText */ public final synchronized void setText(String newText) { text = newText; } /** * Get the text of the USING clause used on CREATE * or ALTER statement. * * @return The text */ public final String getUsingText() { return usingText; } /** * Gets the UUID of the SPS. * * @return The UUID. */ public final UUID getUUID() { return uuid; } /** * Get the array of date type descriptors for * this statement. Currently, we do a lookup * if we don't already have the parameters saved. * When SPSes are cached, the parameters should * be set up when the sps is constructed. * * @return the array of data type descriptors * * @exception StandardException on error */ public final synchronized DataTypeDescriptor[] getParams() throws StandardException { if (params == null && !lookedUpParams) { List<DataValueDescriptor> tmpDefaults = new ArrayList<DataValueDescriptor>(); params = getDataDictionary().getSPSParams(this, tmpDefaults); paramDefaults = tmpDefaults.toArray(); lookedUpParams = true; } return ArrayUtil.copy(params); } /** * Set the list of parameters for this statement * * @param params the parameter list */ public final synchronized void setParams(DataTypeDescriptor params[]) { this.params = ArrayUtil.copy(params); } /** * Get the default parameter values for this * statement. Default parameter values are * supplied by a USING clause on either a * CREATE or ALTER STATEMENT statement. * * @return the default parameter values * * @exception StandardException on error */ public final synchronized Object[] getParameterDefaults() throws StandardException { if (paramDefaults == null) { getParams(); } return ArrayUtil.copy( paramDefaults ); } /** * Set the parameter defaults for this statement. * * @param values the parameter defaults */ public final synchronized void setParameterDefaults(Object[] values) { this.paramDefaults = ArrayUtil.copy( values ); } /** * Get the preparedStatement for this statement. * If stmt is invalid or hasn't been compiled yet, * it will be recompiled. * * @return the preparedStatement * * @exception StandardException on error */ public final ExecPreparedStatement getPreparedStatement() throws StandardException { return getPreparedStatement(true); } /** * Get the preparedStatement for this statement. * Expects the prepared statement to have already * been added to SYS.SYSSTATEMENTS. * <p> * Side Effects: will update SYS.SYSSTATEMENTS with * the new plan if it needs to be recompiled. * * @param recompIfInvalid if false, never recompile even * if statement is invalid * * @return the preparedStatement * * @exception StandardException on error */ public final synchronized ExecPreparedStatement getPreparedStatement(boolean recompIfInvalid) throws StandardException { //System.out.println("preparedStatement = " + preparedStatement); /* ** Recompile if we are invalid, we don't have ** a prepared statement, or the statements activation ** has been cleared and cannot be reconstituted. */ if (recompIfInvalid && (!valid || (preparedStatement == null))) { ContextManager cm = getContextService().getCurrentContextManager(); /* ** Find the language connection context. Get ** it each time in case a connection is dropped. */ LanguageConnectionContext lcc = (LanguageConnectionContext) cm.getContext(LanguageConnectionContext.CONTEXT_ID); if (!lcc.getDataDictionary().isReadOnlyUpgrade()) { final String savepoint = lcc.getUniqueSavepointName(); // First try compiling in a nested transaction so we can // release the locks after the compilation, and not have them // sit around in the parent transaction. But if we get lock // time out in the nested transaction, then go ahead and do // the compilation in the user transaction. When doing the // compilation in the user transaction, the locks acquired for // recompilation will be released at the end of the user // transaction (commit or abort). TransactionController nestedTC; try { nestedTC = lcc.getTransactionCompile().startNestedUserTransaction( false, true); // DERBY-3693: The nested transaction may run into a lock // conflict with its parent transaction, in which case we // don't want to wait for a timeout. If a lock timeout is // detected while we're executing the nested transaction, // we ignore the error and retry in the user transaction. // When retrying in the user transaction, we'll wait for // locks if necessary. nestedTC.setNoLockWait(true); // Set a savepoint so that the work in the nested // transaction can be rolled back on error without // aborting the parent transaction. nestedTC.setSavePoint(savepoint, null); } catch (StandardException se) { // If I cannot start a Nested User Transaction use the // parent transaction to do all the work. nestedTC = null; } try { prepareAndRelease(lcc, null, nestedTC); updateSYSSTATEMENTS(lcc, RECOMPILE, nestedTC); } catch (StandardException se) { if (nestedTC != null) { // Roll back to savepoint to undo any work done by // the nested transaction. We cannot abort the nested // transaction in order to achieve the same, since // that would also abort the parent transaction. nestedTC.rollbackToSavePoint(savepoint, false, null); } if ( (nestedTC != null) && ( se.isLockTimeout() || se.isSelfDeadlock() ) ) { // Locks were set nowait, so a lock timeout here // means that some lock request in the nested // transaction immediately conflicted. A conflict // with a parent lock would lead to a undetected // deadlock so must give up trying in the nested // transaction and retry with parent transaction. nestedTC.commit(); nestedTC.destroy(); nestedTC = null; // if we couldn't do this with a nested transaction, // retry with parent-- we need to wait this time! // Lock conflicts at this point are with other // transactions, so must wait. prepareAndRelease(lcc, null, null); updateSYSSTATEMENTS(lcc, RECOMPILE, null); } else { throw se; } } finally { // no matter what, commit the nested transaction; // if something bad happened in the child transaction lets // not abort the parent here. if (nestedTC != null) { nestedTC.commit(); nestedTC.destroy(); } } } } return preparedStatement; } /** * Get the compilation type schema id when this view * was first bound. * * @return the schema UUID */ public final UUID getCompSchemaId() { return compSchemaId; } /** * Prints the contents of the TableDescriptor * * @return The contents as a String */ @Override public final String toString() { if (SanityManager.DEBUG) { return "SPSDescriptor:\n"+ "\tname: "+sd.getSchemaName()+"."+name+"\n"+ "\tuuid: "+uuid+"\n"+ "\ttext: "+text+"\n"+ "\tvalid: "+((valid) ? "TRUE" : "FALSE")+"\n" + "\tpreparedStatement: "+preparedStatement+"\n"; } else { return ""; } } ////////////////////////////////////////////////////// // // PROVIDER INTERFACE // ////////////////////////////////////////////////////// /** * Return the stored form of this provider * * @see Dependable#getDependableFinder */ public final DependableFinder getDependableFinder() { return getDependableFinder(StoredFormatIds.SPS_DESCRIPTOR_FINDER_V01_ID); } /** * Return the name of this Provider. (Useful for errors.) * * @return String The name of this provider. */ public final String getObjectName() { return name; } /** * Get the provider's UUID * * @return String The provider's UUID */ public final UUID getObjectID() { return uuid; } /** * Get the provider's type. * * @return String The provider's type. */ public final String getClassType() { return Dependable.STORED_PREPARED_STATEMENT; } ////////////////////////////////////////////////////// // // DEPENDENT INTERFACE // ////////////////////////////////////////////////////// /** * Check that all of the dependent's dependencies are valid. * * @return true if the dependent is currently valid */ public final synchronized boolean isValid() { return valid; } /** * Prepare to mark the dependent as invalid (due to at least one of * its dependencies being invalid). * * @param action The action causing the invalidation * @param p the provider * * @exception StandardException thrown if unable to make it invalid */ public final void prepareToInvalidate( Provider p, int action, LanguageConnectionContext lcc) throws StandardException { switch (action) { /* ** Things that don't affect us */ case DependencyManager.CREATE_VIEW: /* ** Things that force a recompile, but are ** allowed. */ case DependencyManager.CREATE_INDEX: case DependencyManager.CREATE_CONSTRAINT: case DependencyManager.DROP_CONSTRAINT: case DependencyManager.DROP_INDEX: case DependencyManager.DROP_TABLE: case DependencyManager.DROP_VIEW: case DependencyManager.DROP_METHOD_ALIAS: case DependencyManager.DROP_SYNONYM: case DependencyManager.ALTER_TABLE: case DependencyManager.RENAME: case DependencyManager.RENAME_INDEX: case DependencyManager.PREPARED_STATEMENT_RELEASE: case DependencyManager.USER_RECOMPILE_REQUEST: case DependencyManager.CHANGED_CURSOR: case DependencyManager.BULK_INSERT: case DependencyManager.COMPRESS_TABLE: case DependencyManager.SET_CONSTRAINTS_ENABLE: case DependencyManager.SET_CONSTRAINTS_DISABLE: case DependencyManager.SET_TRIGGERS_ENABLE: case DependencyManager.SET_TRIGGERS_DISABLE: case DependencyManager.ROLLBACK: case DependencyManager.INTERNAL_RECOMPILE_REQUEST: case DependencyManager.CREATE_TRIGGER: case DependencyManager.DROP_TRIGGER: case DependencyManager.DROP_COLUMN: case DependencyManager.DROP_COLUMN_RESTRICT: case DependencyManager.UPDATE_STATISTICS: case DependencyManager.DROP_STATISTICS: case DependencyManager.TRUNCATE_TABLE: break; /* ** The rest are errors */ default: DependencyManager dm; dm = getDataDictionary().getDependencyManager(); throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_S_P_S, dm.getActionString(action), p.getObjectName(), name); } } /** * Mark the dependent as invalid (due to at least one of * its dependencies being invalid). * * @param action The action causing the invalidation * * @exception StandardException thrown if unable to make it invalid */ public final synchronized void makeInvalid(int action, LanguageConnectionContext lcc) throws StandardException { DependencyManager dm; dm = getDataDictionary().getDependencyManager(); switch (action) { /* ** Some things that don't affect stored prepared ** statements. */ case DependencyManager.PREPARED_STATEMENT_RELEASE: case DependencyManager.CREATE_VIEW: break; /* ** Things that can invalidate a stored ** prepared statement. */ case DependencyManager.CREATE_INDEX: case DependencyManager.CREATE_CONSTRAINT: case DependencyManager.DROP_CONSTRAINT: case DependencyManager.DROP_TABLE: case DependencyManager.DROP_INDEX: case DependencyManager.DROP_VIEW: case DependencyManager.DROP_METHOD_ALIAS: case DependencyManager.DROP_SYNONYM: case DependencyManager.ALTER_TABLE: case DependencyManager.RENAME: case DependencyManager.RENAME_INDEX: case DependencyManager.USER_RECOMPILE_REQUEST: case DependencyManager.CHANGED_CURSOR: case DependencyManager.BULK_INSERT: case DependencyManager.COMPRESS_TABLE: case DependencyManager.SET_CONSTRAINTS_ENABLE: case DependencyManager.SET_CONSTRAINTS_DISABLE: case DependencyManager.SET_TRIGGERS_ENABLE: case DependencyManager.SET_TRIGGERS_DISABLE: case DependencyManager.ROLLBACK: case DependencyManager.INTERNAL_RECOMPILE_REQUEST: case DependencyManager.CREATE_TRIGGER: case DependencyManager.DROP_TRIGGER: case DependencyManager.DROP_COLUMN: case DependencyManager.DROP_COLUMN_RESTRICT: case DependencyManager.UPDATE_STATISTICS: case DependencyManager.DROP_STATISTICS: case DependencyManager.TRUNCATE_TABLE: /* ** If we are already invalid, don't write ourselves ** out. Just to be safe, we'll send out an invalidate ** to our dependents either way. */ if (valid == true) { valid = false; preparedStatement = null; updateSYSSTATEMENTS(lcc, INVALIDATE, null); } dm.invalidateFor( this, DependencyManager.USER_RECOMPILE_REQUEST, lcc); break; case DependencyManager.DROP_SPS: //System.out.println("SPSD " + preparedStatement); dm.clearDependencies(lcc, this); break; default: /* ** We should never get here, since we can't have dangling references */ if (SanityManager.DEBUG) { SanityManager.THROWASSERT("makeInvalid("+ dm.getActionString(action)+ ") not expected to get called; should have failed in "+ "prepareToInvalidate()"); } break; } } /** * Invalidate and revalidate. The functional equivalent * of calling makeInvalid() and makeValid(), except it * is optimized. * * @exception StandardException on error */ public final synchronized void revalidate(LanguageConnectionContext lcc) throws StandardException { /* ** Mark it as invalid first to ensure that ** we don't write SYSSTATEMENTS 2x. */ valid = false; makeInvalid(DependencyManager.USER_RECOMPILE_REQUEST, lcc); prepareAndRelease(lcc); updateSYSSTATEMENTS(lcc, RECOMPILE, null); } /** * Load the underlying generatd class. This is not expected * to be used outside of the datadictionary package. It * is used for optimizing class loading for sps * cacheing. * * @exception StandardException on error */ public void loadGeneratedClass() throws StandardException { /* ** On upgrade, we null out the statement body, ** so handle that here. */ if (preparedStatement != null) { ((StorablePreparedStatement)preparedStatement).loadGeneratedClass(); } } /* ** Update SYSSTATEMENTS with the changed the descriptor. ** Always done in the user XACT. ** <p> ** Ideally, the changes to SYSSTATEMENTS would be made ** in a separate xact as the current user xact, but this ** is painful (you'ld need to get a new ContextManager ** and then push all of the usual langauge contexts ** onto it and THEN call AccessManager.getTransaction()), ** and it wont work, because the xact is in a different ** compatibility space and will self deadlock (e.g. ** in the process of call DependencyManager.makeInvalid() ** we first did a DDdependableFinder.getDependable() ** which called DataDictionaryImpl.getSPSDescriptor() ** so we hold a lock on SYS.SYSSTATEMENTS by the ** time we get a 2nd xact and try to drop the statement). */ private void updateSYSSTATEMENTS(LanguageConnectionContext lcc, int mode, TransactionController tc) throws StandardException { DataDictionary dd = getDataDictionary(); if (dd.isReadOnlyUpgrade()) return; /* ** Get busy time */ dd.startWriting(lcc); if (tc == null) { //bug 4821 - tc will passed null if we want to use the user transaction tc = lcc.getTransactionExecute(); } dd.updateSPS(this, tc, (mode == RECOMPILE)); } /** * Get the UUID for the given string * * @param idString the string * * @return the UUID */ private UUID recreateUUID(String idString) { if (uuidFactory == null) { uuidFactory = DataDescriptorGenerator.getMonitor().getUUIDFactory(); } return uuidFactory.recreateUUID(idString); } /** @see TupleDescriptor#getDescriptorType */ @Override public String getDescriptorType() { return "Statement"; } /** @see TupleDescriptor#getDescriptorName */ // RESOLVE: some descriptors have getName. some descriptors have // getTableName, getColumnName whatever! try and unify all of this to one // getDescriptorName! @Override public String getDescriptorName() { return name; } /** * Privileged lookup of the ContextService. Must be private so that user code * can't call this entry point. */ private static ContextService getContextService() { if ( System.getSecurityManager() == null ) { return ContextService.getFactory(); } else { return AccessController.doPrivileged ( new PrivilegedAction<ContextService>() { public ContextService run() { return ContextService.getFactory(); } } ); } } }
googleapis/google-cloud-java
37,897
java-websecurityscanner/proto-google-cloud-websecurityscanner-v1alpha/src/main/java/com/google/cloud/websecurityscanner/v1alpha/UpdateScanConfigRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/websecurityscanner/v1alpha/web_security_scanner.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.websecurityscanner.v1alpha; /** * * * <pre> * Request for the `UpdateScanConfigRequest` method. * </pre> * * Protobuf type {@code google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest} */ public final class UpdateScanConfigRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest) UpdateScanConfigRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateScanConfigRequest.newBuilder() to construct. private UpdateScanConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateScanConfigRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateScanConfigRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto .internal_static_google_cloud_websecurityscanner_v1alpha_UpdateScanConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto .internal_static_google_cloud_websecurityscanner_v1alpha_UpdateScanConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest.class, com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest.Builder.class); } private int bitField0_; public static final int SCAN_CONFIG_FIELD_NUMBER = 2; private com.google.cloud.websecurityscanner.v1alpha.ScanConfig scanConfig_; /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the scanConfig field is set. */ @java.lang.Override public boolean hasScanConfig() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The scanConfig. */ @java.lang.Override public com.google.cloud.websecurityscanner.v1alpha.ScanConfig getScanConfig() { return scanConfig_ == null ? com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance() : scanConfig_; } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder getScanConfigOrBuilder() { return scanConfig_ == null ? com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance() : scanConfig_; } public static final int UPDATE_MASK_FIELD_NUMBER = 3; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.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(2, getScanConfig()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, 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(2, getScanConfig()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, 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.websecurityscanner.v1alpha.UpdateScanConfigRequest)) { return super.equals(obj); } com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest other = (com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest) obj; if (hasScanConfig() != other.hasScanConfig()) return false; if (hasScanConfig()) { if (!getScanConfig().equals(other.getScanConfig())) 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 (hasScanConfig()) { hash = (37 * hash) + SCAN_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getScanConfig().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.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request for the `UpdateScanConfigRequest` method. * </pre> * * Protobuf type {@code google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest) com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto .internal_static_google_cloud_websecurityscanner_v1alpha_UpdateScanConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto .internal_static_google_cloud_websecurityscanner_v1alpha_UpdateScanConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest.class, com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest.Builder.class); } // Construct using // com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getScanConfigFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; scanConfig_ = null; if (scanConfigBuilder_ != null) { scanConfigBuilder_.dispose(); scanConfigBuilder_ = 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.websecurityscanner.v1alpha.WebSecurityScannerProto .internal_static_google_cloud_websecurityscanner_v1alpha_UpdateScanConfigRequest_descriptor; } @java.lang.Override public com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest getDefaultInstanceForType() { return com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest build() { com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest buildPartial() { com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest result = new com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.scanConfig_ = scanConfigBuilder_ == null ? scanConfig_ : scanConfigBuilder_.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.websecurityscanner.v1alpha.UpdateScanConfigRequest) { return mergeFrom( (com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest other) { if (other == com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest .getDefaultInstance()) return this; if (other.hasScanConfig()) { mergeScanConfig(other.getScanConfig()); } 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 18: { input.readMessage(getScanConfigFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 18 case 26: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.websecurityscanner.v1alpha.ScanConfig scanConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.websecurityscanner.v1alpha.ScanConfig, com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder, com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder> scanConfigBuilder_; /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the scanConfig field is set. */ public boolean hasScanConfig() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The scanConfig. */ public com.google.cloud.websecurityscanner.v1alpha.ScanConfig getScanConfig() { if (scanConfigBuilder_ == null) { return scanConfig_ == null ? com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance() : scanConfig_; } else { return scanConfigBuilder_.getMessage(); } } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setScanConfig(com.google.cloud.websecurityscanner.v1alpha.ScanConfig value) { if (scanConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } scanConfig_ = value; } else { scanConfigBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setScanConfig( com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder builderForValue) { if (scanConfigBuilder_ == null) { scanConfig_ = builderForValue.build(); } else { scanConfigBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeScanConfig(com.google.cloud.websecurityscanner.v1alpha.ScanConfig value) { if (scanConfigBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && scanConfig_ != null && scanConfig_ != com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance()) { getScanConfigBuilder().mergeFrom(value); } else { scanConfig_ = value; } } else { scanConfigBuilder_.mergeFrom(value); } if (scanConfig_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearScanConfig() { bitField0_ = (bitField0_ & ~0x00000001); scanConfig_ = null; if (scanConfigBuilder_ != null) { scanConfigBuilder_.dispose(); scanConfigBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder getScanConfigBuilder() { bitField0_ |= 0x00000001; onChanged(); return getScanConfigFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder getScanConfigOrBuilder() { if (scanConfigBuilder_ != null) { return scanConfigBuilder_.getMessageOrBuilder(); } else { return scanConfig_ == null ? com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance() : scanConfig_; } } /** * * * <pre> * Required. The ScanConfig to be updated. The name field must be set to identify the * resource to be updated. The values of fields not covered by the mask * will be ignored. * </pre> * * <code> * .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_config = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.websecurityscanner.v1alpha.ScanConfig, com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder, com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder> getScanConfigFieldBuilder() { if (scanConfigBuilder_ == null) { scanConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.websecurityscanner.v1alpha.ScanConfig, com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder, com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder>( getScanConfig(), getParentForChildren(), isClean()); scanConfig_ = null; } return scanConfigBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest) } // @@protoc_insertion_point(class_scope:google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest) private static final com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest(); } public static com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateScanConfigRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateScanConfigRequest>() { @java.lang.Override public UpdateScanConfigRequest 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<UpdateScanConfigRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateScanConfigRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.websecurityscanner.v1alpha.UpdateScanConfigRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ignite-3
37,643
modules/jdbc/src/integrationTest/java/org/apache/ignite/jdbc/ItJdbcResultSetSelfTest.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.jdbc; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.InputStream; import java.io.Reader; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.Period; import java.util.GregorianCalendar; import java.util.UUID; import org.apache.ignite.internal.tostring.S; import org.apache.ignite.jdbc.util.JdbcTestUtils; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * Result set test. */ public class ItJdbcResultSetSelfTest extends AbstractJdbcSelfTest { /** SQL static query. */ private static final String STATIC_SQL = "SELECT 1::INTEGER as id, true as boolVal, 1::TINYINT as byteVal, 1::SMALLINT as shortVal, 1::INTEGER as intVal, 1::BIGINT " + "as longVal, 1.0::FLOAT as floatVal, 1.0::DOUBLE as doubleVal, 1.0::DECIMAL as bigVal, " + "'1' as strVal, '1', '1901-02-01'::DATE as dateVal, '01:01:01'::TIME as timeVal, " + "TIMESTAMP '1970-01-01 00:00:00' as tsVal, 'fd10556e-fc27-4a99-b5e4-89b8344cb3ce'::UUID as uuidVal"; /** SQL query. */ private static final String SQL_SINGLE_RES = "select id, boolVal, byteVal, shortVal, intVal, longVal, floatVal, " + "doubleVal, bigVal, strVal, uuidVal from TEST WHERE id = 1"; @BeforeAll public static void beforeClass() throws SQLException { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("CREATE TABLE test(" + "id INT PRIMARY KEY," + "boolval TINYINT," + "byteval TINYINT," + "shortval SMALLINT," + "intval INT," + "longval BIGINT," + "floatval FLOAT," + "doubleval DOUBLE," + "bigval DECIMAL(10, 3)," + "strval VARCHAR," + "arrval VARBINARY," + "dateval DATE," + "timeval TIME," + "tsval TIMESTAMP," + "urlval VARBINARY," + "uuidVal UUID" + ")" ); stmt.executeUpdate("INSERT INTO test (" + "id, boolval, byteval, shortval, intval, longval, floatval, doubleval, bigval, strval," + "dateval, timeval, tsval, uuidVal) " + "VALUES (1, 1, 1, 1, 1, 1, 1.0, 1.0, 1, '1', " + "date '1901-02-01', time '01:01:01', timestamp '1970-01-01 00:00:01', 'fd10556e-fc27-4a99-b5e4-89b8344cb3ce'::UUID)"); stmt.executeUpdate("INSERT INTO test (" + "id, boolval, byteval, shortval, intval, longval, floatval, doubleval, bigval, strval," + "dateval, timeval, tsval, uuidVal) " + "VALUES (2, 1, 1, 1, 1, 1, 1.0, 1.0, 1, '1', " + "date '1901-02-01', time '01:01:01', timestamp '1970-01-01 00:00:01', 'fd10556e-fc27-4a99-b5e4-89b8344cb3ce'::UUID)"); } } @Test public void testIntervalResult() throws SQLException { assertEquals(Duration.ofDays(4), eval("INTERVAL '4' DAYS")); assertEquals(Duration.ofSeconds(1), eval("INTERVAL '1' SECONDS")); assertEquals(Duration.ofSeconds(-1), eval("INTERVAL - '1' SECONDS")); assertEquals(Duration.ofSeconds(-1), eval("INTERVAL '-1' SECONDS")); assertEquals(Duration.ofSeconds(123), eval("INTERVAL '123' SECONDS")); assertEquals(Duration.ofSeconds(123), eval("INTERVAL '123' SECONDS(3)")); assertEquals(Duration.ofMinutes(2), eval("INTERVAL '2' MINUTES")); assertEquals(Duration.ofHours(3), eval("INTERVAL '3' HOURS")); assertEquals(Duration.ofDays(4), eval("INTERVAL '4' DAYS")); assertEquals(Period.ofMonths(5), eval("INTERVAL '5' MONTHS")); assertEquals(Period.ofMonths(-5), eval("INTERVAL - '5' MONTHS")); assertEquals(Period.ofMonths(-5), eval("INTERVAL '-5' MONTHS")); assertEquals(Period.ofYears(6), eval("INTERVAL '6' YEARS")); assertEquals(Period.of(1, 2, 0), eval("INTERVAL '1-2' YEAR TO MONTH")); assertEquals(Duration.ofHours(25), eval("INTERVAL '1 1' DAY TO HOUR")); assertEquals(Duration.ofMinutes(62), eval("INTERVAL '1:2' HOUR TO MINUTE")); assertEquals(Duration.ofSeconds(63), eval("INTERVAL '1:3' MINUTE TO SECOND")); assertEquals(Duration.ofSeconds(3723), eval("INTERVAL '1:2:3' HOUR TO SECOND")); assertEquals(Duration.ofMillis(3723456), eval("INTERVAL '0 1:2:3.456' DAY TO SECOND")); assertEquals(Duration.ofSeconds(123), eval("INTERVAL '123' SECONDS")); assertEquals(Duration.ofMillis(123987), eval("INTERVAL '123.987' SECONDS")); } @Test public void testTemporalArithmetic() throws SQLException { assertEquals(LocalDate.parse("2021-01-02"), eval("DATE '2021-01-01' + interval '1' days")); assertEquals(Period.ofMonths(2), eval("(DATE '2021-03-01' - DATE '2021-01-01') months")); assertEquals(Duration.ofHours(24), eval("(DATE '2021-03-02' - DATE '2021-03-01') hours")); assertEquals(Duration.ofHours(48), eval("INTERVAL '3' DAYS - INTERVAL '1' DAYS")); assertEquals(Period.ofMonths(1), eval("INTERVAL '5' MONTHS - INTERVAL '4' MONTHS")); assertEquals(Duration.ofSeconds(1), eval("INTERVAL '5' SECONDS - INTERVAL '4' SECONDS")); assertEquals(Duration.ofSeconds(10), eval("INTERVAL '5' SECONDS * 2")); } private Object eval(String exp) throws SQLException { ResultSet r = stmt.executeQuery("SELECT " + exp); r.next(); return r.getObject(1); } @Test public void testBoolean() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertTrue(rs.getBoolean("boolVal")); assertTrue(rs.getBoolean(2)); assertEquals(1, rs.getByte(2)); assertEquals(1, rs.getInt(2)); assertEquals(1, rs.getShort(2)); assertEquals(1, rs.getLong(2)); assertEquals(1.0, rs.getDouble(2)); assertEquals(1.0f, rs.getFloat(2)); assertEquals(new BigDecimal(1), rs.getBigDecimal(2)); assertEquals(rs.getString(2), "1"); // Because we don't support bool values right now. assertTrue(rs.getObject(2, Boolean.class)); assertEquals((byte) 1, rs.getObject(2, Byte.class)); assertEquals((short) 1, rs.getObject(2, Short.class)); assertEquals(1, rs.getObject(2, Integer.class)); assertEquals(1, rs.getObject(2, Long.class)); assertEquals(1.0f, rs.getObject(2, Float.class)); assertEquals(1.0, rs.getObject(2, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(2, BigDecimal.class)); assertEquals("1", rs.getObject(2, String.class)); // Because we don't support bool values right now. } cnt++; } assertEquals(1, cnt); ResultSet rs0 = stmt.executeQuery("select 1"); assertTrue(rs0.next()); assertTrue(rs0.getBoolean(1)); rs0 = stmt.executeQuery("select 0"); assertTrue(rs0.next()); assertFalse(rs0.getBoolean(1)); rs0 = stmt.executeQuery("select '1'"); assertTrue(rs0.next()); assertTrue(rs0.getBoolean(1)); rs0 = stmt.executeQuery("select '0'"); assertTrue(rs0.next()); assertFalse(rs0.getBoolean(1)); JdbcTestUtils.assertThrowsSqlException( "Cannot convert to boolean: ", () -> { ResultSet badRs = stmt.executeQuery("select ''"); assertTrue(badRs.next()); assertTrue(badRs.getBoolean(1)); }); JdbcTestUtils.assertThrowsSqlException( "Cannot convert to boolean: qwe", () -> { ResultSet badRs = stmt.executeQuery("select 'qwe'"); assertTrue(badRs.next()); assertTrue(badRs.getBoolean(1)); }); } @Test public void testByte() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1, rs.getByte("byteVal")); assertTrue(rs.getBoolean(3)); assertEquals(1, rs.getByte(3)); assertEquals(1, rs.getInt(3)); assertEquals(1, rs.getShort(3)); assertEquals(1, rs.getLong(3)); assertEquals(1.0, rs.getDouble(3)); assertEquals(1.0f, rs.getFloat(3)); assertEquals(new BigDecimal(1), rs.getBigDecimal(3)); assertEquals(rs.getString(3), "1"); assertTrue(rs.getObject(3, Boolean.class)); assertEquals((byte) 1, rs.getObject(3, Byte.class)); assertEquals((short) 1, rs.getObject(3, Short.class)); assertEquals(1, rs.getObject(3, Integer.class)); assertEquals(1, rs.getObject(3, Long.class)); assertEquals(1.f, rs.getObject(3, Float.class)); assertEquals(1, rs.getObject(3, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(3, BigDecimal.class)); assertArrayEquals(new byte[]{1}, rs.getBytes(3)); assertEquals(rs.getObject(3, String.class), "1"); } cnt++; } assertEquals(1, cnt); } @Test public void testShort() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1, rs.getShort("shortVal")); assertTrue(rs.getBoolean(4)); assertEquals(1, rs.getByte(4)); assertEquals(1, rs.getShort(4)); assertEquals(1, rs.getInt(4)); assertEquals(1, rs.getLong(4)); assertEquals(1.0, rs.getDouble(4)); assertEquals(1.0f, rs.getFloat(4)); assertEquals(new BigDecimal(1), rs.getBigDecimal(4)); assertEquals(rs.getString(4), "1"); assertTrue(rs.getObject(4, Boolean.class)); assertEquals((byte) 1, rs.getObject(4, Byte.class)); assertEquals((short) 1, rs.getObject(4, Short.class)); assertEquals(1, rs.getObject(4, Integer.class)); assertEquals(1, rs.getObject(4, Long.class)); assertEquals(1.f, rs.getObject(4, Float.class)); assertEquals(1, rs.getObject(4, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(4, BigDecimal.class)); assertArrayEquals(new byte[]{0, 1}, rs.getBytes(4)); assertEquals(rs.getObject(4, String.class), "1"); } cnt++; } assertEquals(1, cnt); } @Test public void testInteger() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1, rs.getInt("intVal")); assertTrue(rs.getBoolean(5)); assertEquals(1, rs.getByte(5)); assertEquals(1, rs.getShort(5)); assertEquals(1, rs.getInt(5)); assertEquals(1, rs.getLong(5)); assertEquals(1.0, rs.getDouble(5)); assertEquals(1.0f, rs.getFloat(5)); assertEquals(new BigDecimal(1), rs.getBigDecimal(5)); assertEquals(rs.getString(5), "1"); assertTrue(rs.getObject(5, Boolean.class)); assertEquals((byte) 1, rs.getObject(5, Byte.class)); assertEquals((short) 1, rs.getObject(5, Short.class)); assertEquals(1, rs.getObject(5, Integer.class)); assertEquals(1, rs.getObject(5, Long.class)); assertEquals(1.f, rs.getObject(5, Float.class)); assertEquals(1, rs.getObject(5, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(5, BigDecimal.class)); assertArrayEquals(new byte[]{0, 0, 0, 1}, rs.getBytes(5)); assertEquals(rs.getObject(5, String.class), "1"); } cnt++; } assertEquals(1, cnt); } @Test public void testLong() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1, rs.getLong("longVal")); assertTrue(rs.getBoolean(6)); assertEquals(1, rs.getByte(6)); assertEquals(1, rs.getShort(6)); assertEquals(1, rs.getInt(6)); assertEquals(1, rs.getLong(6)); assertEquals(1.0, rs.getDouble(6)); assertEquals(1.0f, rs.getFloat(6)); assertEquals(new BigDecimal(1), rs.getBigDecimal(6)); assertEquals(rs.getString(6), "1"); assertTrue(rs.getObject(6, Boolean.class)); assertEquals((byte) 1, rs.getObject(6, Byte.class)); assertEquals((short) 1, rs.getObject(6, Short.class)); assertEquals(1, rs.getObject(6, Integer.class)); assertEquals(1, rs.getObject(6, Long.class)); assertEquals(1.f, rs.getObject(6, Float.class)); assertEquals(1, rs.getObject(6, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(6, BigDecimal.class)); assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 1}, rs.getBytes(6)); assertEquals(rs.getObject(6, String.class), "1"); } cnt++; } assertEquals(1, cnt); } @Test public void testFloat() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1.0, rs.getFloat("floatVal")); assertTrue(rs.getBoolean(7)); assertEquals(1, rs.getByte(7)); assertEquals(1, rs.getShort(7)); assertEquals(1, rs.getInt(7)); assertEquals(1, rs.getLong(7)); assertEquals(1.0, rs.getDouble(7)); assertEquals(1.0f, rs.getFloat(7)); assertEquals(new BigDecimal(1), rs.getBigDecimal(7)); assertEquals(rs.getString(7), "1.0"); assertTrue(rs.getObject(7, Boolean.class)); assertEquals((byte) 1, rs.getObject(7, Byte.class)); assertEquals((short) 1, rs.getObject(7, Short.class)); assertEquals(1, rs.getObject(7, Integer.class)); assertEquals(1, rs.getObject(7, Long.class)); assertEquals(1.f, rs.getObject(7, Float.class)); assertEquals(1, rs.getObject(7, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(7, BigDecimal.class)); assertArrayEquals(new byte[]{63, -128, 0, 0}, rs.getBytes(7)); assertEquals(rs.getObject(7, String.class), "1.0"); } cnt++; } assertEquals(1, cnt); } @Test public void testDouble() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1.0, rs.getDouble("doubleVal")); assertTrue(rs.getBoolean(8)); assertEquals(1, rs.getByte(8)); assertEquals(1, rs.getShort(8)); assertEquals(1, rs.getInt(8)); assertEquals(1, rs.getLong(8)); assertEquals(1.0, rs.getDouble(8)); assertEquals(1.0f, rs.getFloat(8)); assertEquals(new BigDecimal(1), rs.getBigDecimal(8)); assertEquals(rs.getString(8), "1.0"); assertTrue(rs.getObject(8, Boolean.class)); assertEquals((byte) 1, rs.getObject(8, Byte.class)); assertEquals((short) 1, rs.getObject(8, Short.class)); assertEquals(1, rs.getObject(8, Integer.class)); assertEquals(1, rs.getObject(8, Long.class)); assertEquals(1.f, rs.getObject(8, Float.class)); assertEquals(1, rs.getObject(8, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(8, BigDecimal.class)); assertArrayEquals(new byte[]{63, -16, 0, 0, 0, 0, 0, 0}, rs.getBytes(8)); assertEquals(rs.getObject(8, String.class), "1.0"); } cnt++; } assertEquals(1, cnt); } @Test public void testBigDecimal() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assertEquals(1, rs.getBigDecimal("bigVal").intValue()); assertTrue(rs.getBoolean(9)); assertEquals(1, rs.getByte(9)); assertEquals(1, rs.getShort(9)); assertEquals(1, rs.getInt(9)); assertEquals(1, rs.getLong(9)); assertEquals(1.0, rs.getDouble(9)); assertEquals(1.0f, rs.getFloat(9)); assertEquals(new BigDecimal("1.000"), rs.getBigDecimal(9)); assertEquals(rs.getString(9), "1.000"); assertTrue(rs.getObject(9, Boolean.class)); assertEquals((byte) 1, rs.getObject(9, Byte.class)); assertEquals((short) 1, rs.getObject(9, Short.class)); assertEquals(1, rs.getObject(9, Integer.class)); assertEquals(1, rs.getObject(9, Long.class)); assertEquals(1.f, rs.getObject(9, Float.class)); assertEquals(1, rs.getObject(9, Double.class)); assertEquals(new BigDecimal("1.000"), rs.getObject(9, BigDecimal.class)); assertEquals(rs.getObject(9, String.class), "1.000"); } cnt++; } assertEquals(1, cnt); } @Test public void testBigDecimalScale() throws Exception { assertEquals(convertStringToBigDecimalViaJdbc("0.1234", 2).toString(), "0.12"); assertEquals(convertStringToBigDecimalViaJdbc("1.0005", 3).toString(), "1.001"); assertEquals(convertStringToBigDecimalViaJdbc("1205.5", -3).toString(), "1E+3"); assertEquals(convertStringToBigDecimalViaJdbc("12505.5", -3).toString(), "1.3E+4"); } /** * Converts {@link String} to {@link BigDecimal}. * * @param strDec String representation of a decimal value. * @param scale Scale. * @return BigDecimal object. * @throws SQLException On error. */ private BigDecimal convertStringToBigDecimalViaJdbc(String strDec, int scale) throws SQLException { try (ResultSet rs = stmt.executeQuery("select '" + strDec + "'")) { assertTrue(rs.next()); return rs.getBigDecimal(1, scale); } } @Test public void testString() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); int cnt = 0; while (rs.next()) { if (cnt == 0) { assert "1".equals(rs.getString("strVal")); assertTrue(rs.getBoolean(10)); assertEquals(1, rs.getByte(10)); assertEquals(1, rs.getShort(10)); assertEquals(1, rs.getInt(10)); assertEquals(1, rs.getLong(10)); assertEquals(1.0, rs.getDouble(10)); assertEquals(1.0f, rs.getFloat(10)); assertEquals(new BigDecimal("1"), rs.getBigDecimal(10)); assertEquals(rs.getString(10), "1"); assertTrue(rs.getObject(10, Boolean.class)); assertEquals((byte) 1, rs.getObject(10, Byte.class)); assertEquals((short) 1, rs.getObject(10, Short.class)); assertEquals(1, rs.getObject(10, Integer.class)); assertEquals(1, rs.getObject(10, Long.class)); assertEquals(1.f, rs.getObject(10, Float.class)); assertEquals(1, rs.getObject(10, Double.class)); assertEquals(new BigDecimal(1), rs.getObject(10, BigDecimal.class)); assertArrayEquals(new byte[]{49}, rs.getBytes(10)); assertEquals(rs.getObject(10, String.class), "1"); } cnt++; } assertEquals(1, cnt); } @Test public void testDate() throws Exception { ResultSet rs = stmt.executeQuery(STATIC_SQL); int cnt = 0; Date exp = Date.valueOf(LocalDate.parse("1901-02-01")); while (rs.next()) { if (cnt == 0) { assertEquals(exp, rs.getDate("dateVal")); assertEquals(exp, rs.getDate(12)); assertEquals(new Time(exp.getTime()), rs.getTime(12)); assertEquals(new Timestamp(exp.getTime()), rs.getTimestamp(12)); assertEquals(exp, rs.getObject(12, Date.class)); assertEquals(new Time(exp.getTime()), rs.getObject(12, Time.class)); assertEquals(new Timestamp(exp.getTime()), rs.getObject(12, Timestamp.class)); } cnt++; } assertEquals(1, cnt); } /** * Test date-time. * * @throws Exception If failed. */ @SuppressWarnings("deprecation") @Test public void testTime() throws Exception { ResultSet rs = stmt.executeQuery(STATIC_SQL); int cnt = 0; while (rs.next()) { if (cnt == 0) { assert rs.getTime("timeVal").equals(new Time(1, 1, 1)); assertEquals(new Date(new Time(1, 1, 1).getTime()), rs.getDate(13)); assertEquals(new Time(1, 1, 1), rs.getTime(13)); assertEquals(new Timestamp(new Time(1, 1, 1).getTime()), rs.getTimestamp(13)); assertEquals(new Date(new Time(1, 1, 1).getTime()), rs.getObject(13, Date.class)); assertEquals(new Time(1, 1, 1), rs.getObject(13, Time.class)); assertEquals(new Timestamp(new Time(1, 1, 1).getTime()), rs.getObject(13, Timestamp.class)); } cnt++; } assertEquals(1, cnt); } @Test public void testTimestamp() throws Exception { ResultSet rs = stmt.executeQuery(STATIC_SQL); assertTrue(rs.next()); Timestamp localEpoch = Timestamp.valueOf("1970-01-01 00:00:00"); Instant localEpochInst = localEpoch.toInstant(); assertEquals(localEpoch, rs.getTimestamp("tsVal")); assertEquals(Date.from(localEpochInst), rs.getDate(14)); assertEquals(Time.from(localEpochInst), rs.getTime(14)); assertEquals(Timestamp.from(localEpochInst), rs.getTimestamp(14)); assertEquals(Date.from(localEpochInst), rs.getObject(14, Date.class)); assertEquals(Time.from(localEpochInst), rs.getObject(14, Time.class)); assertEquals(Timestamp.from(localEpochInst), rs.getObject(14, Timestamp.class)); assertFalse(rs.next()); } @Test public void testUuid() throws SQLException { ResultSet rs = stmt.executeQuery(STATIC_SQL); assertTrue(rs.next()); Object uuidVal = rs.getObject("uuidVal"); assertNotNull(uuidVal); assertEquals(UUID.fromString("fd10556e-fc27-4a99-b5e4-89b8344cb3ce"), uuidVal); assertFalse(rs.next()); } @Test public void testNavigation() throws Exception { ResultSet rs = stmt.executeQuery("SELECT * FROM test where id > 0"); assertTrue(rs.isBeforeFirst()); assertFalse(rs.isAfterLast()); assertFalse(rs.isFirst()); assertFalse(rs.isLast()); assertEquals(0, rs.getRow()); assertTrue(rs.next()); assertFalse(rs.isBeforeFirst()); assertFalse(rs.isAfterLast()); assertTrue(rs.isFirst()); assertFalse(rs.isLast()); assertEquals(1, rs.getRow()); assertTrue(rs.next()); assertFalse(rs.isBeforeFirst()); assertFalse(rs.isAfterLast()); assertFalse(rs.isFirst()); assertTrue(rs.isLast()); assertEquals(2, rs.getRow()); assertFalse(rs.next()); assertFalse(rs.isBeforeFirst()); assertTrue(rs.isAfterLast()); assertFalse(rs.isFirst()); assertFalse(rs.isLast()); assertEquals(0, rs.getRow()); rs = stmt.executeQuery("select id from test where id < 0"); assertFalse(rs.isBeforeFirst()); } @Test public void testFindColumn() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.findColumn("id")); JdbcTestUtils.assertThrowsSqlException("Column not found: wrong", () -> rs.findColumn("wrong")); } @Test public void testNotSupportedTypes() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); assertTrue(rs.next()); checkNotSupported(() -> rs.getArray(1)); checkNotSupported(() -> rs.getArray("id")); checkNotSupported(() -> rs.getAsciiStream(1)); checkNotSupported(() -> rs.getAsciiStream("id")); checkNotSupported(() -> rs.getBinaryStream(1)); checkNotSupported(() -> rs.getBinaryStream("id")); checkNotSupported(() -> rs.getBlob(1)); checkNotSupported(() -> rs.getBlob("id")); checkNotSupported(() -> rs.getClob(1)); checkNotSupported(() -> rs.getClob("id")); checkNotSupported(() -> rs.getCharacterStream(1)); checkNotSupported(() -> rs.getCharacterStream("id")); checkNotSupported(() -> rs.getNCharacterStream(1)); checkNotSupported(() -> rs.getNCharacterStream("id")); checkNotSupported(() -> rs.getNClob(1)); checkNotSupported(() -> rs.getNClob("id")); checkNotSupported(() -> rs.getRef(1)); checkNotSupported(() -> rs.getRef("id")); checkNotSupported(() -> rs.getRowId(1)); checkNotSupported(() -> rs.getRowId("id")); checkNotSupported(() -> rs.getSQLXML(1)); checkNotSupported(() -> rs.getSQLXML("id")); } @Test public void testUpdateNotSupported() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); assertTrue(rs.next()); checkNotSupported(() -> rs.updateBoolean(1, true)); checkNotSupported(() -> rs.updateBoolean("id", true)); checkNotSupported(() -> rs.updateByte(1, (byte) 0)); checkNotSupported(() -> rs.updateByte("id", (byte) 0)); checkNotSupported(() -> rs.updateShort(1, (short) 0)); checkNotSupported(() -> rs.updateShort("id", (short) 0)); checkNotSupported(() -> rs.updateInt(1, 0)); checkNotSupported(() -> rs.updateInt("id", 0)); checkNotSupported(() -> rs.updateLong(1, 0)); checkNotSupported(() -> rs.updateLong("id", 0)); checkNotSupported(() -> rs.updateFloat(1, (float) 0.0)); checkNotSupported(() -> rs.updateFloat("id", (float) 0.0)); checkNotSupported(() -> rs.updateDouble(1, 0.0)); checkNotSupported(() -> rs.updateDouble("id", 0.0)); checkNotSupported(() -> rs.updateString(1, "")); checkNotSupported(() -> rs.updateString("id", "")); checkNotSupported(() -> rs.updateTime(1, new Time(0))); checkNotSupported(() -> rs.updateTime("id", new Time(0))); checkNotSupported(() -> rs.updateDate(1, new Date(0))); checkNotSupported(() -> rs.updateDate("id", new Date(0))); checkNotSupported(() -> rs.updateTimestamp(1, new Timestamp(0))); checkNotSupported(() -> rs.updateTimestamp("id", new Timestamp(0))); checkNotSupported(() -> rs.updateBytes(1, new byte[]{})); checkNotSupported(() -> rs.updateBytes("id", new byte[]{})); checkNotSupported(() -> rs.updateArray(1, null)); checkNotSupported(() -> rs.updateArray("id", null)); checkNotSupported(() -> rs.updateBlob(1, (Blob) null)); checkNotSupported(() -> rs.updateBlob(1, (InputStream) null)); checkNotSupported(() -> rs.updateBlob(1, null, 0L)); checkNotSupported(() -> rs.updateBlob("id", (Blob) null)); checkNotSupported(() -> rs.updateBlob("id", (InputStream) null)); checkNotSupported(() -> rs.updateBlob("id", null, 0L)); checkNotSupported(() -> rs.updateClob(1, (Clob) null)); checkNotSupported(() -> rs.updateClob(1, (Reader) null)); checkNotSupported(() -> rs.updateClob(1, null, 0L)); checkNotSupported(() -> rs.updateClob("id", (Clob) null)); checkNotSupported(() -> rs.updateClob("id", (Reader) null)); checkNotSupported(() -> rs.updateClob("id", null, 0L)); checkNotSupported(() -> rs.updateNClob(1, (NClob) null)); checkNotSupported(() -> rs.updateNClob(1, (Reader) null)); checkNotSupported(() -> rs.updateNClob(1, null, 0L)); checkNotSupported(() -> rs.updateNClob("id", (NClob) null)); checkNotSupported(() -> rs.updateNClob("id", (Reader) null)); checkNotSupported(() -> rs.updateNClob("id", null, 0L)); checkNotSupported(() -> rs.updateAsciiStream(1, null)); checkNotSupported(() -> rs.updateAsciiStream(1, null, 0)); checkNotSupported(() -> rs.updateAsciiStream(1, null, 0L)); checkNotSupported(() -> rs.updateAsciiStream("id", null)); checkNotSupported(() -> rs.updateAsciiStream("id", null, 0)); checkNotSupported(() -> rs.updateAsciiStream("id", null, 0L)); checkNotSupported(() -> rs.updateCharacterStream(1, null)); checkNotSupported(() -> rs.updateCharacterStream(1, null, 0)); checkNotSupported(() -> rs.updateCharacterStream(1, null, 0L)); checkNotSupported(() -> rs.updateCharacterStream("id", null)); checkNotSupported(() -> rs.updateCharacterStream("id", null, 0)); checkNotSupported(() -> rs.updateCharacterStream("id", null, 0L)); checkNotSupported(() -> rs.updateNCharacterStream(1, null)); checkNotSupported(() -> rs.updateNCharacterStream(1, null, 0)); checkNotSupported(() -> rs.updateNCharacterStream(1, null, 0L)); checkNotSupported(() -> rs.updateNCharacterStream("id", null)); checkNotSupported(() -> rs.updateNCharacterStream("id", null, 0)); checkNotSupported(() -> rs.updateNCharacterStream("id", null, 0L)); checkNotSupported(() -> rs.updateRef(1, null)); checkNotSupported(() -> rs.updateRef("id", null)); checkNotSupported(() -> rs.updateRowId(1, null)); checkNotSupported(() -> rs.updateRowId("id", null)); checkNotSupported(() -> rs.updateNString(1, null)); checkNotSupported(() -> rs.updateNString("id", null)); checkNotSupported(() -> rs.updateSQLXML(1, null)); checkNotSupported(() -> rs.updateSQLXML("id", null)); checkNotSupported(() -> rs.updateObject(1, null)); checkNotSupported(() -> rs.updateObject(1, null, 0)); checkNotSupported(() -> rs.updateObject("id", null)); checkNotSupported(() -> rs.updateObject("id", null, 0)); checkNotSupported(() -> rs.updateBigDecimal(1, null)); checkNotSupported(() -> rs.updateBigDecimal("id", null)); checkNotSupported(() -> rs.updateNull(1)); checkNotSupported(() -> rs.updateNull("id")); checkNotSupported(rs::cancelRowUpdates); checkNotSupported(rs::updateRow); checkNotSupported(rs::deleteRow); checkNotSupported(rs::insertRow); checkNotSupported(rs::moveToInsertRow); } @Test public void testExceptionOnClosedResultSet() throws Exception { ResultSet rs = stmt.executeQuery(SQL_SINGLE_RES); rs.close(); // Must do nothing on closed result set rs.close(); checkResultSetClosed(() -> rs.getBoolean(1)); checkResultSetClosed(() -> rs.getBoolean("id")); checkResultSetClosed(() -> rs.getByte(1)); checkResultSetClosed(() -> rs.getByte("id")); checkResultSetClosed(() -> rs.getShort(1)); checkResultSetClosed(() -> rs.getShort("id")); checkResultSetClosed(() -> rs.getInt(1)); checkResultSetClosed(() -> rs.getInt("id")); checkResultSetClosed(() -> rs.getLong(1)); checkResultSetClosed(() -> rs.getLong("id")); checkResultSetClosed(() -> rs.getFloat(1)); checkResultSetClosed(() -> rs.getFloat("id")); checkResultSetClosed(() -> rs.getDouble(1)); checkResultSetClosed(() -> rs.getDouble("id")); checkResultSetClosed(() -> rs.getString(1)); checkResultSetClosed(() -> rs.getString("id")); checkResultSetClosed(() -> rs.getBytes(1)); checkResultSetClosed(() -> rs.getBytes("id")); checkResultSetClosed(() -> rs.getDate(1)); checkResultSetClosed(() -> rs.getDate(1, new GregorianCalendar())); checkResultSetClosed(() -> rs.getDate("id")); checkResultSetClosed(() -> rs.getDate("id", new GregorianCalendar())); checkResultSetClosed(() -> rs.getTime(1)); checkResultSetClosed(() -> rs.getTime(1, new GregorianCalendar())); checkResultSetClosed(() -> rs.getTime("id")); checkResultSetClosed(() -> rs.getTime("id", new GregorianCalendar())); checkResultSetClosed(() -> rs.getTimestamp(1)); checkResultSetClosed(() -> rs.getTimestamp(1, new GregorianCalendar())); checkResultSetClosed(() -> rs.getTimestamp("id")); checkResultSetClosed(() -> rs.getTimestamp("id", new GregorianCalendar())); checkResultSetClosed(() -> rs.getObject("objVal")); checkResultSetClosed(() -> rs.getObject("objVal", TestObjectField.class)); checkResultSetClosed(rs::wasNull); checkResultSetClosed(rs::getMetaData); checkResultSetClosed(rs::next); checkResultSetClosed(rs::last); checkResultSetClosed(rs::afterLast); checkResultSetClosed(rs::beforeFirst); checkResultSetClosed(rs::first); checkResultSetClosed(() -> rs.findColumn("id")); checkResultSetClosed(rs::getRow); } /** * Test object field. */ @SuppressWarnings("PackageVisibleField") private static class TestObjectField implements Serializable { final int ai; final String bi; /** * Constructor. * * @param ai A. * @param bi B. */ private TestObjectField(int ai, String bi) { this.ai = ai; this.bi = bi; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TestObjectField that = (TestObjectField) o; return ai == that.ai && !(bi != null ? !bi.equals(that.bi) : that.bi != null); } /** {@inheritDoc} */ @Override public int hashCode() { int res = ai; res = 31 * res + (bi != null ? bi.hashCode() : 0); return res; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(TestObjectField.class, this); } } }
googleapis/google-api-java-client-services
38,185
clients/google-api-services-discoveryengine/v1/2.0.0/com/google/api/services/discoveryengine/v1/model/GoogleCloudDiscoveryengineV1UserEvent.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.discoveryengine.v1.model; /** * UserEvent captures all metadata information Discovery Engine API needs to know about how end * users interact with your website. * * <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 Discovery Engine 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 GoogleCloudDiscoveryengineV1UserEvent extends com.google.api.client.json.GenericJson { /** * Extra user event features to include in the recommendation model. These attributes must NOT * contain data that needs to be parsed or processed further, e.g. JSON or other encodings. If you * provide custom attributes for ingested user events, also include them in the user events that * you associate with prediction requests. Custom attribute formatting must be consistent between * imported events and events provided with prediction requests. This lets the Discovery Engine * API use those custom attributes when training models and serving predictions, which helps * improve recommendation quality. This field needs to pass all below criteria, otherwise an * `INVALID_ARGUMENT` error is returned: * The key must be a UTF-8 encoded string with a length * limit of 5,000 characters. * For text attributes, at most 400 values are allowed. Empty values * are not allowed. Each value must be a UTF-8 encoded string with a length limit of 256 * characters. * For number attributes, at most 400 values are allowed. For product * recommendations, an example of extra user information is `traffic_channel`, which is how a user * arrives at the site. Users can arrive at the site by coming to the site directly, coming * through Google search, or in other ways. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, GoogleCloudDiscoveryengineV1CustomAttribute> attributes; static { // hack to force ProGuard to consider GoogleCloudDiscoveryengineV1CustomAttribute used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDiscoveryengineV1CustomAttribute.class); } /** * Token to attribute an API response to user action(s) to trigger the event. Highly recommended * for user events that are the result of RecommendationService.Recommend. This field enables * accurate attribution of recommendation model performance. The value must be one of: * * RecommendResponse.attribution_token for events that are the result of * RecommendationService.Recommend. * SearchResponse.attribution_token for events that are the * result of SearchService.Search. This token enables us to accurately attribute page view or * conversion completion back to the event and the particular predict response containing this * clicked/purchased product. If user clicks on product K in the recommendation results, pass * RecommendResponse.attribution_token as a URL parameter to product K's page. When recording * events on product K's page, log the RecommendResponse.attribution_token to this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String attributionToken; /** * CompletionService.CompleteQuery details related to the event. This field should be set for * `search` event when autocomplete function is enabled and the user clicks a suggestion for * search. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1CompletionInfo completionInfo; /** * Optional. Conversion type. Required if UserEvent.event_type is `conversion`. This is a * customer-defined conversion name in lowercase letters or numbers separated by "-", such as * "watch", "good-visit" etc. Do not set the field if UserEvent.event_type is not `conversion`. * This mixes the custom conversion event with predefined events like `search`, `view-item` etc. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String conversionType; /** * The DataStore resource full name, of the form `projects/{project}/locations/{location}/collecti * ons/{collection_id}/dataStores/{data_store_id}`. Optional. Only required for user events whose * data store can't by determined by UserEvent.engine or UserEvent.documents. If data store is set * in the parent of write/import/collect user event requests, this field can be omitted. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String dataStore; /** * Should set to true if the request is made directly from the end user, in which case the * UserEvent.user_info.user_agent can be populated from the HTTP request. This flag should be set * only if the API request is made directly from the end user such as a mobile app (and not if a * gateway or a server is processing and pushing the user events). This should not be set when * using the JavaScript tag in UserEventService.CollectUserEvent. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean directUserRequest; /** * List of Documents associated with this user event. This field is optional except for the * following event types: * `view-item` * `add-to-cart` * `purchase` * `media-play` * `media- * complete` In a `search` event, this field represents the documents returned to the end user on * the current page (the end user may have not finished browsing the whole page yet). When a new * page is returned to the end user, after pagination/filtering/ordering even for the same query, * a new `search` event with different UserEvent.documents is desired. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDiscoveryengineV1DocumentInfo> documents; static { // hack to force ProGuard to consider GoogleCloudDiscoveryengineV1DocumentInfo used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDiscoveryengineV1DocumentInfo.class); } /** * The Engine resource name, in the form of * `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`. * Optional. Only required for Engine produced user events. For example, user events from blended * search. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String engine; /** * Only required for UserEventService.ImportUserEvents method. Timestamp of when the user event * happened. * The value may be {@code null}. */ @com.google.api.client.util.Key private String eventTime; /** * Required. User event type. Allowed values are: Generic values: * `search`: Search for * Documents. * `view-item`: Detailed page view of a Document. * `view-item-list`: View of a panel * or ordered list of Documents. * `view-home-page`: View of the home page. * `view-category- * page`: View of a category page, e.g. Home > Men > Jeans Retail-related values: * `add-to-cart`: * Add an item(s) to cart, e.g. in Retail online shopping * `purchase`: Purchase an item(s) Media- * related values: * `media-play`: Start/resume watching a video, playing a song, etc. * `media- * complete`: Finished or stopped midway through a video, song, etc. Custom conversion value: * * `conversion`: Customer defined conversion event. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String eventType; /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the documents being filtered. One example is for `search` events, the associated * SearchRequest may contain a filter expression in SearchRequest.filter conforming to * https://google.aip.dev/160#filtering. Similarly, for `view-item-list` events that are generated * from a RecommendRequest, this field may be populated directly from RecommendRequest.filter * conforming to https://google.aip.dev/160#filtering. The value must be a UTF-8 encoded string * with a length limit of 1,000 characters. Otherwise, an `INVALID_ARGUMENT` error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String filter; /** * Media-specific info. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1MediaInfo mediaInfo; /** * Page metadata such as categories and other critical information for certain event types such as * `view-category-page`. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1PageInfo pageInfo; /** * Panel metadata associated with this user event. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1PanelInfo panel; /** * Optional. List of panels associated with this event. Used for page-level impression data. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDiscoveryengineV1PanelInfo> panels; static { // hack to force ProGuard to consider GoogleCloudDiscoveryengineV1PanelInfo used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDiscoveryengineV1PanelInfo.class); } /** * The promotion IDs if this is an event associated with promotions. Currently, this field is * restricted to at most one ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> promotionIds; /** * SearchService.Search details related to the event. This field should be set for `search` event. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1SearchInfo searchInfo; /** * A unique identifier for tracking a visitor session with a length limit of 128 bytes. A session * is an aggregation of an end user behavior in a time span. A general guideline to populate the * session_id: 1. If user has no activity for 30 min, a new session_id should be assigned. 2. The * session_id should be unique across users, suggest use uuid or add UserEvent.user_pseudo_id as * prefix. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String sessionId; /** * A list of identifiers for the independent experiment groups this user event belongs to. This is * used to distinguish between user events associated with different experiment setups. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> tagIds; /** * The transaction metadata (if any) associated with this user event. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1TransactionInfo transactionInfo; /** * Information about the end user. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDiscoveryengineV1UserInfo userInfo; /** * Required. A unique identifier for tracking visitors. For example, this could be implemented * with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. * This unique identifier should not change if the visitor log in/out of the website. Do not set * the field to the same fixed ID for different users. This mixes the event history of those users * together, which results in degraded model quality. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an `INVALID_ARGUMENT` error is returned. The * field should not contain PII or user-data. We recommend to use Google Analytics [Client * ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field- * reference#clientId) for this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String userPseudoId; /** * Extra user event features to include in the recommendation model. These attributes must NOT * contain data that needs to be parsed or processed further, e.g. JSON or other encodings. If you * provide custom attributes for ingested user events, also include them in the user events that * you associate with prediction requests. Custom attribute formatting must be consistent between * imported events and events provided with prediction requests. This lets the Discovery Engine * API use those custom attributes when training models and serving predictions, which helps * improve recommendation quality. This field needs to pass all below criteria, otherwise an * `INVALID_ARGUMENT` error is returned: * The key must be a UTF-8 encoded string with a length * limit of 5,000 characters. * For text attributes, at most 400 values are allowed. Empty values * are not allowed. Each value must be a UTF-8 encoded string with a length limit of 256 * characters. * For number attributes, at most 400 values are allowed. For product * recommendations, an example of extra user information is `traffic_channel`, which is how a user * arrives at the site. Users can arrive at the site by coming to the site directly, coming * through Google search, or in other ways. * @return value or {@code null} for none */ public java.util.Map<String, GoogleCloudDiscoveryengineV1CustomAttribute> getAttributes() { return attributes; } /** * Extra user event features to include in the recommendation model. These attributes must NOT * contain data that needs to be parsed or processed further, e.g. JSON or other encodings. If you * provide custom attributes for ingested user events, also include them in the user events that * you associate with prediction requests. Custom attribute formatting must be consistent between * imported events and events provided with prediction requests. This lets the Discovery Engine * API use those custom attributes when training models and serving predictions, which helps * improve recommendation quality. This field needs to pass all below criteria, otherwise an * `INVALID_ARGUMENT` error is returned: * The key must be a UTF-8 encoded string with a length * limit of 5,000 characters. * For text attributes, at most 400 values are allowed. Empty values * are not allowed. Each value must be a UTF-8 encoded string with a length limit of 256 * characters. * For number attributes, at most 400 values are allowed. For product * recommendations, an example of extra user information is `traffic_channel`, which is how a user * arrives at the site. Users can arrive at the site by coming to the site directly, coming * through Google search, or in other ways. * @param attributes attributes or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setAttributes(java.util.Map<String, GoogleCloudDiscoveryengineV1CustomAttribute> attributes) { this.attributes = attributes; return this; } /** * Token to attribute an API response to user action(s) to trigger the event. Highly recommended * for user events that are the result of RecommendationService.Recommend. This field enables * accurate attribution of recommendation model performance. The value must be one of: * * RecommendResponse.attribution_token for events that are the result of * RecommendationService.Recommend. * SearchResponse.attribution_token for events that are the * result of SearchService.Search. This token enables us to accurately attribute page view or * conversion completion back to the event and the particular predict response containing this * clicked/purchased product. If user clicks on product K in the recommendation results, pass * RecommendResponse.attribution_token as a URL parameter to product K's page. When recording * events on product K's page, log the RecommendResponse.attribution_token to this field. * @return value or {@code null} for none */ public java.lang.String getAttributionToken() { return attributionToken; } /** * Token to attribute an API response to user action(s) to trigger the event. Highly recommended * for user events that are the result of RecommendationService.Recommend. This field enables * accurate attribution of recommendation model performance. The value must be one of: * * RecommendResponse.attribution_token for events that are the result of * RecommendationService.Recommend. * SearchResponse.attribution_token for events that are the * result of SearchService.Search. This token enables us to accurately attribute page view or * conversion completion back to the event and the particular predict response containing this * clicked/purchased product. If user clicks on product K in the recommendation results, pass * RecommendResponse.attribution_token as a URL parameter to product K's page. When recording * events on product K's page, log the RecommendResponse.attribution_token to this field. * @param attributionToken attributionToken or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setAttributionToken(java.lang.String attributionToken) { this.attributionToken = attributionToken; return this; } /** * CompletionService.CompleteQuery details related to the event. This field should be set for * `search` event when autocomplete function is enabled and the user clicks a suggestion for * search. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1CompletionInfo getCompletionInfo() { return completionInfo; } /** * CompletionService.CompleteQuery details related to the event. This field should be set for * `search` event when autocomplete function is enabled and the user clicks a suggestion for * search. * @param completionInfo completionInfo or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setCompletionInfo(GoogleCloudDiscoveryengineV1CompletionInfo completionInfo) { this.completionInfo = completionInfo; return this; } /** * Optional. Conversion type. Required if UserEvent.event_type is `conversion`. This is a * customer-defined conversion name in lowercase letters or numbers separated by "-", such as * "watch", "good-visit" etc. Do not set the field if UserEvent.event_type is not `conversion`. * This mixes the custom conversion event with predefined events like `search`, `view-item` etc. * @return value or {@code null} for none */ public java.lang.String getConversionType() { return conversionType; } /** * Optional. Conversion type. Required if UserEvent.event_type is `conversion`. This is a * customer-defined conversion name in lowercase letters or numbers separated by "-", such as * "watch", "good-visit" etc. Do not set the field if UserEvent.event_type is not `conversion`. * This mixes the custom conversion event with predefined events like `search`, `view-item` etc. * @param conversionType conversionType or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setConversionType(java.lang.String conversionType) { this.conversionType = conversionType; return this; } /** * The DataStore resource full name, of the form `projects/{project}/locations/{location}/collecti * ons/{collection_id}/dataStores/{data_store_id}`. Optional. Only required for user events whose * data store can't by determined by UserEvent.engine or UserEvent.documents. If data store is set * in the parent of write/import/collect user event requests, this field can be omitted. * @return value or {@code null} for none */ public java.lang.String getDataStore() { return dataStore; } /** * The DataStore resource full name, of the form `projects/{project}/locations/{location}/collecti * ons/{collection_id}/dataStores/{data_store_id}`. Optional. Only required for user events whose * data store can't by determined by UserEvent.engine or UserEvent.documents. If data store is set * in the parent of write/import/collect user event requests, this field can be omitted. * @param dataStore dataStore or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setDataStore(java.lang.String dataStore) { this.dataStore = dataStore; return this; } /** * Should set to true if the request is made directly from the end user, in which case the * UserEvent.user_info.user_agent can be populated from the HTTP request. This flag should be set * only if the API request is made directly from the end user such as a mobile app (and not if a * gateway or a server is processing and pushing the user events). This should not be set when * using the JavaScript tag in UserEventService.CollectUserEvent. * @return value or {@code null} for none */ public java.lang.Boolean getDirectUserRequest() { return directUserRequest; } /** * Should set to true if the request is made directly from the end user, in which case the * UserEvent.user_info.user_agent can be populated from the HTTP request. This flag should be set * only if the API request is made directly from the end user such as a mobile app (and not if a * gateway or a server is processing and pushing the user events). This should not be set when * using the JavaScript tag in UserEventService.CollectUserEvent. * @param directUserRequest directUserRequest or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setDirectUserRequest(java.lang.Boolean directUserRequest) { this.directUserRequest = directUserRequest; return this; } /** * List of Documents associated with this user event. This field is optional except for the * following event types: * `view-item` * `add-to-cart` * `purchase` * `media-play` * `media- * complete` In a `search` event, this field represents the documents returned to the end user on * the current page (the end user may have not finished browsing the whole page yet). When a new * page is returned to the end user, after pagination/filtering/ordering even for the same query, * a new `search` event with different UserEvent.documents is desired. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDiscoveryengineV1DocumentInfo> getDocuments() { return documents; } /** * List of Documents associated with this user event. This field is optional except for the * following event types: * `view-item` * `add-to-cart` * `purchase` * `media-play` * `media- * complete` In a `search` event, this field represents the documents returned to the end user on * the current page (the end user may have not finished browsing the whole page yet). When a new * page is returned to the end user, after pagination/filtering/ordering even for the same query, * a new `search` event with different UserEvent.documents is desired. * @param documents documents or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setDocuments(java.util.List<GoogleCloudDiscoveryengineV1DocumentInfo> documents) { this.documents = documents; return this; } /** * The Engine resource name, in the form of * `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`. * Optional. Only required for Engine produced user events. For example, user events from blended * search. * @return value or {@code null} for none */ public java.lang.String getEngine() { return engine; } /** * The Engine resource name, in the form of * `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`. * Optional. Only required for Engine produced user events. For example, user events from blended * search. * @param engine engine or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setEngine(java.lang.String engine) { this.engine = engine; return this; } /** * Only required for UserEventService.ImportUserEvents method. Timestamp of when the user event * happened. * @return value or {@code null} for none */ public String getEventTime() { return eventTime; } /** * Only required for UserEventService.ImportUserEvents method. Timestamp of when the user event * happened. * @param eventTime eventTime or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setEventTime(String eventTime) { this.eventTime = eventTime; return this; } /** * Required. User event type. Allowed values are: Generic values: * `search`: Search for * Documents. * `view-item`: Detailed page view of a Document. * `view-item-list`: View of a panel * or ordered list of Documents. * `view-home-page`: View of the home page. * `view-category- * page`: View of a category page, e.g. Home > Men > Jeans Retail-related values: * `add-to-cart`: * Add an item(s) to cart, e.g. in Retail online shopping * `purchase`: Purchase an item(s) Media- * related values: * `media-play`: Start/resume watching a video, playing a song, etc. * `media- * complete`: Finished or stopped midway through a video, song, etc. Custom conversion value: * * `conversion`: Customer defined conversion event. * @return value or {@code null} for none */ public java.lang.String getEventType() { return eventType; } /** * Required. User event type. Allowed values are: Generic values: * `search`: Search for * Documents. * `view-item`: Detailed page view of a Document. * `view-item-list`: View of a panel * or ordered list of Documents. * `view-home-page`: View of the home page. * `view-category- * page`: View of a category page, e.g. Home > Men > Jeans Retail-related values: * `add-to-cart`: * Add an item(s) to cart, e.g. in Retail online shopping * `purchase`: Purchase an item(s) Media- * related values: * `media-play`: Start/resume watching a video, playing a song, etc. * `media- * complete`: Finished or stopped midway through a video, song, etc. Custom conversion value: * * `conversion`: Customer defined conversion event. * @param eventType eventType or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setEventType(java.lang.String eventType) { this.eventType = eventType; return this; } /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the documents being filtered. One example is for `search` events, the associated * SearchRequest may contain a filter expression in SearchRequest.filter conforming to * https://google.aip.dev/160#filtering. Similarly, for `view-item-list` events that are generated * from a RecommendRequest, this field may be populated directly from RecommendRequest.filter * conforming to https://google.aip.dev/160#filtering. The value must be a UTF-8 encoded string * with a length limit of 1,000 characters. Otherwise, an `INVALID_ARGUMENT` error is returned. * @return value or {@code null} for none */ public java.lang.String getFilter() { return filter; } /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the documents being filtered. One example is for `search` events, the associated * SearchRequest may contain a filter expression in SearchRequest.filter conforming to * https://google.aip.dev/160#filtering. Similarly, for `view-item-list` events that are generated * from a RecommendRequest, this field may be populated directly from RecommendRequest.filter * conforming to https://google.aip.dev/160#filtering. The value must be a UTF-8 encoded string * with a length limit of 1,000 characters. Otherwise, an `INVALID_ARGUMENT` error is returned. * @param filter filter or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setFilter(java.lang.String filter) { this.filter = filter; return this; } /** * Media-specific info. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1MediaInfo getMediaInfo() { return mediaInfo; } /** * Media-specific info. * @param mediaInfo mediaInfo or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setMediaInfo(GoogleCloudDiscoveryengineV1MediaInfo mediaInfo) { this.mediaInfo = mediaInfo; return this; } /** * Page metadata such as categories and other critical information for certain event types such as * `view-category-page`. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1PageInfo getPageInfo() { return pageInfo; } /** * Page metadata such as categories and other critical information for certain event types such as * `view-category-page`. * @param pageInfo pageInfo or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setPageInfo(GoogleCloudDiscoveryengineV1PageInfo pageInfo) { this.pageInfo = pageInfo; return this; } /** * Panel metadata associated with this user event. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1PanelInfo getPanel() { return panel; } /** * Panel metadata associated with this user event. * @param panel panel or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setPanel(GoogleCloudDiscoveryengineV1PanelInfo panel) { this.panel = panel; return this; } /** * Optional. List of panels associated with this event. Used for page-level impression data. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDiscoveryengineV1PanelInfo> getPanels() { return panels; } /** * Optional. List of panels associated with this event. Used for page-level impression data. * @param panels panels or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setPanels(java.util.List<GoogleCloudDiscoveryengineV1PanelInfo> panels) { this.panels = panels; return this; } /** * The promotion IDs if this is an event associated with promotions. Currently, this field is * restricted to at most one ID. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPromotionIds() { return promotionIds; } /** * The promotion IDs if this is an event associated with promotions. Currently, this field is * restricted to at most one ID. * @param promotionIds promotionIds or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setPromotionIds(java.util.List<java.lang.String> promotionIds) { this.promotionIds = promotionIds; return this; } /** * SearchService.Search details related to the event. This field should be set for `search` event. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1SearchInfo getSearchInfo() { return searchInfo; } /** * SearchService.Search details related to the event. This field should be set for `search` event. * @param searchInfo searchInfo or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setSearchInfo(GoogleCloudDiscoveryengineV1SearchInfo searchInfo) { this.searchInfo = searchInfo; return this; } /** * A unique identifier for tracking a visitor session with a length limit of 128 bytes. A session * is an aggregation of an end user behavior in a time span. A general guideline to populate the * session_id: 1. If user has no activity for 30 min, a new session_id should be assigned. 2. The * session_id should be unique across users, suggest use uuid or add UserEvent.user_pseudo_id as * prefix. * @return value or {@code null} for none */ public java.lang.String getSessionId() { return sessionId; } /** * A unique identifier for tracking a visitor session with a length limit of 128 bytes. A session * is an aggregation of an end user behavior in a time span. A general guideline to populate the * session_id: 1. If user has no activity for 30 min, a new session_id should be assigned. 2. The * session_id should be unique across users, suggest use uuid or add UserEvent.user_pseudo_id as * prefix. * @param sessionId sessionId or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setSessionId(java.lang.String sessionId) { this.sessionId = sessionId; return this; } /** * A list of identifiers for the independent experiment groups this user event belongs to. This is * used to distinguish between user events associated with different experiment setups. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTagIds() { return tagIds; } /** * A list of identifiers for the independent experiment groups this user event belongs to. This is * used to distinguish between user events associated with different experiment setups. * @param tagIds tagIds or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setTagIds(java.util.List<java.lang.String> tagIds) { this.tagIds = tagIds; return this; } /** * The transaction metadata (if any) associated with this user event. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1TransactionInfo getTransactionInfo() { return transactionInfo; } /** * The transaction metadata (if any) associated with this user event. * @param transactionInfo transactionInfo or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setTransactionInfo(GoogleCloudDiscoveryengineV1TransactionInfo transactionInfo) { this.transactionInfo = transactionInfo; return this; } /** * Information about the end user. * @return value or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserInfo getUserInfo() { return userInfo; } /** * Information about the end user. * @param userInfo userInfo or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setUserInfo(GoogleCloudDiscoveryengineV1UserInfo userInfo) { this.userInfo = userInfo; return this; } /** * Required. A unique identifier for tracking visitors. For example, this could be implemented * with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. * This unique identifier should not change if the visitor log in/out of the website. Do not set * the field to the same fixed ID for different users. This mixes the event history of those users * together, which results in degraded model quality. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an `INVALID_ARGUMENT` error is returned. The * field should not contain PII or user-data. We recommend to use Google Analytics [Client * ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field- * reference#clientId) for this field. * @return value or {@code null} for none */ public java.lang.String getUserPseudoId() { return userPseudoId; } /** * Required. A unique identifier for tracking visitors. For example, this could be implemented * with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. * This unique identifier should not change if the visitor log in/out of the website. Do not set * the field to the same fixed ID for different users. This mixes the event history of those users * together, which results in degraded model quality. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an `INVALID_ARGUMENT` error is returned. The * field should not contain PII or user-data. We recommend to use Google Analytics [Client * ID](https://developers.google.com/analytics/devguides/collection/analyticsjs/field- * reference#clientId) for this field. * @param userPseudoId userPseudoId or {@code null} for none */ public GoogleCloudDiscoveryengineV1UserEvent setUserPseudoId(java.lang.String userPseudoId) { this.userPseudoId = userPseudoId; return this; } @Override public GoogleCloudDiscoveryengineV1UserEvent set(String fieldName, Object value) { return (GoogleCloudDiscoveryengineV1UserEvent) super.set(fieldName, value); } @Override public GoogleCloudDiscoveryengineV1UserEvent clone() { return (GoogleCloudDiscoveryengineV1UserEvent) super.clone(); } }
googleapis/google-cloud-java
37,908
java-network-management/google-cloud-network-management/src/test/java/com/google/cloud/networkmanagement/v1/ReachabilityServiceClientTest.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.networkmanagement.v1; import static com.google.cloud.networkmanagement.v1.ReachabilityServiceClient.ListConnectivityTestsPagedResponse; import static com.google.cloud.networkmanagement.v1.ReachabilityServiceClient.ListLocationsPagedResponse; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.api.gax.grpc.testing.MockGrpcService; import com.google.api.gax.grpc.testing.MockServiceHelper; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.api.gax.rpc.StatusCode; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.collect.Lists; import com.google.iam.v1.AuditConfig; import com.google.iam.v1.Binding; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.GetPolicyOptions; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.protobuf.AbstractMessage; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import com.google.protobuf.Timestamp; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class ReachabilityServiceClientTest { private static MockIAMPolicy mockIAMPolicy; private static MockLocations mockLocations; private static MockReachabilityService mockReachabilityService; private static MockServiceHelper mockServiceHelper; private LocalChannelProvider channelProvider; private ReachabilityServiceClient client; @BeforeClass public static void startStaticServer() { mockReachabilityService = new MockReachabilityService(); mockLocations = new MockLocations(); mockIAMPolicy = new MockIAMPolicy(); mockServiceHelper = new MockServiceHelper( UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockReachabilityService, mockLocations, mockIAMPolicy)); mockServiceHelper.start(); } @AfterClass public static void stopServer() { mockServiceHelper.stop(); } @Before public void setUp() throws IOException { mockServiceHelper.reset(); channelProvider = mockServiceHelper.createChannelProvider(); ReachabilityServiceSettings settings = ReachabilityServiceSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = ReachabilityServiceClient.create(settings); } @After public void tearDown() throws Exception { client.close(); } @Test public void listConnectivityTestsTest() throws Exception { ConnectivityTest responsesElement = ConnectivityTest.newBuilder().build(); ListConnectivityTestsResponse expectedResponse = ListConnectivityTestsResponse.newBuilder() .setNextPageToken("") .addAllResources(Arrays.asList(responsesElement)) .build(); mockReachabilityService.addResponse(expectedResponse); ProjectName parent = ProjectName.of("[PROJECT]"); ListConnectivityTestsPagedResponse pagedListResponse = client.listConnectivityTests(parent); List<ConnectivityTest> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getResourcesList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListConnectivityTestsRequest actualRequest = ((ListConnectivityTestsRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listConnectivityTestsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { ProjectName parent = ProjectName.of("[PROJECT]"); client.listConnectivityTests(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listConnectivityTestsTest2() throws Exception { ConnectivityTest responsesElement = ConnectivityTest.newBuilder().build(); ListConnectivityTestsResponse expectedResponse = ListConnectivityTestsResponse.newBuilder() .setNextPageToken("") .addAllResources(Arrays.asList(responsesElement)) .build(); mockReachabilityService.addResponse(expectedResponse); String parent = "parent-995424086"; ListConnectivityTestsPagedResponse pagedListResponse = client.listConnectivityTests(parent); List<ConnectivityTest> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getResourcesList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListConnectivityTestsRequest actualRequest = ((ListConnectivityTestsRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listConnectivityTestsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { String parent = "parent-995424086"; client.listConnectivityTests(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getConnectivityTestTest() throws Exception { ConnectivityTest expectedResponse = ConnectivityTest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .setDescription("description-1724546052") .setSource(Endpoint.newBuilder().build()) .setDestination(Endpoint.newBuilder().build()) .setProtocol("protocol-989163880") .addAllRelatedProjects(new ArrayList<String>()) .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .setReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setProbingDetails(ProbingDetails.newBuilder().build()) .setRoundTrip(true) .setReturnReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setBypassFirewallChecks(true) .build(); mockReachabilityService.addResponse(expectedResponse); ConnectivityTestName name = ConnectivityTestName.of("[PROJECT]", "[TEST]"); ConnectivityTest actualResponse = client.getConnectivityTest(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetConnectivityTestRequest actualRequest = ((GetConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getConnectivityTestExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { ConnectivityTestName name = ConnectivityTestName.of("[PROJECT]", "[TEST]"); client.getConnectivityTest(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getConnectivityTestTest2() throws Exception { ConnectivityTest expectedResponse = ConnectivityTest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .setDescription("description-1724546052") .setSource(Endpoint.newBuilder().build()) .setDestination(Endpoint.newBuilder().build()) .setProtocol("protocol-989163880") .addAllRelatedProjects(new ArrayList<String>()) .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .setReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setProbingDetails(ProbingDetails.newBuilder().build()) .setRoundTrip(true) .setReturnReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setBypassFirewallChecks(true) .build(); mockReachabilityService.addResponse(expectedResponse); String name = "name3373707"; ConnectivityTest actualResponse = client.getConnectivityTest(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetConnectivityTestRequest actualRequest = ((GetConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getConnectivityTestExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { String name = "name3373707"; client.getConnectivityTest(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createConnectivityTestTest() throws Exception { ConnectivityTest expectedResponse = ConnectivityTest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .setDescription("description-1724546052") .setSource(Endpoint.newBuilder().build()) .setDestination(Endpoint.newBuilder().build()) .setProtocol("protocol-989163880") .addAllRelatedProjects(new ArrayList<String>()) .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .setReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setProbingDetails(ProbingDetails.newBuilder().build()) .setRoundTrip(true) .setReturnReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setBypassFirewallChecks(true) .build(); Operation resultOperation = Operation.newBuilder() .setName("createConnectivityTestTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockReachabilityService.addResponse(resultOperation); ProjectName parent = ProjectName.of("[PROJECT]"); String testId = "testId-877170355"; ConnectivityTest resource = ConnectivityTest.newBuilder().build(); ConnectivityTest actualResponse = client.createConnectivityTestAsync(parent, testId, resource).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateConnectivityTestRequest actualRequest = ((CreateConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(testId, actualRequest.getTestId()); Assert.assertEquals(resource, actualRequest.getResource()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createConnectivityTestExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { ProjectName parent = ProjectName.of("[PROJECT]"); String testId = "testId-877170355"; ConnectivityTest resource = ConnectivityTest.newBuilder().build(); client.createConnectivityTestAsync(parent, testId, resource).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 createConnectivityTestTest2() throws Exception { ConnectivityTest expectedResponse = ConnectivityTest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .setDescription("description-1724546052") .setSource(Endpoint.newBuilder().build()) .setDestination(Endpoint.newBuilder().build()) .setProtocol("protocol-989163880") .addAllRelatedProjects(new ArrayList<String>()) .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .setReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setProbingDetails(ProbingDetails.newBuilder().build()) .setRoundTrip(true) .setReturnReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setBypassFirewallChecks(true) .build(); Operation resultOperation = Operation.newBuilder() .setName("createConnectivityTestTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockReachabilityService.addResponse(resultOperation); String parent = "parent-995424086"; String testId = "testId-877170355"; ConnectivityTest resource = ConnectivityTest.newBuilder().build(); ConnectivityTest actualResponse = client.createConnectivityTestAsync(parent, testId, resource).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateConnectivityTestRequest actualRequest = ((CreateConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(testId, actualRequest.getTestId()); Assert.assertEquals(resource, actualRequest.getResource()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createConnectivityTestExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { String parent = "parent-995424086"; String testId = "testId-877170355"; ConnectivityTest resource = ConnectivityTest.newBuilder().build(); client.createConnectivityTestAsync(parent, testId, resource).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 updateConnectivityTestTest() throws Exception { ConnectivityTest expectedResponse = ConnectivityTest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .setDescription("description-1724546052") .setSource(Endpoint.newBuilder().build()) .setDestination(Endpoint.newBuilder().build()) .setProtocol("protocol-989163880") .addAllRelatedProjects(new ArrayList<String>()) .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .setReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setProbingDetails(ProbingDetails.newBuilder().build()) .setRoundTrip(true) .setReturnReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setBypassFirewallChecks(true) .build(); Operation resultOperation = Operation.newBuilder() .setName("updateConnectivityTestTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockReachabilityService.addResponse(resultOperation); FieldMask updateMask = FieldMask.newBuilder().build(); ConnectivityTest resource = ConnectivityTest.newBuilder().build(); ConnectivityTest actualResponse = client.updateConnectivityTestAsync(updateMask, resource).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateConnectivityTestRequest actualRequest = ((UpdateConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); Assert.assertEquals(resource, actualRequest.getResource()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateConnectivityTestExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { FieldMask updateMask = FieldMask.newBuilder().build(); ConnectivityTest resource = ConnectivityTest.newBuilder().build(); client.updateConnectivityTestAsync(updateMask, resource).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 rerunConnectivityTestTest() throws Exception { ConnectivityTest expectedResponse = ConnectivityTest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .setDescription("description-1724546052") .setSource(Endpoint.newBuilder().build()) .setDestination(Endpoint.newBuilder().build()) .setProtocol("protocol-989163880") .addAllRelatedProjects(new ArrayList<String>()) .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .setReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setProbingDetails(ProbingDetails.newBuilder().build()) .setRoundTrip(true) .setReturnReachabilityDetails(ReachabilityDetails.newBuilder().build()) .setBypassFirewallChecks(true) .build(); Operation resultOperation = Operation.newBuilder() .setName("rerunConnectivityTestTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockReachabilityService.addResponse(resultOperation); RerunConnectivityTestRequest request = RerunConnectivityTestRequest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .build(); ConnectivityTest actualResponse = client.rerunConnectivityTestAsync(request).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); RerunConnectivityTestRequest actualRequest = ((RerunConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void rerunConnectivityTestExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { RerunConnectivityTestRequest request = RerunConnectivityTestRequest.newBuilder() .setName(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .build(); client.rerunConnectivityTestAsync(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 deleteConnectivityTestTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("deleteConnectivityTestTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockReachabilityService.addResponse(resultOperation); ConnectivityTestName name = ConnectivityTestName.of("[PROJECT]", "[TEST]"); client.deleteConnectivityTestAsync(name).get(); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); DeleteConnectivityTestRequest actualRequest = ((DeleteConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void deleteConnectivityTestExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { ConnectivityTestName name = ConnectivityTestName.of("[PROJECT]", "[TEST]"); client.deleteConnectivityTestAsync(name).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void deleteConnectivityTestTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("deleteConnectivityTestTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockReachabilityService.addResponse(resultOperation); String name = "name3373707"; client.deleteConnectivityTestAsync(name).get(); List<AbstractMessage> actualRequests = mockReachabilityService.getRequests(); Assert.assertEquals(1, actualRequests.size()); DeleteConnectivityTestRequest actualRequest = ((DeleteConnectivityTestRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void deleteConnectivityTestExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockReachabilityService.addException(exception); try { String name = "name3373707"; client.deleteConnectivityTestAsync(name).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void 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(ConnectivityTestName.of("[PROJECT]", "[TEST]").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(ConnectivityTestName.of("[PROJECT]", "[TEST]").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(ConnectivityTestName.of("[PROJECT]", "[TEST]").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(ConnectivityTestName.of("[PROJECT]", "[TEST]").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(ConnectivityTestName.of("[PROJECT]", "[TEST]").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(ConnectivityTestName.of("[PROJECT]", "[TEST]").toString()) .addAllPermissions(new ArrayList<String>()) .build(); client.testIamPermissions(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
apache/systemds
35,785
src/main/java/org/apache/sysds/runtime/instructions/spark/utils/FrameRDDConverterUtils.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.sysds.runtime.instructions.spark.utils; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.PairFlatMapFunction; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.ml.linalg.Vector; import org.apache.spark.ml.linalg.VectorUDT; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import org.apache.sysds.common.Types.ValueType; import org.apache.sysds.runtime.DMLRuntimeException; import org.apache.sysds.runtime.controlprogram.caching.MatrixObject.UpdateType; import org.apache.sysds.runtime.frame.data.FrameBlock; import org.apache.sysds.runtime.frame.data.iterators.IteratorFactory; import org.apache.sysds.runtime.instructions.spark.data.FrameReblockBuffer; import org.apache.sysds.runtime.instructions.spark.data.SerLongWritable; import org.apache.sysds.runtime.instructions.spark.data.SerText; import org.apache.sysds.runtime.instructions.spark.functions.ConvertFrameBlockToIJVLines; import org.apache.sysds.runtime.instructions.spark.utils.RDDConverterUtils.DataFrameExtractIDFunction; import org.apache.sysds.runtime.io.FileFormatPropertiesCSV; import org.apache.sysds.runtime.io.IOUtilFunctions; import org.apache.sysds.runtime.matrix.data.MatrixBlock; import org.apache.sysds.runtime.matrix.data.MatrixIndexes; import org.apache.sysds.runtime.matrix.data.Pair; import org.apache.sysds.runtime.meta.DataCharacteristics; import org.apache.sysds.runtime.meta.MatrixCharacteristics; import org.apache.sysds.runtime.transform.TfUtils; import org.apache.sysds.runtime.util.DataConverter; import org.apache.sysds.runtime.util.FastStringTokenizer; import org.apache.sysds.runtime.util.UtilFunctions; import scala.Tuple2; public class FrameRDDConverterUtils { private static final Log LOG = LogFactory.getLog(FrameRDDConverterUtils.class.getName()); //===================================== // CSV <--> Binary block public static JavaPairRDD<Long, FrameBlock> csvToBinaryBlock(JavaSparkContext sc, JavaPairRDD<LongWritable, Text> input, DataCharacteristics mc, ValueType[] schema, boolean hasHeader, String delim, boolean fill, double fillValue, Set<String> naStrings) { //determine unknown dimensions and sparsity if required if( !mc.dimsKnown() ) { //nnz irrelevant here JavaRDD<String> tmp = input.values() .map(new TextToStringFunction()); String tmpStr = tmp.first(); boolean metaHeader = tmpStr.startsWith(TfUtils.TXMTD_MVPREFIX) || tmpStr.startsWith(TfUtils.TXMTD_NDPREFIX); tmpStr = (metaHeader) ? tmpStr.substring(tmpStr.indexOf(delim)+1) : tmpStr; long rlen = tmp.count() - (hasHeader ? 1 : 0) - (metaHeader ? 2 : 0); long clen = IOUtilFunctions.splitCSV(tmpStr, delim).length; mc.set(rlen, clen, mc.getBlocksize(), -1); } //prepare csv w/ row indexes (sorted by filenames) JavaPairRDD<Text,Long> prepinput = input.values() .zipWithIndex(); //zip row index //prepare default schema if needed if( schema == null || schema.length==1 ) schema = UtilFunctions.nCopies((int)mc.getCols(), ValueType.STRING); //convert csv rdd to binary block rdd (w/ partial blocks) JavaPairRDD<Long, FrameBlock> out = prepinput.mapPartitionsToPair( new CSVToBinaryBlockFunction(mc, schema, hasHeader, delim, naStrings)); return out; } public static JavaPairRDD<Long, FrameBlock> csvToBinaryBlock(JavaSparkContext sc, JavaRDD<String> input, DataCharacteristics mcOut, ValueType[] schema, boolean hasHeader, String delim, boolean fill, double fillValue, Set<String> naStrings) { //convert string rdd to serializable longwritable/text JavaPairRDD<LongWritable, Text> prepinput = input.mapToPair(new StringToSerTextFunction()); //convert to binary block return csvToBinaryBlock(sc, prepinput, mcOut, schema, hasHeader, delim, fill, fillValue, naStrings); } public static JavaRDD<String> binaryBlockToCsv(JavaPairRDD<Long,FrameBlock> in, DataCharacteristics mcIn, FileFormatPropertiesCSV props, boolean strict) { JavaPairRDD<Long,FrameBlock> input = in; //sort if required (on blocks/rows) if( strict && !isSorted(input) ) { input = input.sortByKey(true); } //convert binary block to csv (from blocks/rows) return input.flatMap( new BinaryBlockToCSVFunction(props)); } //===================================== // Text cell <--> Binary block public static JavaPairRDD<Long, FrameBlock> textCellToBinaryBlock(JavaSparkContext sc, JavaPairRDD<LongWritable, Text> in, DataCharacteristics mcOut, ValueType[] schema ) { //convert input rdd to serializable long/frame block JavaPairRDD<Long,Text> input = in.mapToPair(new LongWritableTextToLongTextFunction()); //do actual conversion return textCellToBinaryBlockLongIndex(sc, input, mcOut, schema); } public static JavaPairRDD<Long, FrameBlock> textCellToBinaryBlockLongIndex(JavaSparkContext sc, JavaPairRDD<Long, Text> input, DataCharacteristics mc, ValueType[] schema ) { //prepare default schema if needed if( schema == null || schema.length==1 ) { schema = UtilFunctions.nCopies((int)mc.getCols(), (schema!=null) ? schema[0] : ValueType.STRING); } //convert textcell rdd to binary block rdd (w/ partial blocks) JavaPairRDD<Long, FrameBlock> output = input.values() .mapPartitionsToPair(new TextToBinaryBlockFunction( mc, schema )); //aggregate partial matrix blocks return FrameRDDAggregateUtils.mergeByKey( output ); } public static JavaRDD<String> binaryBlockToTextCell(JavaPairRDD<Long, FrameBlock> input, DataCharacteristics mcIn) { //convert frame blocks to ijv string triples return input.flatMap(new ConvertFrameBlockToIJVLines()); } //===================================== // Matrix block <--> Binary block public static JavaPairRDD<LongWritable, FrameBlock> matrixBlockToBinaryBlock(JavaSparkContext sc, JavaPairRDD<MatrixIndexes, MatrixBlock> input, DataCharacteristics mcIn) { //convert and map to serializable LongWritable/frame block return matrixBlockToBinaryBlockLongIndex(sc,input, mcIn) .mapToPair(new LongFrameToLongWritableFrameFunction()); } public static JavaPairRDD<Long, FrameBlock> matrixBlockToBinaryBlockLongIndex(JavaSparkContext sc, JavaPairRDD<MatrixIndexes, MatrixBlock> input, DataCharacteristics dcIn) { JavaPairRDD<MatrixIndexes, MatrixBlock> in = input; DataCharacteristics mc = new MatrixCharacteristics(dcIn); //reblock matrix blocks if required (multiple column blocks) if(dcIn.getCols() > dcIn.getBlocksize()) { //split matrix blocks into extended matrix blocks in = in.flatMapToPair(new MatrixFrameReblockFunction(dcIn)); mc.setBlocksize(MatrixFrameReblockFunction.computeBlockSize(mc)); //shuffle matrix blocks (instead of frame blocks) in order to exploit //sparse formats (for sparse or wide matrices) during shuffle in = RDDAggregateUtils.mergeByKey(in, false); } //convert individual matrix blocks to frame blocks (w/o shuffle) return in.mapToPair(new MatrixToFrameBlockFunction(mc)); } public static JavaPairRDD<MatrixIndexes, MatrixBlock> binaryBlockToMatrixBlock(JavaPairRDD<Long,FrameBlock> input, DataCharacteristics mcIn, DataCharacteristics mcOut) { //convert binary block to matrix block JavaPairRDD<MatrixIndexes, MatrixBlock> out = input .flatMapToPair(new BinaryBlockToMatrixBlockFunction(mcIn, mcOut)); //aggregate partial matrix blocks return RDDAggregateUtils.mergeByKey(out, false); } //===================================== // DataFrame <--> Binary block public static JavaPairRDD<Long, FrameBlock> dataFrameToBinaryBlock(JavaSparkContext sc, Dataset<Row> df, DataCharacteristics mc, boolean containsID) { return dataFrameToBinaryBlock(sc, df, mc, containsID, new Pair<String[], ValueType[]>()); } public static JavaPairRDD<Long, FrameBlock> dataFrameToBinaryBlock(JavaSparkContext sc, Dataset<Row> df, DataCharacteristics mc, boolean containsID, Pair<String[],ValueType[]> out) { //determine unknown dimensions if required if( !mc.dimsKnown() ) { //nnz are irrelevant here int colVect = getColVectFromDFSchema(df.schema(), containsID); int off = (containsID ? 1 : 0); long rlen = df.count(); long clen = df.columns().length - off + ((colVect >= 0) ? ((Vector)df.first().get(off+colVect)).size() - 1 : 0); mc.set(rlen, clen, mc.getBlocksize(), -1); } //append or reuse row index column JavaPairRDD<Row, Long> prepinput = containsID ? df.javaRDD().mapToPair(new DataFrameExtractIDFunction( df.schema().fieldIndex(RDDConverterUtils.DF_ID_COLUMN))) : df.javaRDD().zipWithIndex(); //zip row index //convert data frame to frame schema (prepare once) String[] colnames = new String[(int)mc.getCols()]; ValueType[] fschema = new ValueType[(int)mc.getCols()]; int colVect = convertDFSchemaToFrameSchema(df.schema(), colnames, fschema, containsID); out.set(colnames, fschema); //make schema available //convert rdd to binary block rdd return prepinput.mapPartitionsToPair( new DataFrameToBinaryBlockFunction(mc, colnames, fschema, containsID, colVect)); } public static Dataset<Row> binaryBlockToDataFrame(SparkSession sparkSession, JavaPairRDD<Long,FrameBlock> in, DataCharacteristics mc, ValueType[] schema) { if( !mc.colsKnown() ) throw new RuntimeException("Number of columns needed to convert binary block to data frame."); //convert binary block to rows rdd JavaRDD<Row> rowRDD = in.flatMap( new BinaryBlockToDataFrameFunction()); //create data frame schema if( schema == null ) schema = UtilFunctions.nCopies((int)mc.getCols(), ValueType.STRING); StructType dfSchema = convertFrameSchemaToDFSchema(schema, true); //rdd to data frame conversion return sparkSession.createDataFrame(rowRDD, dfSchema); } @Deprecated public static Dataset<Row> binaryBlockToDataFrame(SQLContext sqlContext, JavaPairRDD<Long,FrameBlock> in, DataCharacteristics mc, ValueType[] schema) { return binaryBlockToDataFrame(sqlContext.sparkSession(), in, mc, schema); } /** * This function will convert Frame schema into DataFrame schema * * @param fschema frame schema * @param containsID true if contains ID column * @return Spark StructType of StructFields representing schema */ public static StructType convertFrameSchemaToDFSchema(ValueType[] fschema, boolean containsID) { // generate the schema based on the string of schema List<StructField> fields = new ArrayList<>(); // add id column type if( containsID ) fields.add(DataTypes.createStructField(RDDConverterUtils.DF_ID_COLUMN, DataTypes.DoubleType, true)); // add remaining types int col = 1; for (ValueType schema : fschema) { DataType dt = null; switch(schema) { case STRING: dt = DataTypes.StringType; break; case FP64: dt = DataTypes.DoubleType; break; case INT64: dt = DataTypes.LongType; break; case BOOLEAN: dt = DataTypes.BooleanType; break; default: dt = DataTypes.StringType; LOG.warn("Using default type String for " + schema.toString()); } fields.add(DataTypes.createStructField("C"+col++, dt, true)); } return DataTypes.createStructType(fields); } /** * NOTE: regarding the support of vector columns, we make the following * schema restriction: single vector column, which allows inference of * the vector length without data access and covers the common case. * * @param dfschema schema as StructType * @param colnames column names * @param fschema array of SystemDS ValueTypes * @param containsID if true, contains ID column * @return 0-based column index of vector column, -1 if no vector. */ public static int convertDFSchemaToFrameSchema(StructType dfschema, String[] colnames, ValueType[] fschema, boolean containsID) { //basic meta data int off = containsID ? 1 : 0; boolean containsVect = false; int lenVect = fschema.length - (dfschema.fields().length - off) + 1; int colVect = -1; //process individual columns for( int i=off, pos=0; i<dfschema.fields().length; i++ ) { StructField structType = dfschema.apply(i); colnames[pos] = structType.name(); if(structType.dataType() == DataTypes.DoubleType || structType.dataType() == DataTypes.FloatType) fschema[pos++] = ValueType.FP64; else if(structType.dataType() == DataTypes.LongType || structType.dataType() == DataTypes.IntegerType) fschema[pos++] = ValueType.INT64; else if(structType.dataType() == DataTypes.BooleanType) fschema[pos++] = ValueType.BOOLEAN; else if(structType.dataType() instanceof VectorUDT) { if( containsVect ) throw new RuntimeException("Found invalid second vector column."); String name = colnames[pos]; colVect = pos; for( int j=0; j<lenVect; j++ ) { colnames[pos] = name+"v"+j; fschema[pos++] = ValueType.FP64; } containsVect = true; } else fschema[pos++] = ValueType.STRING; } return colVect; } /** * Obtain column vector from DataFrame schema * * @param dfschema schema as StructType * @param containsID if true, contains ID column * @return 0-based column index of vector column, -1 if no vector. */ private static int getColVectFromDFSchema(StructType dfschema, boolean containsID) { int off = containsID ? 1 : 0; for( int i=off; i<dfschema.fields().length; i++ ) { StructField structType = dfschema.apply(i); if(structType.dataType() instanceof VectorUDT) return i-off; } return -1; } /* * It will return JavaRDD<Row> based on csv data input file. */ public static JavaRDD<Row> csvToRowRDD(JavaSparkContext sc, String fnameIn, String delim, ValueType[] schema) { // Load a text file and convert each line to a java rdd. JavaRDD<String> dataRdd = sc.textFile(fnameIn); return dataRdd.map(new RowGenerator(schema, delim)); } /* * It will return JavaRDD<Row> based on csv data. */ public static JavaRDD<Row> csvToRowRDD(JavaSparkContext sc, JavaRDD<String> dataRdd, String delim, ValueType[] schema) { // Convert each line to a java rdd. return dataRdd.map(new RowGenerator(schema, delim)); } /* * Row Generator class based on individual line in CSV file. */ private static class RowGenerator implements Function<String,Row> { private static final long serialVersionUID = -6736256507697511070L; private ValueType[] _schema = null; private String _delim = null; public RowGenerator(ValueType[] schema, String delim) { _schema = schema; _delim = delim; } @Override public Row call(String record) throws Exception { String[] fields = IOUtilFunctions.splitCSV(record, _delim); Object[] objects = new Object[fields.length]; for (int i=0; i<fields.length; i++) { objects[i] = UtilFunctions.stringToObject(_schema[i], fields[i]); } return RowFactory.create(objects); } } /** * Check if the rdd is already sorted in order to avoid unnecessary * sampling, shuffle, and sort per partition. * * @param in JavaPairRDD of FrameBlocks * @return true if RDD is sorted */ private static boolean isSorted(JavaPairRDD<Long, FrameBlock> in) { //check sorted partitions (returns max key if true; -1 otherwise) List<Long> keys = in.keys().mapPartitions( new SortingAnalysisFunction()).collect(); long max = 0; for( Long val : keys ) { if( val < max ) return false; max = val; } return true; } private static class SortingAnalysisFunction implements FlatMapFunction<Iterator<Long>,Long> { private static final long serialVersionUID = -5789003262381127469L; @Override public Iterator<Long> call(Iterator<Long> arg0) throws Exception { long max = 0; while( max >= 0 && arg0.hasNext() ) { long val = arg0.next(); max = (val < max) ? -1 : val; } ArrayList<Long> ret = new ArrayList<>(); ret.add(max); return ret.iterator(); } } ///////////////////////////////// // CSV-SPECIFIC FUNCTIONS private static class StringToSerTextFunction implements PairFunction<String, LongWritable, Text> { private static final long serialVersionUID = 8683232211035837695L; @Override public Tuple2<LongWritable, Text> call(String arg0) throws Exception { return new Tuple2<>(new SerLongWritable(1L), new SerText(arg0)); } } public static class LongWritableToSerFunction implements PairFunction<Tuple2<LongWritable,FrameBlock>,LongWritable,FrameBlock> { private static final long serialVersionUID = 2286037080400222528L; @Override public Tuple2<LongWritable, FrameBlock> call(Tuple2<LongWritable, FrameBlock> arg0) throws Exception { return new Tuple2<>(new SerLongWritable(arg0._1.get()), arg0._2); } } public static class LongWritableTextToLongTextFunction implements PairFunction<Tuple2<LongWritable,Text>,Long,Text> { private static final long serialVersionUID = -5408386071466175348L; @Override public Tuple2<Long, Text> call(Tuple2<LongWritable, Text> arg0) throws Exception { return new Tuple2<>(Long.valueOf(arg0._1.get()), arg0._2); } } public static class LongFrameToLongWritableFrameFunction implements PairFunction<Tuple2<Long,FrameBlock>,LongWritable,FrameBlock> { private static final long serialVersionUID = -1467314923206783333L; @Override public Tuple2<LongWritable, FrameBlock> call(Tuple2<Long, FrameBlock> arg0) throws Exception { return new Tuple2<>(new LongWritable(arg0._1), arg0._2); } } public static class LongWritableFrameToLongFrameFunction implements PairFunction<Tuple2<LongWritable,FrameBlock>,Long,FrameBlock> { private static final long serialVersionUID = -1232439643533739078L; @Override public Tuple2<Long, FrameBlock> call(Tuple2<LongWritable, FrameBlock> arg0) throws Exception { return new Tuple2<>(arg0._1.get(), arg0._2); } } private static class TextToStringFunction implements Function<Text,String> { private static final long serialVersionUID = -2744814934501782747L; @Override public String call(Text v1) throws Exception { return v1.toString(); } } /** * This functions allows to map rdd partitions of csv rows into a set of partial binary blocks. * * NOTE: For this csv to binary block function, we need to hold all output blocks per partition * in-memory. Hence, we keep state of all column blocks and aggregate row segments into these blocks. * In terms of memory consumption this is better than creating partial blocks of row segments. * */ private static class CSVToBinaryBlockFunction implements PairFlatMapFunction<Iterator<Tuple2<Text,Long>>,Long,FrameBlock> { private static final long serialVersionUID = -1976803898174960086L; private long _clen = -1; private boolean _hasHeader = false; private String _delim = null; private int _maxRowsPerBlock = -1; private ValueType[] _schema = null; private String[] _colnames = null; private List<String> _mvMeta = null; //missing value meta data private List<String> _ndMeta = null; //num distinct meta data private Set<String> _naStrings; public CSVToBinaryBlockFunction(DataCharacteristics mc, ValueType[] schema, boolean hasHeader, String delim, Set<String> naStrings) { _clen = mc.getCols(); _schema = schema; _hasHeader = hasHeader; _delim = delim; _maxRowsPerBlock = Math.max((int) (FrameBlock.BUFFER_SIZE/_clen), 1); _naStrings = naStrings; } @Override public Iterator<Tuple2<Long, FrameBlock>> call(Iterator<Tuple2<Text,Long>> arg0) throws Exception { ArrayList<Tuple2<Long,FrameBlock>> ret = new ArrayList<>(); long ix = -1; FrameBlock fb = null; String[] tmprow = new String[(int)_clen]; while( arg0.hasNext() ) { Tuple2<Text,Long> tmp = arg0.next(); String row = tmp._1().toString().trim(); long rowix = tmp._2(); if(_hasHeader && rowix == 0) { //Skip header _colnames = row.split(_delim); continue; } if( row.startsWith(TfUtils.TXMTD_MVPREFIX) ) { _mvMeta = Arrays.asList(Arrays.copyOfRange(IOUtilFunctions.splitCSV(row, _delim), 1, (int)_clen+1)); continue; } else if( row.startsWith(TfUtils.TXMTD_NDPREFIX) ) { _ndMeta = Arrays.asList(Arrays.copyOfRange(IOUtilFunctions.splitCSV(row, _delim), 1, (int)_clen+1)); continue; } //adjust row index for header and meta data rowix += (_hasHeader ? 0 : 1) - ((_mvMeta == null) ? 0 : 2); if( fb == null || fb.getNumRows() == _maxRowsPerBlock) { if( fb != null ) flushBlocksToList(ix, fb, ret); ix = rowix; fb = createFrameBlock(); } //split and process row data fb.appendRow(IOUtilFunctions.splitCSV(row, _delim, tmprow, _naStrings)); } //flush last blocks flushBlocksToList(ix, fb, ret); return ret.iterator(); } // Creates new state of empty column blocks for current global row index. private FrameBlock createFrameBlock() { //frame block with given schema FrameBlock fb = new FrameBlock(_schema); //preallocate physical columns (to avoid re-allocations) fb.ensureAllocatedColumns(_maxRowsPerBlock); fb.reset(0, false); //reset data but keep schema //handle meta data if( _colnames != null ) fb.setColumnNames(_colnames); if( _mvMeta != null ) for( int j=0; j<_clen; j++ ) fb.getColumnMetadata(j).setMvValue(_mvMeta.get(j)); if( _ndMeta != null ) for( int j=0; j<_clen; j++ ) fb.getColumnMetadata(j).setNumDistinct(Long.parseLong(_ndMeta.get(j))); return fb; } private static void flushBlocksToList( Long ix, FrameBlock fb, ArrayList<Tuple2<Long,FrameBlock>> ret ) { if( fb != null && fb.getNumRows()>=0 ) ret.add(new Tuple2<>(ix, fb)); } } private static class BinaryBlockToCSVFunction implements FlatMapFunction<Tuple2<Long,FrameBlock>,String> { private static final long serialVersionUID = 8020608184930291069L; private FileFormatPropertiesCSV _props = null; public BinaryBlockToCSVFunction(FileFormatPropertiesCSV props) { _props = props; } @Override public Iterator<String> call(Tuple2<Long, FrameBlock> arg0) throws Exception { Long ix = arg0._1(); FrameBlock blk = arg0._2(); ArrayList<String> ret = new ArrayList<>(); StringBuilder sb = new StringBuilder(); //handle header information and frame meta data if( ix==1 ) { if( _props.hasHeader() ) { for(int j = 1; j <= blk.getNumColumns(); j++) { sb.append(blk.getColumnNames()[j] + ((j<blk.getNumColumns()-1)?_props.getDelim():"")); } ret.add(sb.toString()); sb.setLength(0); //reset } if( !blk.isColumnMetadataDefault() ) { sb.append(TfUtils.TXMTD_MVPREFIX + _props.getDelim()); for( int j=0; j<blk.getNumColumns(); j++ ) sb.append(blk.getColumnMetadata(j).getMvValue() + ((j<blk.getNumColumns()-1)?_props.getDelim():"")); ret.add(sb.toString()); sb.setLength(0); //reset sb.append(TfUtils.TXMTD_NDPREFIX + _props.getDelim()); for( int j=0; j<blk.getNumColumns(); j++ ) sb.append(blk.getColumnMetadata(j).getNumDistinct() + ((j<blk.getNumColumns()-1)?_props.getDelim():"")); ret.add(sb.toString()); sb.setLength(0); //reset } } //handle Frame block data Iterator<String[]> iter = IteratorFactory.getStringRowIterator(blk); while( iter.hasNext() ) { String[] row = iter.next(); for(int j=0; j<row.length; j++) { if(j != 0) sb.append(_props.getDelim()); if(row[j] != null) sb.append(row[j]); } ret.add(sb.toString()); sb.setLength(0); //reset } return ret.iterator(); } } ///////////////////////////////// // DataFrame-SPECIFIC FUNCTIONS private static class DataFrameToBinaryBlockFunction implements PairFlatMapFunction<Iterator<Tuple2<Row,Long>>,Long,FrameBlock> { private static final long serialVersionUID = 2269315691094111843L; private long _clen = -1; private String[] _colnames = null; private ValueType[] _schema = null; private boolean _containsID = false; private int _colVect = -1; private int _maxRowsPerBlock = -1; public DataFrameToBinaryBlockFunction(DataCharacteristics mc, String[] colnames, ValueType[] schema, boolean containsID, int colVect) { _clen = mc.getCols(); _colnames = colnames; _schema = schema; _containsID = containsID; _colVect = colVect; _maxRowsPerBlock = Math.max((int) (FrameBlock.BUFFER_SIZE/_clen), 1); } @Override public Iterator<Tuple2<Long, FrameBlock>> call(Iterator<Tuple2<Row, Long>> arg0) throws Exception { ArrayList<Tuple2<Long,FrameBlock>> ret = new ArrayList<>(); long ix = -1; FrameBlock fb = null; Object[] tmprow = new Object[(int)_clen]; while( arg0.hasNext() ) { Tuple2<Row,Long> tmp = arg0.next(); Row row = tmp._1(); long rowix = tmp._2()+1; if( fb == null || fb.getNumRows() == _maxRowsPerBlock) { if( fb != null ) flushBlocksToList(ix, fb, ret); ix = rowix; fb = new FrameBlock(_schema, _colnames); } //process row data int off = _containsID ? 1 : 0; for(int i=off, pos=0; i<row.size(); i++) { if( i-off == _colVect ) { Vector vect = (Vector) row.get(i); for( int j=0; j<vect.size(); j++ ) tmprow[pos++] = vect.apply(j); } else { tmprow[pos] = UtilFunctions.objectToObject( _schema[pos], row.get(i)); pos++; } } fb.appendRow(tmprow); } //flush last blocks flushBlocksToList(ix, fb, ret); return ret.iterator(); } private static void flushBlocksToList( Long ix, FrameBlock fb, ArrayList<Tuple2<Long,FrameBlock>> ret ) { if( fb != null && fb.getNumRows()>=0 ) ret.add(new Tuple2<>(ix, fb)); } } private static class BinaryBlockToDataFrameFunction implements FlatMapFunction<Tuple2<Long,FrameBlock>,Row> { private static final long serialVersionUID = 8093340778966667460L; @Override public Iterator<Row> call(Tuple2<Long, FrameBlock> arg0) throws Exception { long rowIndex = arg0._1(); FrameBlock blk = arg0._2(); ArrayList<Row> ret = new ArrayList<>(); //handle Frame block data int rows = blk.getNumRows(); int cols = blk.getNumColumns(); for( int i=0; i<rows; i++ ) { Object[] row = new Object[cols+1]; row[0] = (double)rowIndex++; for( int j=0; j<cols; j++ ) row[j+1] = blk.get(i, j); ret.add(RowFactory.create(row)); } return ret.iterator(); } } ///////////////////////////////// // TEXTCELL-SPECIFIC FUNCTIONS private static abstract class CellToBinaryBlockFunction implements Serializable { private static final long serialVersionUID = -729614449626680946L; protected int _bufflen = -1; protected long _rlen = -1; protected long _clen = -1; protected CellToBinaryBlockFunction(DataCharacteristics mc) { _rlen = mc.getRows(); _clen = mc.getCols(); //determine upper bounded buffer len _bufflen = (int) Math.min(_rlen*_clen, FrameBlock.BUFFER_SIZE); } protected void flushBufferToList( FrameReblockBuffer rbuff, ArrayList<Tuple2<Long,FrameBlock>> ret ) throws DMLRuntimeException { //temporary list of indexed matrix values to prevent library dependencies ArrayList<Pair<Long, FrameBlock>> rettmp = new ArrayList<>(); rbuff.flushBufferToBinaryBlocks(rettmp); ret.addAll(SparkUtils.fromIndexedFrameBlock(rettmp)); } } private static class TextToBinaryBlockFunction extends CellToBinaryBlockFunction implements PairFlatMapFunction<Iterator<Text>,Long,FrameBlock> { private static final long serialVersionUID = -2042208027876880588L; ValueType[] _schema = null; protected TextToBinaryBlockFunction(DataCharacteristics mc, ValueType[] schema ) { super(mc); _schema = schema; } @Override public Iterator<Tuple2<Long, FrameBlock>> call(Iterator<Text> arg0) throws Exception { ArrayList<Tuple2<Long,FrameBlock>> ret = new ArrayList<>(); FrameReblockBuffer rbuff = new FrameReblockBuffer(_bufflen, _rlen, _clen, _schema ); FastStringTokenizer st = new FastStringTokenizer(' '); while( arg0.hasNext() ) { //get input string (ignore matrix market comments) String strVal = arg0.next().toString(); if( strVal.startsWith("%") ) continue; //parse input ijv triple st.reset( strVal ); long row = st.nextLong(); long col = st.nextLong(); String val = st.nextToken(); //flush buffer if necessary if( rbuff.getSize() >= rbuff.getCapacity() ) flushBufferToList(rbuff, ret); //add value to reblock buffer rbuff.appendCell(row, col, val); } //final flush buffer flushBufferToList(rbuff, ret); return ret.iterator(); } } // MATRIX Block <---> Binary Block specific functions private static class MatrixFrameReblockFunction implements PairFlatMapFunction<Tuple2<MatrixIndexes,MatrixBlock>,MatrixIndexes,MatrixBlock> { private static final long serialVersionUID = 6205071301074768437L; private int _blen = -1; private long _clen = -1; private int _maxRowsPerBlock = -1; private boolean _sparse = false; public MatrixFrameReblockFunction(DataCharacteristics dc) { _blen = dc.getBlocksize(); _blen = dc.getBlocksize(); _clen = dc.getCols(); _maxRowsPerBlock = computeBlockSize(dc); _sparse = dc.dimsKnown() && MatrixBlock.evalSparseFormatInMemory( dc.getRows(), dc.getCols(), dc.getNonZeros()/(_clen/_blen)); } @Override public Iterator<Tuple2<MatrixIndexes, MatrixBlock>> call(Tuple2<MatrixIndexes,MatrixBlock> arg0) throws Exception { ArrayList<Tuple2<MatrixIndexes,MatrixBlock>> ret = new ArrayList<>(); MatrixIndexes ix = arg0._1(); MatrixBlock mb = arg0._2(); MatrixBlock mbreuse = new MatrixBlock(); boolean sparse = _sparse || mb.isInSparseFormat(); //frame index (row id, 1-based) long rowix = (ix.getRowIndex()-1)*_blen+1; //global index within frame block (0-based) long cl = (int)((ix.getColumnIndex()-1)*_blen); long cu = Math.min(cl+mb.getNumColumns()-1, _clen); //prepare output frame blocks for( int i=0; i<mb.getNumRows(); i+=_maxRowsPerBlock ) { int ru = Math.min(i+_maxRowsPerBlock, mb.getNumRows())-1; long rix = UtilFunctions.computeBlockIndex(rowix+i, _maxRowsPerBlock); MatrixIndexes ixout = new MatrixIndexes(rix, 1); MatrixBlock out = new MatrixBlock(ru-i+1, (int)_clen, sparse); out.copy(0, out.getNumRows()-1, (int)cl, (int)cu, mb.slice(i, ru, 0, mb.getNumColumns()-1, mbreuse), true); out.examSparsity(); ret.add(new Tuple2<>(ixout,out)); } return ret.iterator(); } /** * Computes an output row block size that ensures matrix block alignment * and contains at most FrameBlock.BUFFER_SIZE cells per block. * * @param dc matrix characteristics * @return block size */ public static int computeBlockSize(DataCharacteristics dc) { int blen = dc.getBlocksize(); int basic = Math.max((int)(FrameBlock.BUFFER_SIZE/dc.getCols()), 1); int div = (int)Math.ceil((double)blen/basic); while( blen % div != 0 ) div++; return blen / div; } } private static class MatrixToFrameBlockFunction implements PairFunction<Tuple2<MatrixIndexes,MatrixBlock>,Long,FrameBlock> { private static final long serialVersionUID = 3716019666116660815L; private int _blen = -1; public MatrixToFrameBlockFunction(DataCharacteristics mc) { _blen = mc.getBlocksize(); } @Override public Tuple2<Long, FrameBlock> call(Tuple2<MatrixIndexes,MatrixBlock> arg0) throws Exception { FrameBlock fb = DataConverter.convertToFrameBlock(arg0._2()); return new Tuple2<>( (arg0._1().getRowIndex()-1)*_blen+1, fb); } } private static class BinaryBlockToMatrixBlockFunction implements PairFlatMapFunction<Tuple2<Long,FrameBlock>,MatrixIndexes, MatrixBlock> { private static final long serialVersionUID = -2654986510471835933L; private DataCharacteristics _mcIn; private DataCharacteristics _mcOut; public BinaryBlockToMatrixBlockFunction(DataCharacteristics mcIn, DataCharacteristics mcOut) { _mcIn = mcIn; //Frame Characteristics _mcOut = mcOut; //Matrix Characteristics } @Override public Iterator<Tuple2<MatrixIndexes, MatrixBlock>> call(Tuple2<Long, FrameBlock> arg0) throws Exception { long rowIndex = arg0._1(); FrameBlock blk = arg0._2(); ArrayList<Tuple2<MatrixIndexes, MatrixBlock>> ret = new ArrayList<>(); long rlen = _mcIn.getRows(); long clen = _mcIn.getCols(); int blen = _mcOut.getBlocksize(); //slice aligned matrix blocks out of given frame block long rstartix = UtilFunctions.computeBlockIndex(rowIndex, blen); long rendix = UtilFunctions.computeBlockIndex(rowIndex+blk.getNumRows()-1, blen); long cendix = UtilFunctions.computeBlockIndex(blk.getNumColumns(), blen); for( long rix=rstartix; rix<=rendix; rix++ ) { //for all row blocks long rpos = UtilFunctions.computeCellIndex(rix, blen, 0); int lrlen = UtilFunctions.computeBlockSize(rlen, rix, blen); int fix = (int)((rpos-rowIndex>=0) ? rpos-rowIndex : 0); int fix2 = (int)Math.min(rpos+lrlen-rowIndex-1,blk.getNumRows()-1); int mix = UtilFunctions.computeCellInBlock(rowIndex+fix, blen); int mix2 = mix + (fix2-fix); for( long cix=1; cix<=cendix; cix++ ) { //for all column blocks long cpos = UtilFunctions.computeCellIndex(cix, blen, 0); int lclen = UtilFunctions.computeBlockSize(clen, cix, blen); MatrixBlock matrix = new MatrixBlock(lrlen, lclen, false); FrameBlock frame = blk.slice(fix, fix2, (int)cpos-1, (int)cpos+lclen-2, new FrameBlock()); MatrixBlock mframe = DataConverter.convertToMatrixBlock(frame); ret.add(new Tuple2<>(new MatrixIndexes(rix, cix), matrix.leftIndexingOperations(mframe, mix, mix2, 0, lclen-1, new MatrixBlock(), UpdateType.INPLACE_PINNED))); } } return ret.iterator(); } } }
googleapis/google-cloud-java
37,850
java-contact-center-insights/proto-google-cloud-contact-center-insights-v1/src/main/java/com/google/cloud/contactcenterinsights/v1/ConversationDataSource.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/resources.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.contactcenterinsights.v1; /** * * * <pre> * The conversation source, which is a combination of transcript and audio. * </pre> * * Protobuf type {@code google.cloud.contactcenterinsights.v1.ConversationDataSource} */ public final class ConversationDataSource extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.ConversationDataSource) ConversationDataSourceOrBuilder { private static final long serialVersionUID = 0L; // Use ConversationDataSource.newBuilder() to construct. private ConversationDataSource(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ConversationDataSource() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ConversationDataSource(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.contactcenterinsights.v1.ResourcesProto .internal_static_google_cloud_contactcenterinsights_v1_ConversationDataSource_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.contactcenterinsights.v1.ResourcesProto .internal_static_google_cloud_contactcenterinsights_v1_ConversationDataSource_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.contactcenterinsights.v1.ConversationDataSource.class, com.google.cloud.contactcenterinsights.v1.ConversationDataSource.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), DIALOGFLOW_SOURCE(3), 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 3: return DIALOGFLOW_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> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> * * @return Whether the gcsSource field is set. */ @java.lang.Override public boolean hasGcsSource() { return sourceCase_ == 1; } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> * * @return The gcsSource. */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.GcsSource getGcsSource() { if (sourceCase_ == 1) { return (com.google.cloud.contactcenterinsights.v1.GcsSource) source_; } return com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance(); } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.GcsSourceOrBuilder getGcsSourceOrBuilder() { if (sourceCase_ == 1) { return (com.google.cloud.contactcenterinsights.v1.GcsSource) source_; } return com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance(); } public static final int DIALOGFLOW_SOURCE_FIELD_NUMBER = 3; /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> * * @return Whether the dialogflowSource field is set. */ @java.lang.Override public boolean hasDialogflowSource() { return sourceCase_ == 3; } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> * * @return The dialogflowSource. */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.DialogflowSource getDialogflowSource() { if (sourceCase_ == 3) { return (com.google.cloud.contactcenterinsights.v1.DialogflowSource) source_; } return com.google.cloud.contactcenterinsights.v1.DialogflowSource.getDefaultInstance(); } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.DialogflowSourceOrBuilder getDialogflowSourceOrBuilder() { if (sourceCase_ == 3) { return (com.google.cloud.contactcenterinsights.v1.DialogflowSource) source_; } return com.google.cloud.contactcenterinsights.v1.DialogflowSource.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.contactcenterinsights.v1.GcsSource) source_); } if (sourceCase_ == 3) { output.writeMessage(3, (com.google.cloud.contactcenterinsights.v1.DialogflowSource) 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.contactcenterinsights.v1.GcsSource) source_); } if (sourceCase_ == 3) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 3, (com.google.cloud.contactcenterinsights.v1.DialogflowSource) 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.contactcenterinsights.v1.ConversationDataSource)) { return super.equals(obj); } com.google.cloud.contactcenterinsights.v1.ConversationDataSource other = (com.google.cloud.contactcenterinsights.v1.ConversationDataSource) obj; if (!getSourceCase().equals(other.getSourceCase())) return false; switch (sourceCase_) { case 1: if (!getGcsSource().equals(other.getGcsSource())) return false; break; case 3: if (!getDialogflowSource().equals(other.getDialogflowSource())) 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 3: hash = (37 * hash) + DIALOGFLOW_SOURCE_FIELD_NUMBER; hash = (53 * hash) + getDialogflowSource().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource 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.ConversationDataSource parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource 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.ConversationDataSource parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource 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.ConversationDataSource parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource 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.ConversationDataSource parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource 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.ConversationDataSource 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.ConversationDataSource 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.ConversationDataSource 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 conversation source, which is a combination of transcript and audio. * </pre> * * Protobuf type {@code google.cloud.contactcenterinsights.v1.ConversationDataSource} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.ConversationDataSource) com.google.cloud.contactcenterinsights.v1.ConversationDataSourceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.contactcenterinsights.v1.ResourcesProto .internal_static_google_cloud_contactcenterinsights_v1_ConversationDataSource_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.contactcenterinsights.v1.ResourcesProto .internal_static_google_cloud_contactcenterinsights_v1_ConversationDataSource_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.contactcenterinsights.v1.ConversationDataSource.class, com.google.cloud.contactcenterinsights.v1.ConversationDataSource.Builder.class); } // Construct using com.google.cloud.contactcenterinsights.v1.ConversationDataSource.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(); } if (dialogflowSourceBuilder_ != null) { dialogflowSourceBuilder_.clear(); } sourceCase_ = 0; source_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.contactcenterinsights.v1.ResourcesProto .internal_static_google_cloud_contactcenterinsights_v1_ConversationDataSource_descriptor; } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.ConversationDataSource getDefaultInstanceForType() { return com.google.cloud.contactcenterinsights.v1.ConversationDataSource.getDefaultInstance(); } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.ConversationDataSource build() { com.google.cloud.contactcenterinsights.v1.ConversationDataSource result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.ConversationDataSource buildPartial() { com.google.cloud.contactcenterinsights.v1.ConversationDataSource result = new com.google.cloud.contactcenterinsights.v1.ConversationDataSource(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0( com.google.cloud.contactcenterinsights.v1.ConversationDataSource result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs( com.google.cloud.contactcenterinsights.v1.ConversationDataSource result) { result.sourceCase_ = sourceCase_; result.source_ = this.source_; if (sourceCase_ == 1 && gcsSourceBuilder_ != null) { result.source_ = gcsSourceBuilder_.build(); } if (sourceCase_ == 3 && dialogflowSourceBuilder_ != null) { result.source_ = dialogflowSourceBuilder_.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.contactcenterinsights.v1.ConversationDataSource) { return mergeFrom((com.google.cloud.contactcenterinsights.v1.ConversationDataSource) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.contactcenterinsights.v1.ConversationDataSource other) { if (other == com.google.cloud.contactcenterinsights.v1.ConversationDataSource.getDefaultInstance()) return this; switch (other.getSourceCase()) { case GCS_SOURCE: { mergeGcsSource(other.getGcsSource()); break; } case DIALOGFLOW_SOURCE: { mergeDialogflowSource(other.getDialogflowSource()); 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 case 26: { input.readMessage( getDialogflowSourceFieldBuilder().getBuilder(), extensionRegistry); sourceCase_ = 3; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int 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.contactcenterinsights.v1.GcsSource, com.google.cloud.contactcenterinsights.v1.GcsSource.Builder, com.google.cloud.contactcenterinsights.v1.GcsSourceOrBuilder> gcsSourceBuilder_; /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> * * @return Whether the gcsSource field is set. */ @java.lang.Override public boolean hasGcsSource() { return sourceCase_ == 1; } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> * * @return The gcsSource. */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.GcsSource getGcsSource() { if (gcsSourceBuilder_ == null) { if (sourceCase_ == 1) { return (com.google.cloud.contactcenterinsights.v1.GcsSource) source_; } return com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance(); } else { if (sourceCase_ == 1) { return gcsSourceBuilder_.getMessage(); } return com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance(); } } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ public Builder setGcsSource(com.google.cloud.contactcenterinsights.v1.GcsSource value) { if (gcsSourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } source_ = value; onChanged(); } else { gcsSourceBuilder_.setMessage(value); } sourceCase_ = 1; return this; } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ public Builder setGcsSource( com.google.cloud.contactcenterinsights.v1.GcsSource.Builder builderForValue) { if (gcsSourceBuilder_ == null) { source_ = builderForValue.build(); onChanged(); } else { gcsSourceBuilder_.setMessage(builderForValue.build()); } sourceCase_ = 1; return this; } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ public Builder mergeGcsSource(com.google.cloud.contactcenterinsights.v1.GcsSource value) { if (gcsSourceBuilder_ == null) { if (sourceCase_ == 1 && source_ != com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance()) { source_ = com.google.cloud.contactcenterinsights.v1.GcsSource.newBuilder( (com.google.cloud.contactcenterinsights.v1.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> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.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> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ public com.google.cloud.contactcenterinsights.v1.GcsSource.Builder getGcsSourceBuilder() { return getGcsSourceFieldBuilder().getBuilder(); } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.GcsSourceOrBuilder getGcsSourceOrBuilder() { if ((sourceCase_ == 1) && (gcsSourceBuilder_ != null)) { return gcsSourceBuilder_.getMessageOrBuilder(); } else { if (sourceCase_ == 1) { return (com.google.cloud.contactcenterinsights.v1.GcsSource) source_; } return com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance(); } } /** * * * <pre> * A Cloud Storage location specification for the audio and transcript. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.GcsSource gcs_source = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.GcsSource, com.google.cloud.contactcenterinsights.v1.GcsSource.Builder, com.google.cloud.contactcenterinsights.v1.GcsSourceOrBuilder> getGcsSourceFieldBuilder() { if (gcsSourceBuilder_ == null) { if (!(sourceCase_ == 1)) { source_ = com.google.cloud.contactcenterinsights.v1.GcsSource.getDefaultInstance(); } gcsSourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.GcsSource, com.google.cloud.contactcenterinsights.v1.GcsSource.Builder, com.google.cloud.contactcenterinsights.v1.GcsSourceOrBuilder>( (com.google.cloud.contactcenterinsights.v1.GcsSource) source_, getParentForChildren(), isClean()); source_ = null; } sourceCase_ = 1; onChanged(); return gcsSourceBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.DialogflowSource, com.google.cloud.contactcenterinsights.v1.DialogflowSource.Builder, com.google.cloud.contactcenterinsights.v1.DialogflowSourceOrBuilder> dialogflowSourceBuilder_; /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> * * @return Whether the dialogflowSource field is set. */ @java.lang.Override public boolean hasDialogflowSource() { return sourceCase_ == 3; } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> * * @return The dialogflowSource. */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.DialogflowSource getDialogflowSource() { if (dialogflowSourceBuilder_ == null) { if (sourceCase_ == 3) { return (com.google.cloud.contactcenterinsights.v1.DialogflowSource) source_; } return com.google.cloud.contactcenterinsights.v1.DialogflowSource.getDefaultInstance(); } else { if (sourceCase_ == 3) { return dialogflowSourceBuilder_.getMessage(); } return com.google.cloud.contactcenterinsights.v1.DialogflowSource.getDefaultInstance(); } } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ public Builder setDialogflowSource( com.google.cloud.contactcenterinsights.v1.DialogflowSource value) { if (dialogflowSourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } source_ = value; onChanged(); } else { dialogflowSourceBuilder_.setMessage(value); } sourceCase_ = 3; return this; } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ public Builder setDialogflowSource( com.google.cloud.contactcenterinsights.v1.DialogflowSource.Builder builderForValue) { if (dialogflowSourceBuilder_ == null) { source_ = builderForValue.build(); onChanged(); } else { dialogflowSourceBuilder_.setMessage(builderForValue.build()); } sourceCase_ = 3; return this; } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ public Builder mergeDialogflowSource( com.google.cloud.contactcenterinsights.v1.DialogflowSource value) { if (dialogflowSourceBuilder_ == null) { if (sourceCase_ == 3 && source_ != com.google.cloud.contactcenterinsights.v1.DialogflowSource .getDefaultInstance()) { source_ = com.google.cloud.contactcenterinsights.v1.DialogflowSource.newBuilder( (com.google.cloud.contactcenterinsights.v1.DialogflowSource) source_) .mergeFrom(value) .buildPartial(); } else { source_ = value; } onChanged(); } else { if (sourceCase_ == 3) { dialogflowSourceBuilder_.mergeFrom(value); } else { dialogflowSourceBuilder_.setMessage(value); } } sourceCase_ = 3; return this; } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ public Builder clearDialogflowSource() { if (dialogflowSourceBuilder_ == null) { if (sourceCase_ == 3) { sourceCase_ = 0; source_ = null; onChanged(); } } else { if (sourceCase_ == 3) { sourceCase_ = 0; source_ = null; } dialogflowSourceBuilder_.clear(); } return this; } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ public com.google.cloud.contactcenterinsights.v1.DialogflowSource.Builder getDialogflowSourceBuilder() { return getDialogflowSourceFieldBuilder().getBuilder(); } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.DialogflowSourceOrBuilder getDialogflowSourceOrBuilder() { if ((sourceCase_ == 3) && (dialogflowSourceBuilder_ != null)) { return dialogflowSourceBuilder_.getMessageOrBuilder(); } else { if (sourceCase_ == 3) { return (com.google.cloud.contactcenterinsights.v1.DialogflowSource) source_; } return com.google.cloud.contactcenterinsights.v1.DialogflowSource.getDefaultInstance(); } } /** * * * <pre> * The source when the conversation comes from Dialogflow. * </pre> * * <code>.google.cloud.contactcenterinsights.v1.DialogflowSource dialogflow_source = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.DialogflowSource, com.google.cloud.contactcenterinsights.v1.DialogflowSource.Builder, com.google.cloud.contactcenterinsights.v1.DialogflowSourceOrBuilder> getDialogflowSourceFieldBuilder() { if (dialogflowSourceBuilder_ == null) { if (!(sourceCase_ == 3)) { source_ = com.google.cloud.contactcenterinsights.v1.DialogflowSource.getDefaultInstance(); } dialogflowSourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.DialogflowSource, com.google.cloud.contactcenterinsights.v1.DialogflowSource.Builder, com.google.cloud.contactcenterinsights.v1.DialogflowSourceOrBuilder>( (com.google.cloud.contactcenterinsights.v1.DialogflowSource) source_, getParentForChildren(), isClean()); source_ = null; } sourceCase_ = 3; onChanged(); return dialogflowSourceBuilder_; } @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.ConversationDataSource) } // @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.ConversationDataSource) private static final com.google.cloud.contactcenterinsights.v1.ConversationDataSource DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.ConversationDataSource(); } public static com.google.cloud.contactcenterinsights.v1.ConversationDataSource getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ConversationDataSource> PARSER = new com.google.protobuf.AbstractParser<ConversationDataSource>() { @java.lang.Override public ConversationDataSource 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<ConversationDataSource> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ConversationDataSource> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.ConversationDataSource getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/cxf
38,057
rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/AbstractJAXBProvider.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.jaxrs.provider; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.validation.Schema; import org.w3c.dom.Element; import org.xml.sax.helpers.DefaultHandler; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.StreamingOutput; import jakarta.ws.rs.ext.ContextResolver; import jakarta.ws.rs.ext.MessageBodyReader; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBElement; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.PropertyException; import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.ValidationEventHandler; import jakarta.xml.bind.annotation.XmlAnyElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.cxf.annotations.SchemaValidation; import org.apache.cxf.common.jaxb.JAXBUtils; import org.apache.cxf.common.util.PackageUtils; import org.apache.cxf.jaxrs.ext.MessageContext; import org.apache.cxf.jaxrs.model.ClassResourceInfo; import org.apache.cxf.jaxrs.utils.ExceptionUtils; import org.apache.cxf.jaxrs.utils.InjectionUtils; import org.apache.cxf.jaxrs.utils.JAXRSUtils; import org.apache.cxf.jaxrs.utils.ResourceUtils; import org.apache.cxf.jaxrs.utils.schemas.SchemaHandler; import org.apache.cxf.message.Message; import org.apache.cxf.phase.PhaseInterceptorChain; import org.apache.cxf.staxutils.DepthExceededStaxException; import org.apache.cxf.staxutils.DepthRestrictingStreamReader; import org.apache.cxf.staxutils.DepthXMLStreamReader; import org.apache.cxf.staxutils.DocumentDepthProperties; import org.apache.cxf.staxutils.StaxUtils; import org.apache.cxf.staxutils.transform.TransformUtils; public abstract class AbstractJAXBProvider<T> extends AbstractConfigurableProvider implements MessageBodyReader<T>, MessageBodyWriter<T> { protected static final String NS_MAPPER_PROPERTY_RI = "com.sun.xml.bind.namespacePrefixMapper"; protected static final String NS_MAPPER_PROPERTY_RI_INT = "com.sun.xml.internal.bind.namespacePrefixMapper"; private static final String JAXB_DEFAULT_NAMESPACE = "##default"; private static final String JAXB_DEFAULT_NAME = "##default"; private static final Set<Class<?>> UNSUPPORTED_CLASSES = new HashSet<Class<?>>(Arrays.asList(InputStream.class, OutputStream.class, StreamingOutput.class)); protected Set<Class<?>> collectionContextClasses = ConcurrentHashMap.newKeySet(); protected Map<String, String> jaxbElementClassMap = Collections.emptyMap(); protected Map<String, Boolean> objectFactoryOrIndexMap = new ConcurrentHashMap<>(); protected boolean unmarshalAsJaxbElement; protected boolean marshalAsJaxbElement; protected boolean xmlTypeAsJaxbElementOnly; protected Map<String, String> outElementsMap; protected Map<String, String> outAppendMap; protected List<String> outDropElements; protected List<String> inDropElements; protected Map<String, String> inElementsMap; protected Map<String, String> inAppendMap; protected Map<String, JAXBContext> packageContexts = new ConcurrentHashMap<>(); protected Map<Class<?>, JAXBContext> classContexts = new ConcurrentHashMap<>(); private boolean attributesToElements; private MessageContext mc; private Schema schema; private String catalogLocation; private Map<String, SchemaHandler> schemaHandlers; private String collectionWrapperName; private Map<String, String> collectionWrapperMap; private List<String> jaxbElementClassNames; private boolean xmlRootAsJaxbElement; private Map<String, Object> cProperties; private Map<String, Object> uProperties; private boolean skipJaxbChecks; private boolean singleJaxbContext; private boolean useSingleContextForPackages; private Class<?>[] extraClass; private boolean validateInputIfPossible = true; private boolean validateOutputIfPossible; private boolean validateBeforeWrite; private ValidationEventHandler eventHandler; private Unmarshaller.Listener unmarshallerListener; private Marshaller.Listener marshallerListener; private DocumentDepthProperties depthProperties; private String namespaceMapperPropertyName; private static JAXBContext newJAXBContextInstance(Class<?>[] classes, Map<String, Object> cProperties) throws JAXBException { try { return AccessController.doPrivileged((PrivilegedExceptionAction<JAXBContext>)() -> { return JAXBContext.newInstance(classes, cProperties); }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof JAXBException) { throw (JAXBException) t; } throw new RuntimeException(t); } } public void setXmlRootAsJaxbElement(boolean xmlRootAsJaxbElement) { this.xmlRootAsJaxbElement = xmlRootAsJaxbElement; } protected void setNamespaceMapper(Marshaller ms, Map<String, String> map) throws Exception { Object nsMapper = JAXBUtils.setNamespaceMapper(getBus(), map, ms); if (nsMapper != null && namespaceMapperPropertyName != null) { setMarshallerProp(ms, nsMapper, namespaceMapperPropertyName, null); } } protected static void setMarshallerProp(Marshaller ms, Object value, String name1, String name2) throws Exception { try { ms.setProperty(name1, value); } catch (PropertyException ex) { if (name2 != null) { ms.setProperty(name2, value); } else { throw ex; } } } public void setValidationHandler(ValidationEventHandler handler) { eventHandler = handler; } public void setSingleJaxbContext(boolean useSingleContext) { singleJaxbContext = useSingleContext; } public void setUseSingleContextForPackages(boolean use) { useSingleContextForPackages = use; } public void setExtraClass(Class<?>[] userExtraClass) { extraClass = userExtraClass; } @Override public void init(List<ClassResourceInfo> cris) { if (singleJaxbContext) { JAXBContext context = null; Set<Class<?>> allTypes = null; if (cris != null) { allTypes = new HashSet<>(ResourceUtils.getAllRequestResponseTypes(cris, true) .getAllTypes().keySet()); context = org.apache.cxf.jaxrs.utils.JAXBUtils.createJaxbContext(allTypes, extraClass, cProperties); } else if (extraClass != null) { allTypes = new HashSet<>(Arrays.asList(extraClass)); context = org.apache.cxf.jaxrs.utils.JAXBUtils.createJaxbContext(allTypes, null, cProperties); } if (context != null) { for (Class<?> cls : allTypes) { if (useSingleContextForPackages) { packageContexts.put(PackageUtils.getPackageName(cls), context); } else { classContexts.put(cls, context); } } } } if (cris != null) { List<String> schemaLocs = new LinkedList<>(); SchemaValidation sv = null; for (ClassResourceInfo cri : cris) { sv = cri.getServiceClass().getAnnotation(SchemaValidation.class); if (sv != null && sv.schemas() != null && sv.type() != SchemaValidation.SchemaValidationType.NONE) { for (String s : sv.schemas()) { String theSchema = s; if (!theSchema.startsWith("classpath:")) { theSchema = "classpath:" + theSchema; } schemaLocs.add(theSchema); } } } if (!schemaLocs.isEmpty()) { this.setSchemaLocations(schemaLocs); if (cris.isEmpty() && schema != null && sv != null) { SchemaValidation.SchemaValidationType type = sv.type(); if (type == SchemaValidation.SchemaValidationType.OUT) { validateInputIfPossible = false; validateOutputIfPossible = true; } else if (type == SchemaValidation.SchemaValidationType.BOTH) { validateOutputIfPossible = true; } } } } } public void setContextProperties(Map<String, Object> contextProperties) { cProperties = contextProperties; } public void setUnmarshallerProperties(Map<String, Object> unmarshalProperties) { uProperties = unmarshalProperties; } public void setUnmarshallAsJaxbElement(boolean value) { unmarshalAsJaxbElement = value; } public void setMarshallAsJaxbElement(boolean value) { marshalAsJaxbElement = value; } public void setXmlTypeAsJaxbElementOnly(boolean value) { this.xmlTypeAsJaxbElementOnly = value; } public void setJaxbElementClassNames(List<String> names) { jaxbElementClassNames = names; } public void setJaxbElementClassMap(Map<String, String> map) { jaxbElementClassMap = map; } protected <X> X getStreamHandlerFromCurrentMessage(Class<X> staxCls) { Message m = PhaseInterceptorChain.getCurrentMessage(); if (m != null) { return staxCls.cast(m.getContent(staxCls)); } return null; } protected boolean isXmlRoot(Class<?> cls) { return cls.getAnnotation(XmlRootElement.class) != null; } protected boolean isXmlType(Class<?> cls) { return cls.getAnnotation(XmlType.class) != null; } @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object convertToJaxbElementIfNeeded(Object obj, Class<?> cls, Type genericType) throws Exception { Class<?> jaxbElementCls = jaxbElementClassNames == null ? null : getJaxbElementClass(cls); boolean asJaxbElement = jaxbElementCls != null; if (!asJaxbElement && isXmlRoot(cls) && !xmlRootAsJaxbElement) { return obj; } if (jaxbElementCls == null) { jaxbElementCls = cls; } QName name = null; String expandedName = jaxbElementClassMap.get(jaxbElementCls.getName()); if (expandedName != null) { name = JAXRSUtils.convertStringToQName(expandedName); } else if (marshalAsJaxbElement || asJaxbElement) { name = getJaxbQName(jaxbElementCls, genericType, obj, false); } return name != null ? new JAXBElement<Object>(name, (Class)jaxbElementCls, null, obj) : obj; } protected Class<?> getJaxbElementClass(Class<?> cls) { if (cls == Object.class) { return null; } if (jaxbElementClassNames.contains(cls.getName())) { return cls; } return getJaxbElementClass(cls.getSuperclass()); } public void setCollectionWrapperName(String wName) { collectionWrapperName = wName; } public void setCollectionWrapperMap(Map<String, String> map) { collectionWrapperMap = map; } protected void setContext(MessageContext context) { mc = context; } public boolean isWriteable(Class<?> type, Type genericType, Annotation[] anns, MediaType mt) { if (InjectionUtils.isSupportedCollectionOrArray(type)) { type = InjectionUtils.getActualType(genericType); if (type == null) { return false; } } return marshalAsJaxbElement && (!xmlTypeAsJaxbElementOnly || isXmlType(type)) || isSupported(type, genericType, anns); } public void writeTo(T t, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { @SuppressWarnings("unchecked") Class<T> type = (Class<T>)t.getClass(); writeTo(t, type, genericType, annotations, mediaType, httpHeaders, entityStream); } protected JAXBContext getCollectionContext(Class<?> type) throws JAXBException { if (collectionContextClasses.add(type)) { collectionContextClasses.add(CollectionWrapper.class); } return newJAXBContextInstance( collectionContextClasses.toArray(new Class[0]), cProperties); } protected QName getCollectionWrapperQName(Class<?> cls, Type type, Object object, boolean pluralName) throws Exception { String name = getCollectionWrapperName(cls); if (name == null) { return getJaxbQName(cls, type, object, pluralName); } return JAXRSUtils.convertStringToQName(name); } private String getCollectionWrapperName(Class<?> cls) { if (collectionWrapperName != null) { return collectionWrapperName; } if (collectionWrapperMap != null) { return collectionWrapperMap.get(cls.getName()); } return null; } protected QName getJaxbQName(Class<?> cls, Type type, Object object, boolean pluralName) throws Exception { if (cls == JAXBElement.class) { return object != null ? ((JAXBElement<?>)object).getName() : null; } XmlRootElement root = cls.getAnnotation(XmlRootElement.class); if (root != null) { return getQNameFromNamespaceAndName(root.namespace(), root.name(), cls, pluralName); } else if (isXmlType(cls)) { XmlType xmlType = cls.getAnnotation(XmlType.class); return getQNameFromNamespaceAndName(xmlType.namespace(), xmlType.name(), cls, pluralName); } else { return new QName(getPackageNamespace(cls), cls.getSimpleName()); } } private static QName getQNameFromNamespaceAndName(String ns, String localName, Class<?> cls, boolean plural) { String name = getLocalName(localName, cls.getSimpleName(), plural); String namespace = getNamespace(ns); if ("".equals(namespace)) { namespace = getPackageNamespace(cls); } return new QName(namespace, name); } private static String getLocalName(String name, String clsName, boolean pluralName) { if (JAXB_DEFAULT_NAME.equals(name)) { name = clsName; if (name.length() > 1) { name = name.substring(0, 1).toLowerCase() + name.substring(1); } else { name = name.toLowerCase(); } } if (pluralName) { name += 's'; } return name; } private static String getPackageNamespace(Class<?> cls) { String packageNs = JAXBUtils.getPackageNamespace(cls); return packageNs != null ? getNamespace(packageNs) : ""; } private static String getNamespace(String namespace) { if (JAXB_DEFAULT_NAMESPACE.equals(namespace)) { return ""; } return namespace; } public boolean isReadable(Class<?> type, Type genericType, Annotation[] anns, MediaType mt) { if (InjectionUtils.isSupportedCollectionOrArray(type)) { type = InjectionUtils.getActualType(genericType); if (type == null) { return false; } } return canBeReadAsJaxbElement(type) || isSupported(type, genericType, anns); } protected boolean canBeReadAsJaxbElement(Class<?> type) { return unmarshalAsJaxbElement && type != Response.class; } public void setSchemaLocations(List<String> locations) { schema = SchemaHandler.createSchema(locations, catalogLocation, getBus()); } public void setCatalogLocation(String name) { this.catalogLocation = name; } public void setSchemaHandler(SchemaHandler handler) { setSchema(handler.getSchema()); } public void setSchemaHandlers(Map<String, SchemaHandler> handlers) { schemaHandlers = handlers; } protected void setSchema(Schema s) { schema = s; } public long getSize(T o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) { return -1; } protected MessageContext getContext() { return mc; } @SuppressWarnings("unchecked") public JAXBContext getJAXBContext(Class<?> type, Type genericType) throws JAXBException { if (mc != null) { ContextResolver<JAXBContext> resolver = mc.getResolver(ContextResolver.class, JAXBContext.class); if (resolver != null) { JAXBContext customContext = resolver.getContext(type); if (customContext != null) { return customContext; } } } JAXBContext context = classContexts.get(type); if (context != null) { return context; } context = getPackageContext(type, genericType); return context != null ? context : getClassContext(type, genericType); } public JAXBContext getClassContext(Class<?> type) throws JAXBException { return getClassContext(type, type); } protected JAXBContext getClassContext(Class<?> type, Type genericType) throws JAXBException { final JAXBException[] jaxbException = new JAXBException[] {null}; final JAXBContext context = classContexts.computeIfAbsent(type, t -> { final Class<?>[] classes; if (extraClass != null) { classes = new Class[extraClass.length + 1]; classes[0] = type; System.arraycopy(extraClass, 0, classes, 1, extraClass.length); } else { classes = new Class[] {type}; } try { return newJAXBContextInstance(classes, cProperties); } catch (JAXBException e) { jaxbException[0] = e; return null; } }); if (null != jaxbException[0]) { throw jaxbException[0]; } return context; } public JAXBContext getPackageContext(Class<?> type) { return getPackageContext(type, type); } protected JAXBContext getPackageContext(final Class<?> type, Type genericType) { if (type == null || type == JAXBElement.class) { return null; } final String packageName = PackageUtils.getPackageName(type); return packageContexts.computeIfAbsent(packageName, p -> { try { final ClassLoader loader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> { return type.getClassLoader(); }); if (loader != null && objectFactoryOrIndexAvailable(type)) { String contextName = packageName; if (extraClass != null) { StringBuilder sb = new StringBuilder(contextName); for (Class<?> extra : extraClass) { String extraPackage = PackageUtils.getPackageName(extra); if (!extraPackage.equals(packageName)) { sb.append(':').append(extraPackage); } } contextName = sb.toString(); } return JAXBContext.newInstance(contextName, loader, cProperties); } } catch (JAXBException ex) { LOG.fine("Error creating a JAXBContext using ObjectFactory : " + ex.getMessage()); } return null; }); } protected boolean isSupported(Class<?> type, Type genericType, Annotation[] anns) { if (jaxbElementClassMap != null && jaxbElementClassMap.containsKey(type.getName()) || isSkipJaxbChecks()) { return true; } if (UNSUPPORTED_CLASSES.contains(type)) { return false; } return isXmlRoot(type) || JAXBElement.class.isAssignableFrom(type) || objectFactoryOrIndexAvailable(type) || (type != genericType && objectFactoryForType(genericType)) || org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(type, anns) != null; } protected boolean objectFactoryOrIndexAvailable(Class<?> type) { if (this.objectFactoryOrIndexMap.get(type.getName()) != null) { return this.objectFactoryOrIndexMap.get(type.getName()); } else { boolean ret = type.getResource("ObjectFactory.class") != null || type.getResource("jaxb.index") != null; this.objectFactoryOrIndexMap.put(type.getName(), ret); return ret; } } private boolean objectFactoryForType(Type genericType) { return objectFactoryOrIndexAvailable(InjectionUtils.getActualType(genericType)); } protected Unmarshaller createUnmarshaller(Class<?> cls, Type genericType) throws JAXBException { return createUnmarshaller(cls, genericType, false); } protected Unmarshaller createUnmarshaller(Class<?> cls, Type genericType, boolean isCollection) throws JAXBException { JAXBContext context = isCollection ? getCollectionContext(cls) : getJAXBContext(cls, genericType); Unmarshaller unmarshaller = context.createUnmarshaller(); if (validateInputIfPossible) { Schema theSchema = getSchema(cls); if (theSchema != null) { unmarshaller.setSchema(theSchema); } } if (eventHandler != null) { unmarshaller.setEventHandler(eventHandler); } if (unmarshallerListener != null) { unmarshaller.setListener(unmarshallerListener); } if (uProperties != null) { for (Map.Entry<String, Object> entry : uProperties.entrySet()) { unmarshaller.setProperty(entry.getKey(), entry.getValue()); } } return unmarshaller; } protected Marshaller createMarshaller(Object obj, Class<?> cls, Type genericType, String enc) throws JAXBException { Class<?> objClazz = JAXBElement.class.isAssignableFrom(cls) ? ((JAXBElement<?>)obj).getDeclaredType() : cls; JAXBContext context = getJAXBContext(objClazz, genericType); Marshaller marshaller = context.createMarshaller(); if (enc != null) { marshaller.setProperty(Marshaller.JAXB_ENCODING, enc); } if (marshallerListener != null) { marshaller.setListener(marshallerListener); } validateObjectIfNeeded(marshaller, cls, obj); return marshaller; } protected void validateObjectIfNeeded(Marshaller marshaller, Class<?> cls, Object obj) throws JAXBException { if (validateOutputIfPossible) { Schema theSchema = getSchema(cls); if (theSchema != null) { marshaller.setEventHandler(eventHandler); marshaller.setSchema(theSchema); if (validateBeforeWrite) { marshaller.marshal(obj, new DefaultHandler()); marshaller.setSchema(null); } } } } protected Class<?> getActualType(Class<?> type, Type genericType, Annotation[] anns) { Class<?> theType; if (JAXBElement.class.isAssignableFrom(type)) { theType = InjectionUtils.getActualType(genericType); } else { theType = type; } XmlJavaTypeAdapter adapter = org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(theType, anns); theType = org.apache.cxf.jaxrs.utils.JAXBUtils.getTypeFromAdapter(adapter, theType, false); return theType; } protected static Object checkAdapter(Object obj, Class<?> cls, Annotation[] anns, boolean marshal) { XmlJavaTypeAdapter adapter = org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(cls, anns); return org.apache.cxf.jaxrs.utils.JAXBUtils.useAdapter(obj, adapter, marshal); } protected Schema getSchema() { return getSchema(null); } protected Schema getSchema(Class<?> cls) { // deal with the typical default case first if (schema == null && schemaHandlers == null) { return null; } if (schema != null) { return schema; } SchemaHandler handler = schemaHandlers.get(cls.getName()); return handler != null ? handler.getSchema() : null; } public void clearContexts() { classContexts.clear(); packageContexts.clear(); objectFactoryOrIndexMap.clear(); } //TODO: move these methods into the dedicated utility class protected static StringBuilder handleExceptionStart(Exception e) { LOG.warning(ExceptionUtils.getStackTrace(e)); StringBuilder sb = new StringBuilder(); if (e.getMessage() != null) { sb.append(e.getMessage()).append(". "); } if (e.getCause() != null && e.getCause().getMessage() != null) { sb.append(e.getCause().getMessage()).append(". "); } return sb; } protected static void handleExceptionEnd(Throwable t, String message, boolean read) { Response.Status status = read ? Response.Status.BAD_REQUEST : Response.Status.INTERNAL_SERVER_ERROR; Response r = JAXRSUtils.toResponseBuilder(status) .type(MediaType.TEXT_PLAIN).entity(message).build(); throw read ? ExceptionUtils.toBadRequestException(t, r) : ExceptionUtils.toInternalServerErrorException(t, r); } protected void handleJAXBException(JAXBException e, boolean read) { StringBuilder sb = handleExceptionStart(e); Throwable linked = e.getLinkedException(); if (linked != null && linked.getMessage() != null) { Throwable cause = linked; while (read && cause != null) { if (cause instanceof XMLStreamException && cause.getMessage().startsWith("Maximum Number")) { throw ExceptionUtils.toWebApplicationException(null, JAXRSUtils.toResponse(413)); } if (cause instanceof DepthExceededStaxException) { throw ExceptionUtils.toWebApplicationException(null, JAXRSUtils.toResponse(413)); } cause = cause.getCause(); } String msg = linked.getMessage(); if (sb.lastIndexOf(msg) == -1) { sb.append(msg).append(". "); } } Throwable t = linked != null ? linked : e.getCause() != null ? e.getCause() : e; String message = new org.apache.cxf.common.i18n.Message("JAXB_EXCEPTION", BUNDLE, sb.toString()).toString(); handleExceptionEnd(t, message, read); } protected void handleXMLStreamException(XMLStreamException e, boolean read) { StringBuilder sb = handleExceptionStart(e); handleExceptionEnd(e, sb.toString(), read); } public void setOutTransformElements(Map<String, String> outElements) { this.outElementsMap = outElements; } public void setInAppendElements(Map<String, String> inElements) { this.inAppendMap = inElements; } public void setInTransformElements(Map<String, String> inElements) { this.inElementsMap = inElements; } public void setOutAppendElements(Map<String, String> map) { this.outAppendMap = map; } public void setOutDropElements(List<String> dropElementsSet) { this.outDropElements = dropElementsSet; } public void setInDropElements(List<String> dropElementsSet) { this.inDropElements = dropElementsSet; } public void setAttributesToElements(boolean value) { this.attributesToElements = value; } public void setSkipJaxbChecks(boolean skipJaxbChecks) { this.skipJaxbChecks = skipJaxbChecks; } public boolean isSkipJaxbChecks() { return skipJaxbChecks; } protected XMLStreamWriter createTransformWriterIfNeeded(XMLStreamWriter writer, OutputStream os, boolean dropAtXmlLevel) { return TransformUtils.createTransformWriterIfNeeded(writer, os, outElementsMap, dropAtXmlLevel ? outDropElements : null, outAppendMap, attributesToElements, null); } protected XMLStreamReader createTransformReaderIfNeeded(XMLStreamReader reader, InputStream is) { return TransformUtils.createTransformReaderIfNeeded(reader, is, inDropElements, inElementsMap, inAppendMap, true); } protected XMLStreamReader createDepthReaderIfNeeded(XMLStreamReader reader, InputStream is) { DocumentDepthProperties props = getDepthProperties(); if (props != null && props.isEffective()) { reader = TransformUtils.createNewReaderIfNeeded(reader, is); reader = new DepthRestrictingStreamReader(reader, props); } else if (reader != null) { reader = configureReaderRestrictions(reader); } return reader; } protected XMLStreamReader configureReaderRestrictions(XMLStreamReader reader) { Message message = PhaseInterceptorChain.getCurrentMessage(); if (message != null) { try { return StaxUtils.configureReader(reader, message); } catch (XMLStreamException ex) { throw ExceptionUtils.toInternalServerErrorException(ex, null); } } return reader; } protected DocumentDepthProperties getDepthProperties() { return depthProperties; } public void setValidateBeforeWrite(boolean validateBeforeWrite) { this.validateBeforeWrite = validateBeforeWrite; } public void setValidateOutput(boolean validateOutput) { this.validateOutputIfPossible = validateOutput; } public void setValidateInput(boolean validateInput) { this.validateInputIfPossible = validateInput; } public void setDepthProperties(DocumentDepthProperties depthProperties) { this.depthProperties = depthProperties; } public void setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener) { this.unmarshallerListener = unmarshallerListener; } public void setMarshallerListener(Marshaller.Listener marshallerListener) { this.marshallerListener = marshallerListener; } public void setNamespaceMapperPropertyName(String namespaceMapperProperty) { this.namespaceMapperPropertyName = namespaceMapperProperty; } @XmlRootElement protected static class CollectionWrapper { @XmlAnyElement(lax = true) private List<?> l; public void setList(List<?> list) { l = list; } public List<?> getList() { if (l == null) { l = new ArrayList<>(); } return l; } @SuppressWarnings("unchecked") public <T> Object getCollectionOrArray(Unmarshaller unm, Class<T> type, Class<?> collectionType, Type genericType, XmlJavaTypeAdapter adapter) throws JAXBException { List<?> theList = getList(); boolean adapterChecked = false; if (!theList.isEmpty()) { Object first = theList.get(0); if (first instanceof Element) { List<Object> newList = new ArrayList<>(theList.size()); for (Object o : theList) { newList.add(unm.unmarshal((Element)o, type)); } theList = newList; } first = theList.get(0); Type[] types = InjectionUtils.getActualTypes(genericType); boolean isJaxbElement = types != null && types.length > 0 && InjectionUtils.getRawType(types[0]) == JAXBElement.class; if (first instanceof JAXBElement && !isJaxbElement && !JAXBElement.class.isAssignableFrom(type)) { adapterChecked = true; List<Object> newList = new ArrayList<>(theList.size()); for (Object o : theList) { newList.add(org.apache.cxf.jaxrs.utils.JAXBUtils.useAdapter( ((JAXBElement<?>)o).getValue(), adapter, false)); } theList = newList; } else if (!(first instanceof JAXBElement) && isJaxbElement) { List<Object> newList = new ArrayList<>(theList.size()); XmlRootElement root = type.getAnnotation(XmlRootElement.class); QName qname = getQNameFromNamespaceAndName(root.namespace(), root.name(), type, false); @SuppressWarnings("rawtypes") Class theType = type; for (Object o : theList) { newList.add(new JAXBElement<Object>(qname, theType, null, o)); } theList = newList; } } if (collectionType.isArray()) { T[] values = (T[])Array.newInstance(type, theList.size()); for (int i = 0; i < theList.size(); i++) { values[i] = (T)org.apache.cxf.jaxrs.utils.JAXBUtils.useAdapter( theList.get(i), adapter, false); } return values; } if (!adapterChecked && adapter != null) { List<Object> newList = new ArrayList<>(theList.size()); for (Object o : theList) { newList.add(org.apache.cxf.jaxrs.utils.JAXBUtils.useAdapter(o, adapter, false)); } theList = newList; } if (collectionType == Set.class) { return new HashSet<>(theList); } return theList; } } protected static class JAXBCollectionWrapperReader extends DepthXMLStreamReader { private boolean firstName; private boolean firstNs; public JAXBCollectionWrapperReader(XMLStreamReader reader) { super(reader); } @Override public String getNamespaceURI() { if (!firstNs) { firstNs = true; return ""; } return super.getNamespaceURI(); } @Override public String getLocalName() { if (!firstName) { firstName = true; return "collectionWrapper"; } return super.getLocalName(); } } }
apache/pinot
38,085
pinot-controller/src/test/java/org/apache/pinot/controller/api/TableConfigsRestletResourceTest.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.pinot.controller.api; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Sets; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.pinot.controller.helix.ControllerTest; import org.apache.pinot.core.realtime.impl.fakestream.FakeStreamConfigUtils; import org.apache.pinot.spi.config.TableConfigs; import org.apache.pinot.spi.config.table.SegmentsValidationAndRetentionConfig; import org.apache.pinot.spi.config.table.TableConfig; import org.apache.pinot.spi.config.table.TableType; import org.apache.pinot.spi.config.table.TunerConfig; import org.apache.pinot.spi.data.DateTimeFieldSpec; import org.apache.pinot.spi.data.FieldSpec; import org.apache.pinot.spi.data.LogicalTableConfig; import org.apache.pinot.spi.data.MetricFieldSpec; import org.apache.pinot.spi.data.Schema; import org.apache.pinot.spi.stream.StreamConfig; import org.apache.pinot.spi.utils.CommonConstants; import org.apache.pinot.spi.utils.JsonUtils; import org.apache.pinot.spi.utils.builder.ControllerRequestURLBuilder; import org.apache.pinot.spi.utils.builder.TableConfigBuilder; import org.apache.pinot.spi.utils.builder.TableNameBuilder; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.collections.Lists; import static org.testng.Assert.fail; /** * Tests for CRUD APIs of {@link TableConfigs} */ public class TableConfigsRestletResourceTest extends ControllerTest { private String _createTableConfigsUrl; @BeforeClass public void setUp() throws Exception { DEFAULT_INSTANCE.setupSharedStateAndValidate(); _createTableConfigsUrl = DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsCreate(); } private TableConfigBuilder getBaseTableConfigBuilder(String tableName, TableType tableType) { if (tableType == TableType.OFFLINE) { return new TableConfigBuilder(TableType.OFFLINE).setTableName(tableName).setTimeColumnName("timeColumn") .setRetentionTimeUnit("DAYS").setRetentionTimeValue("50"); } else { StreamConfig streamConfig = FakeStreamConfigUtils.getDefaultLowLevelStreamConfigs(); return new TableConfigBuilder(TableType.REALTIME).setTableName(tableName).setTimeColumnName("timeColumn") .setRetentionTimeUnit("DAYS").setRetentionTimeValue("5").setStreamConfigs(streamConfig.getStreamConfigsMap()); } } private TableConfig createOfflineTableConfig(String tableName) { return getBaseTableConfigBuilder(tableName, TableType.OFFLINE).build(); } private TableConfig createRealtimeTableConfig(String tableName) { return getBaseTableConfigBuilder(tableName, TableType.REALTIME).build(); } private TableConfig createOfflineTunerTableConfig(String tableName) { return getBaseTableConfigBuilder(tableName, TableType.OFFLINE).setTunerConfigList( Lists.newArrayList(new TunerConfig("realtimeAutoIndexTuner", null))).build(); } private TableConfig createRealtimeTunerTableConfig(String tableName) { return getBaseTableConfigBuilder(tableName, TableType.REALTIME).setTunerConfigList( Lists.newArrayList(new TunerConfig("realtimeAutoIndexTuner", null))).build(); } private TableConfig createOfflineDimTableConfig(String tableName) { return getBaseTableConfigBuilder(tableName, TableType.OFFLINE).setIsDimTable(true).build(); } @Test public void testValidateConfig() throws IOException { String validateConfigUrl = DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsValidate(); String tableName = "testValidate"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); TableConfig realtimeTableConfig = createRealtimeTableConfig(tableName); Schema schema = createDummySchema(tableName); TableConfigs tableConfigs; // invalid json try { tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, realtimeTableConfig); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString().replace("\"offline\"", "offline\"")); fail("Creation of a TableConfigs with invalid json string should have failed"); } catch (Exception e) { // expected } // null table configs try { tableConfigs = new TableConfigs(tableName, schema, null, null); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with null table offline tableConfig and realtime tableConfig should have " + "failed"); } catch (Exception e) { // expected } // null schema try { tableConfigs = new TableConfigs(tableName, null, offlineTableConfig, null); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with null schema should have failed"); } catch (Exception e) { // expected } // empty config name try { tableConfigs = new TableConfigs("", schema, offlineTableConfig, realtimeTableConfig); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with empty config name should have failed"); } catch (Exception e) { // expected } // schema name doesn't match config name try { tableConfigs = new TableConfigs(tableName, createDummySchema("differentName"), offlineTableConfig, realtimeTableConfig); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with schema name different than tableName should have failed"); } catch (Exception e) { // expected } // schema validation fails try { Schema schemaWithBlankSpace = createDummySchema(tableName); schemaWithBlankSpace.addField(new MetricFieldSpec("blank space", FieldSpec.DataType.LONG)); tableConfigs = new TableConfigs(tableName, schemaWithBlankSpace, offlineTableConfig, realtimeTableConfig); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with blank space in column should have failed"); } catch (Exception e) { // expected } // offline table name doesn't match config name try { tableConfigs = new TableConfigs(tableName, schema, createOfflineTableConfig("differentName"), null); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with offline table name different than tableName should have failed"); } catch (Exception e) { // expected } // table name validation fails try { tableConfigs = new TableConfigs("blank space", createDummySchema("blank space"), createOfflineTableConfig("blank space"), null); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with blank space in table name should have failed"); } catch (Exception e) { // expected } // table validation fails try { TableConfig invalidTableConfig = createOfflineTableConfig(tableName); invalidTableConfig.getIndexingConfig().setInvertedIndexColumns(Lists.newArrayList("nonExistent")); tableConfigs = new TableConfigs(tableName, schema, invalidTableConfig, null); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with invalid table config should have failed"); } catch (Exception e) { // expected } // realtime table name doesn't match config name try { tableConfigs = new TableConfigs(tableName, schema, null, createRealtimeTableConfig("differentName")); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with realtime table name different than tableName should have failed"); } catch (Exception e) { // expected } // table name validation fails try { tableConfigs = new TableConfigs("blank space", createDummySchema("blank space"), null, createRealtimeTableConfig("blank space")); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with blank space in table name should have failed"); } catch (Exception e) { // expected } // table validation fails try { TableConfig invalidTableConfig = createRealtimeTableConfig(tableName); invalidTableConfig.getIndexingConfig().setInvertedIndexColumns(Lists.newArrayList("nonExistent")); tableConfigs = new TableConfigs(tableName, schema, null, invalidTableConfig); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with invalid table config should have failed"); } catch (Exception e) { // expected } // hybrid config consistency check fails try { Schema twoTimeColumns = createDummySchema(tableName); twoTimeColumns.addField( new DateTimeFieldSpec("time1", FieldSpec.DataType.LONG, "1:MILLISECONDS:EPOCH", "1:MILLISECONDS")); twoTimeColumns.addField( new DateTimeFieldSpec("time2", FieldSpec.DataType.LONG, "1:MILLISECONDS:EPOCH", "1:MILLISECONDS")); TableConfig offlineTableConfig1 = createOfflineTableConfig(tableName); offlineTableConfig1.getValidationConfig().setTimeColumnName("time1"); TableConfig realtimeTableConfig1 = createRealtimeTableConfig(tableName); realtimeTableConfig1.getValidationConfig().setTimeColumnName("time2"); tableConfigs = new TableConfigs(tableName, twoTimeColumns, offlineTableConfig1, realtimeTableConfig1); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs with inconsistencies across offline and realtime table config should have " + "failed"); } catch (Exception e) { // expected } // table name check fails when database context is not passed in header but one of the configs has database prefix Schema dummySchema = createDummySchema(tableName); TableConfig offlineTableConfig1 = createOfflineTableConfig("db1." + tableName); TableConfig realtimeTableConfig1 = createRealtimeTableConfig(tableName); tableConfigs = new TableConfigs(tableName, dummySchema, offlineTableConfig1, realtimeTableConfig1); try { sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs without database context in header but provided in one of the configs should " + "fail"); } catch (Exception e) { // expected } // fails with schema as well offlineTableConfig1.setTableName(TableNameBuilder.OFFLINE.tableNameWithType(tableName)); dummySchema.setSchemaName("db1." + tableName); try { sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs without database context in header but provided in one of the configs should " + "fail"); } catch (Exception e) { // expected } // fails even though both configs and schema have the database prefix in the table names but // database context is not passed in header tableConfigs.setTableName("db1." + tableName); try { sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); fail("Creation of an TableConfigs without database context in header but provided in all of the configs should " + "fail"); } catch (Exception e) { // expected } // successfully created with all 3 configs when database context is passed in header and configs may or may not // have the database prefix in the table names Map<String, String> headers = new HashMap<>(); tableConfigs.setTableName(tableName); headers.put(CommonConstants.DATABASE, "db1"); // only schema has the database prefix dummySchema.setSchemaName("db1." + tableName); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString(), headers); // one of the table config has database prefix offlineTableConfig1.setTableName(TableNameBuilder.OFFLINE.tableNameWithType(tableName)); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString(), headers); // successfully created with all 3 configs String tableName1 = "testValidate1"; tableConfigs = new TableConfigs(tableName1, createDummySchema(tableName1), createOfflineTableConfig(tableName1), createRealtimeTableConfig(tableName1)); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); // successfully create with offline config String tableName2 = "testValidate2"; tableConfigs = new TableConfigs(tableName2, createDummySchema(tableName2), createOfflineTableConfig(tableName2), null); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); // successfully create with realtime config String tableName3 = "testValidate3"; tableConfigs = new TableConfigs(tableName3, createDummySchema(tableName3), null, createRealtimeTableConfig(tableName3)); sendPostRequest(validateConfigUrl, tableConfigs.toPrettyJsonString()); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName1)); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName2)); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName3)); } /** * Tests for creation of TableConfigs */ @Test public void testCreateConfig() throws IOException { String tableName = "testCreate"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); TableConfig realtimeTableConfig = createRealtimeTableConfig(tableName); Schema schema = createDummySchema(tableName); TableConfigs tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, realtimeTableConfig); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); String response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); TableConfigs tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); Assert.assertEquals(tableConfigsResponse.getOffline().getTableName(), offlineTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getRealtime().getTableName(), realtimeTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getSchema().getSchemaName(), schema.getSchemaName()); // test POST of existing configs fails try { sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); fail("Should fail for trying to add existing config"); } catch (Exception e) { // expected } sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); // replica check tableName = "testCreateReplicas"; TableConfig replicaTestOfflineTableConfig = createOfflineTableConfig(tableName); TableConfig replicaTestRealtimeTableConfig = createRealtimeTableConfig(tableName); replicaTestOfflineTableConfig.getValidationConfig().setReplication("1"); replicaTestRealtimeTableConfig.getValidationConfig().setReplication("1"); tableConfigs = new TableConfigs(tableName, createDummySchema(tableName), replicaTestOfflineTableConfig, replicaTestRealtimeTableConfig); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); Assert.assertEquals(tableConfigsResponse.getOffline().getReplication(), DEFAULT_MIN_NUM_REPLICAS); Assert.assertEquals(tableConfigsResponse.getRealtime().getReplication(), DEFAULT_MIN_NUM_REPLICAS); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); // quota check tableName = "testCreateQuota"; TableConfig offlineDimTableConfig = createOfflineDimTableConfig(tableName); Schema dimSchema = createDummySchemaWithPrimaryKey(tableName); tableConfigs = new TableConfigs(tableName, dimSchema, offlineDimTableConfig, null); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableName, tableConfigsResponse.getTableName()); Assert.assertEquals(tableConfigsResponse.getOffline().getQuotaConfig().getStorage(), DEFAULT_INSTANCE.getControllerConfig().getDimTableMaxSize()); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); // tuner config tableName = "testTunerConfig"; TableConfig offlineTunerTableConfig = createOfflineTunerTableConfig(tableName); TableConfig realtimeTunerTableConfig = createRealtimeTunerTableConfig(tableName); tableConfigs = new TableConfigs(tableName, createDummySchema(tableName), offlineTunerTableConfig, realtimeTunerTableConfig); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableName, tableConfigsResponse.getTableName()); Assert.assertTrue(tableConfigsResponse.getOffline().getIndexingConfig().getInvertedIndexColumns() .containsAll(schema.getDimensionNames())); Assert.assertTrue(tableConfigsResponse.getOffline().getIndexingConfig().getNoDictionaryColumns() .containsAll(schema.getMetricNames())); Assert.assertTrue(tableConfigsResponse.getRealtime().getIndexingConfig().getInvertedIndexColumns() .containsAll(schema.getDimensionNames())); Assert.assertTrue(tableConfigsResponse.getRealtime().getIndexingConfig().getNoDictionaryColumns() .containsAll(schema.getMetricNames())); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); } @Test public void testListConfigs() throws IOException { // create with 1 config String tableName1 = "testList1"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName1); TableConfig realtimeTableConfig = createRealtimeTableConfig(tableName1); Schema schema = createDummySchema(tableName1); TableConfigs tableConfigs = new TableConfigs(tableName1, schema, offlineTableConfig, null); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); // list String getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); List<String> configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 1); Assert.assertTrue(configs.containsAll(Sets.newHashSet(tableName1))); // update to 2 tableConfigs = new TableConfigs(tableName1, schema, offlineTableConfig, realtimeTableConfig); sendPutRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName1), tableConfigs.toPrettyJsonString()); // list getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 1); Assert.assertTrue(configs.containsAll(Sets.newHashSet("testList1"))); // create new String tableName2 = "testList2"; offlineTableConfig = createOfflineTableConfig(tableName2); schema = createDummySchema(tableName2); tableConfigs = new TableConfigs(tableName2, schema, offlineTableConfig, null); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); // list getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 2); Assert.assertTrue(configs.containsAll(Sets.newHashSet(tableName1, tableName2))); // delete 1 sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName2)); // list 1 getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 1); Assert.assertTrue(configs.containsAll(Sets.newHashSet(tableName1))); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName1)); } @Test public void testUpdateConfig() throws IOException { // create with 1 String tableName = "testUpdate1"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); TableConfig realtimeTableConfig = createRealtimeTableConfig(tableName); Schema schema = createDummySchema(tableName); TableConfigs tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, null); // PUT before POST should fail try { sendPutRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName), tableConfigs.toPrettyJsonString()); fail("Should fail for trying to PUT config before creating via POST"); } catch (Exception e) { // expected } sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); String response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); TableConfigs tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); Assert.assertEquals(tableConfigsResponse.getOffline().getTableName(), offlineTableConfig.getTableName()); Assert.assertNull(tableConfigs.getRealtime()); Assert.assertEquals(tableConfigsResponse.getSchema().getSchemaName(), schema.getSchemaName()); // list String getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); List<String> configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 1); Assert.assertTrue(configs.containsAll(Sets.newHashSet(tableName))); // update to 2 tableConfigs = new TableConfigs(tableName, tableConfigsResponse.getSchema(), tableConfigsResponse.getOffline(), realtimeTableConfig); sendPutRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName), tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); Assert.assertEquals(tableConfigsResponse.getOffline().getTableName(), offlineTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getRealtime().getTableName(), realtimeTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getSchema().getSchemaName(), schema.getSchemaName()); // list getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 1); Assert.assertTrue(configs.containsAll(Sets.newHashSet(tableName))); // update existing config schema.addField(new MetricFieldSpec("newMetric", FieldSpec.DataType.LONG)); tableConfigs = new TableConfigs(tableName, schema, tableConfigsResponse.getOffline(), tableConfigsResponse.getRealtime()); sendPutRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName), tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); Assert.assertEquals(tableConfigsResponse.getOffline().getTableName(), offlineTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getRealtime().getTableName(), realtimeTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getSchema().getSchemaName(), schema.getSchemaName()); Assert.assertTrue(tableConfigsResponse.getSchema().getMetricNames().contains("newMetric")); tableConfigsResponse.getOffline().getIndexingConfig().setInvertedIndexColumns(Lists.newArrayList("dimA")); tableConfigsResponse.getRealtime().getIndexingConfig().setInvertedIndexColumns(Lists.newArrayList("dimA")); tableConfigs = new TableConfigs(tableName, schema, tableConfigsResponse.getOffline(), tableConfigsResponse.getRealtime()); sendPutRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName), tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertTrue(tableConfigsResponse.getOffline().getIndexingConfig().getInvertedIndexColumns().contains("dimA")); Assert.assertTrue( tableConfigsResponse.getRealtime().getIndexingConfig().getInvertedIndexColumns().contains("dimA")); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); } @Test public void testForceUpdateTableSchemaAndConfigs() throws IOException { String tableName = "testUpdate1"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); Schema schema = createDummySchema(tableName); TableConfigs tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, null); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); String response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); TableConfigs tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertNotNull(tableConfigs.getOffline()); // Remove field from schema and try to update schema without the 'forceTableSchemaUpdate' option schema.removeField("dimA"); tableConfigs = new TableConfigs(tableName, schema, tableConfigsResponse.getOffline(), tableConfigsResponse.getRealtime()); String tableConfigUpdateUrl = DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName); try { sendPutRequest(tableConfigUpdateUrl, tableConfigs.toPrettyJsonString()); } catch (IOException e) { Assert.assertTrue(e.getMessage().contains("is not backward-compatible with the existing schema")); } // Skip validate table configs – Exception is still thrown String newTableConfigUpdateUrl = tableConfigUpdateUrl + "?validationTypesToSkip=ALL"; try { sendPutRequest(newTableConfigUpdateUrl, tableConfigs.toPrettyJsonString()); } catch (IOException e) { Assert.assertTrue(e.getMessage().contains("is not backward-compatible with the existing schema")); } // Skip table config validation as well as force update the table schema – no exceptions are thrown newTableConfigUpdateUrl = tableConfigUpdateUrl + "?validationTypesToSkip=ALL&forceTableSchemaUpdate=true"; response = sendPutRequest(newTableConfigUpdateUrl, tableConfigs.toPrettyJsonString()); Assert.assertTrue(response.contains("TableConfigs updated for testUpdate1")); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); } @Test public void testDeleteConfig() throws Exception { // create with 1 config String tableName = "testDelete1"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); Schema schema = createDummySchema(tableName); TableConfigs tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, null); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); String response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); TableConfigs tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); // delete & check sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); String getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); List<String> configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 0); tableName = "testDelete2"; offlineTableConfig = createOfflineTableConfig(tableName); TableConfig realtimeTableConfig = createRealtimeTableConfig(tableName); schema = createDummySchema(tableName); tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, realtimeTableConfig); sendPostRequest(_createTableConfigsUrl, tableConfigs.toPrettyJsonString()); response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); // delete & check sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); getResponse = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsList()); configs = JsonUtils.stringToObject(getResponse, new TypeReference<List<String>>() { }); Assert.assertEquals(configs.size(), 0); } @Test public void testDeleteTableWithLogicalTable() throws IOException { String logicalTableName = "testDeleteLogicalTable"; String tableName = "physicalTable"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); TableConfig realtimeTableConfig = createRealtimeTableConfig(tableName); ControllerRequestURLBuilder urlBuilder = DEFAULT_INSTANCE.getControllerRequestURLBuilder(); DEFAULT_INSTANCE.addDummySchema(logicalTableName); DEFAULT_INSTANCE.addDummySchema(tableName); DEFAULT_INSTANCE.addTableConfig(offlineTableConfig); DEFAULT_INSTANCE.addTableConfig(realtimeTableConfig); // Create logical table String createLogicalTableUrl = urlBuilder.forLogicalTableCreate(); LogicalTableConfig logicalTableConfig = getDummyLogicalTableConfig(logicalTableName, List.of(offlineTableConfig.getTableName(), realtimeTableConfig.getTableName()), "DefaultTenant"); String response = sendPostRequest(createLogicalTableUrl, logicalTableConfig.toJsonString()); Assert.assertTrue(response.contains("testDeleteLogicalTable logical table successfully added"), response); // Delete table should fail because it is referenced by a logical table String msg = Assert.expectThrows( IOException.class, () -> sendDeleteRequest(urlBuilder.forTableConfigsDelete(tableName))).getMessage(); Assert.assertTrue(msg.contains("Cannot delete table config: " + tableName + " because it is referenced in logical table: " + logicalTableName), msg); // Delete logical table String deleteLogicalTableUrl = urlBuilder.forLogicalTableDelete(logicalTableName); response = sendDeleteRequest(deleteLogicalTableUrl); Assert.assertTrue(response.contains("testDeleteLogicalTable logical table successfully deleted"), response); // physical table should be deleted successfully response = sendDeleteRequest(urlBuilder.forTableConfigsDelete(tableName)); Assert.assertTrue(response.contains("Deleted TableConfigs: physicalTable"), response); } @Test public void testDeleteTableConfigWithTableTypeValidation() throws IOException { ControllerRequestURLBuilder urlBuilder = DEFAULT_INSTANCE.getControllerRequestURLBuilder(); String tableName = "testDeleteWithTypeValidation"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); DEFAULT_INSTANCE.addDummySchema(tableName); DEFAULT_INSTANCE.addTableConfig(offlineTableConfig); // Delete table should fail because it is not a raw table name String msg = Assert.expectThrows( IOException.class, () -> sendDeleteRequest(urlBuilder.forTableConfigsDelete(offlineTableConfig.getTableName()))) .getMessage(); Assert.assertTrue(msg.contains("Invalid table name: testDeleteWithTypeValidation_OFFLINE. Use raw table name."), msg); // Delete table with raw table name String response = sendDeleteRequest(urlBuilder.forTableConfigsDelete(tableName)); Assert.assertTrue(response.contains("Deleted TableConfigs: testDeleteWithTypeValidation"), response); } @Test public void testUnrecognizedProperties() throws IOException { String tableName = "testUnrecognized1"; TableConfig offlineTableConfig = createOfflineTableConfig(tableName); Schema schema = createDummySchema(tableName); TableConfigs tableConfigs = new TableConfigs(tableName, schema, offlineTableConfig, null); ObjectNode tableConfigsJson = JsonUtils.objectToJsonNode(tableConfigs).deepCopy(); tableConfigsJson.put("illegalKey1", 1); // Validate DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsValidate(); String response = sendPostRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsValidate(), tableConfigsJson.toPrettyString()); JsonNode responseJson = JsonUtils.stringToJsonNode(response); Assert.assertTrue(responseJson.has("unrecognizedProperties")); Assert.assertTrue(responseJson.get("unrecognizedProperties").has("/illegalKey1")); // Create response = sendPostRequest(_createTableConfigsUrl, tableConfigsJson.toPrettyString()); Assert.assertEquals(response, "{\"unrecognizedProperties\":{\"/illegalKey1\":1},\"status\":\"TableConfigs " + "testUnrecognized1 successfully added\"}"); // Update response = sendPutRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsUpdate(tableName), tableConfigsJson.toPrettyString()); Assert.assertEquals(response, "{\"unrecognizedProperties\":{\"/illegalKey1\":1},\"status\":\"TableConfigs updated for testUnrecognized1\"}"); // Delete sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsDelete(tableName)); } /** * Tests get TableConfigs for backwards compatibility */ @Test public void testGetConfigCompatibility() throws IOException { String tableName = "table1"; DEFAULT_INSTANCE.addDummySchema(tableName); TableConfig offlineTableConfig = createOfflineTableConfig(tableName); SegmentsValidationAndRetentionConfig validationConfig = new SegmentsValidationAndRetentionConfig(); validationConfig.setReplication("1"); offlineTableConfig.setValidationConfig(validationConfig); sendPostRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableCreate(), offlineTableConfig.toJsonString()); String response = sendGetRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableConfigsGet(tableName)); TableConfigs tableConfigsResponse = JsonUtils.stringToObject(response, TableConfigs.class); Assert.assertEquals(tableConfigsResponse.getTableName(), tableName); Assert.assertEquals(tableConfigsResponse.getOffline().getTableName(), offlineTableConfig.getTableName()); Assert.assertEquals(tableConfigsResponse.getSchema().getSchemaName(), tableName); // Delete sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forTableDelete(tableName)); sendDeleteRequest(DEFAULT_INSTANCE.getControllerRequestURLBuilder().forSchemaDelete(tableName)); } @AfterClass public void tearDown() { DEFAULT_INSTANCE.cleanup(); } }