repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
apache/inlong
36,955
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/config/CommonConfigHolder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.inlong.dataproxy.config; import org.apache.inlong.common.enums.InlongCompressType; import org.apache.inlong.dataproxy.sink.common.DefaultEventHandler; import org.apache.inlong.dataproxy.sink.mq.AllCacheClusterSelector; import org.apache.inlong.dataproxy.utils.AddressUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.flume.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; /** * common.properties Configure Holder */ public class CommonConfigHolder { private static final Logger LOG = LoggerFactory.getLogger(CommonConfigHolder.class); // configure file name private static final String COMMON_CONFIG_FILE_NAME = "common.properties"; // list split separator private static final String VAL_CONFIG_ITEMS_SEPARATOR = ",|\\s+"; // **** allowed keys and default value, begin // proxy node id @Deprecated private static final String KEY_PROXY_NODE_ID = "nodeId"; private static final String KEY_PROXY_NODE_IDV2 = "proxy.node.id"; private static final String VAL_DEF_PROXY_NODE_ID = "127.0.0.1"; // cluster tag private static final String KEY_PROXY_CLUSTER_TAG = "proxy.cluster.tag"; private static final String VAL_DEF_CLUSTER_TAG = "default_cluster"; // cluster name private static final String KEY_PROXY_CLUSTER_NAME = "proxy.cluster.name"; private static final String VAL_DEF_CLUSTER_NAME = "default_dataproxy"; // cluster incharges @Deprecated private static final String KEY_PROXY_CLUSTER_INCHARGES = "proxy.cluster.inCharges"; private static final String KEY_PROXY_CLUSTER_INCHARGESV2 = "proxy.cluster.incharges"; private static final String VAL_DEF_CLUSTER_INCHARGES = "admin"; // cluster exttag, @Deprecated private static final String KEY_PROXY_CLUSTER_EXT_TAG = "proxy.cluster.extTag"; private static final String KEY_PROXY_CLUSTER_EXT_TAGV2 = "proxy.cluster.ext.tag"; // predefined format of ext tag: {key}={value} private static final String VAL_DEF_CLUSTER_EXT_TAG = "default=true"; // manager hosts private static final String KEY_MANAGER_HOSTS = "manager.hosts"; private static final String KEY_MANAGER_HOST_PORT_SEPARATOR = ":"; // manager auth secret id @Deprecated private static final String KEY_MANAGER_AUTH_SECRET_ID = "manager.auth.secretId"; private static final String KEY_MANAGER_AUTH_SECRET_IDV2 = "manager.auth.secret.id"; // manager auth secret key @Deprecated private static final String KEY_MANAGER_AUTH_SECRET_KEY = "manager.auth.secretKey"; private static final String KEY_MANAGER_AUTH_SECRET_KEYV2 = "manager.auth.secret.key"; // configure file check interval @Deprecated private static final String KEY_CONFIG_CHECK_INTERVAL_MS = "configCheckInterval"; private static final String KEY_META_CONFIG_SYNC_INTERVAL_MS = "meta.config.sync.interval.ms"; private static final long VAL_DEF_CONFIG_SYNC_INTERVAL_MS = 60000L; private static final long VAL_MIN_CONFIG_SYNC_INTERVAL_MS = 10000L; // max allowed wait duration private static final String KEY_META_CONFIG_SYNC_WAST_ALARM_MS = "meta.config.sync.wast.alarm.ms"; private static final long VAL_DEF_META_CONFIG_SYNC_WAST_ALARM_MS = 40000L; // whether to startup using the local metadata.json file without connecting to the Manager @Deprecated private static final String KEY_ENABLE_STARTUP_USING_LOCAL_META_FILE = "startup.using.local.meta.file.enable"; private static final String KEY_ENABLE_STARTUP_USING_LOCAL_META_FILEV2 = "meta.config.startup.using.local.file.enable"; private static final boolean VAL_DEF_ENABLE_STARTUP_USING_LOCAL_META_FILE = false; // whether enable file metric, optional field. private static final String KEY_ENABLE_FILE_METRIC = "file.metric.enable"; private static final boolean VAL_DEF_ENABLE_FILE_METRIC = true; // file metric statistic interval (second) private static final String KEY_FILE_METRIC_STAT_INTERVAL_SEC = "file.metric.stat.interval.sec"; private static final int VAL_DEF_FILE_METRIC_STAT_INVL_SEC = 60; private static final int VAL_MIN_FILE_METRIC_STAT_INVL_SEC = 0; // file metric max statistic key count private static final String KEY_FILE_METRIC_MAX_CACHE_CNT = "file.metric.max.cache.cnt"; private static final int VAL_DEF_FILE_METRIC_MAX_CACHE_CNT = 1000000; private static final int VAL_MIN_FILE_METRIC_MAX_CACHE_CNT = 0; // source metric statistic name private static final String KEY_FILE_METRIC_SOURCE_OUTPUT_NAME = "file.metric.source.output.name"; private static final String VAL_DEF_FILE_METRIC_SOURCE_OUTPUT_NAME = "Source"; // sink metric statistic name private static final String KEY_FILE_METRIC_SINK_OUTPUT_NAME = "file.metric.sink.output.name"; private static final String VAL_DEF_FILE_METRIC_SINK_OUTPUT_NAME = "Sink"; // event metric statistic name private static final String KEY_FILE_METRIC_EVENT_OUTPUT_NAME = "file.metric.event.output.name"; private static final String VAL_DEF_FILE_METRIC_EVENT_OUTPUT_NAME = "Stats"; // prometheus http port @Deprecated private static final String KEY_PROMETHEUS_HTTP_PORT = "prometheusHttpPort"; private static final String KEY_PROMETHEUS_HTTP_PORTV2 = "online.metric.prometheus.http.port"; private static final int VAL_DEF_PROMETHEUS_HTTP_PORT = 8080; // Audit fields private static final String KEY_ENABLE_AUDIT = "audit.enable"; private static final boolean VAL_DEF_ENABLE_AUDIT = true; private static final String KEY_AUDIT_PROXYS_DISCOVERY_MANAGER_ENABLE = "audit.proxys.discovery.manager.enable"; private static final boolean VAL_DEF_AUDIT_PROXYS_DISCOVERY_MANAGER_ENABLE = false; private static final String KEY_AUDIT_PROXYS = "audit.proxys"; @Deprecated private static final String KEY_AUDIT_FILE_PATH = "audit.filePath"; private static final String KEY_AUDIT_FILE_PATHV2 = "audit.file.path"; private static final String VAL_DEF_AUDIT_FILE_PATH = "/data/inlong/audit/"; @Deprecated private static final String KEY_AUDIT_MAX_CACHE_ROWS = "audit.maxCacheRows"; private static final String KEY_AUDIT_MAX_CACHE_ROWSV2 = "audit.max.cache.rows"; private static final int VAL_DEF_AUDIT_MAX_CACHE_ROWS = 2000000; @Deprecated private static final String KEY_AUDIT_FORMAT_INTERVAL_MS = "auditFormatInterval"; private static final String KEY_AUDIT_TIME_FORMAT_INTERVAL = "audit.time.format.intvl.ms"; private static final long VAL_DEF_AUDIT_FORMAT_INTERVAL_MS = 60000L; // v1 msg whether response by sink private static final String KEY_V1MSG_RESPONSE_BY_SINK = "isResponseAfterSave"; private static final String KEY_V1MSG_RESPONSE_BY_SINKV2 = "proxy.v1msg.response.by.sink.enable"; private static final boolean VAL_DEF_V1MSG_RESPONSE_BY_SINK = false; // v1 msg sent compress type @Deprecated private static final String KEY_V1MSG_SENT_COMPRESS_TYPE = "compressType"; private static final String KEY_V1MSG_SENT_COMPRESS_TYPEV2 = "proxy.v1msg.compress.type"; private static final InlongCompressType VAL_DEF_V1MSG_COMPRESS_TYPE = InlongCompressType.INLONG_SNAPPY; // Same as KEY_MAX_RESPONSE_TIMEOUT_MS = "maxResponseTimeoutMs"; private static final String KEY_MAX_RAS_TIMEOUT_MS = "maxRASTimeoutMs"; private static final long VAL_DEF_MAX_RAS_TIMEOUT_MS = 10000L; // max buffer queue size in KB @Deprecated private static final String KEY_DEF_BUFFERQUEUE_SIZE_KB = "maxBufferQueueSizeKb"; private static final String KEY_DEF_BUFFERQUEUE_SIZE_KBV2 = "proxy.def.buffer.queue.size.KB"; private static final int VAL_DEF_BUFFERQUEUE_SIZE_KB = 128 * 1024; // whether to retry after the message send failure @Deprecated private static final String KEY_ENABLE_SEND_RETRY_AFTER_FAILURE = "send.retry.after.failure"; private static final String KEY_ENABLE_SEND_RETRY_AFTER_FAILUREV2 = "msg.send.failure.retry.enable"; private static final boolean VAL_DEF_ENABLE_SEND_RETRY_AFTER_FAILURE = true; // max retry count private static final String KEY_MAX_RETRIES_AFTER_FAILURE = "max.retries.after.failure"; private static final String KEY_MAX_RETRIES_AFTER_FAILUREV2 = "msg.max.retries"; private static final int VAL_DEF_MAX_RETRIES_AFTER_FAILURE = -1; // whether to accept messages without mapping between groupId/streamId and topic private static final String KEY_ENABLE_UNCONFIGURED_TOPIC_ACCEPT = "id2topic.unconfigured.accept.enable"; private static final boolean VAL_DEF_ENABLE_UNCONFIGURED_TOPIC_ACCEPT = false; // default topics configure key, multiple topic settings are separated by "\\s+". private static final String KEY_UNCONFIGURED_TOPIC_DEFAULT_TOPICS = "id2topic.unconfigured.default.topics"; // whether enable whitelist, optional field. @Deprecated private static final String KEY_ENABLE_WHITELIST = "proxy.enable.whitelist"; private static final String KEY_ENABLE_WHITELISTV2 = "proxy.visit.whitelist.enable"; private static final boolean VAL_DEF_ENABLE_WHITELIST = false; // event handler private static final String KEY_EVENT_HANDLER = "eventHandler"; private static final String VAL_DEF_EVENT_HANDLER = DefaultEventHandler.class.getName(); // cache cluster selector @Deprecated private static final String KEY_CACHE_CLUSTER_SELECTOR = "cacheClusterSelector"; private static final String KEY_CACHE_CLUSTER_SELECTORV2 = "proxy.mq.cluster.selector"; private static final String VAL_DEF_CACHE_CLUSTER_SELECTOR = AllCacheClusterSelector.class.getName(); // **** allowed keys and default value, end // class instance private static CommonConfigHolder instance = null; private static volatile boolean isInit = false; private Map<String, String> props; // pre-read field values // node setting private String clusterTag = VAL_DEF_CLUSTER_TAG; private String clusterName = VAL_DEF_CLUSTER_NAME; private String clusterIncharges = VAL_DEF_CLUSTER_INCHARGES; private String clusterExtTag = VAL_DEF_CLUSTER_EXT_TAG; // manager setting private final List<String> managerIpList = new ArrayList<>(); private String managerAuthSecretId = ""; private String managerAuthSecretKey = ""; private boolean enableStartupUsingLocalMetaFile = VAL_DEF_ENABLE_STARTUP_USING_LOCAL_META_FILE; private long metaConfigSyncInvlMs = VAL_DEF_CONFIG_SYNC_INTERVAL_MS; private long metaConfigWastAlarmMs = VAL_DEF_META_CONFIG_SYNC_WAST_ALARM_MS; private boolean enableAudit = VAL_DEF_ENABLE_AUDIT; private boolean enableAuditProxysDiscoveryFromManager = VAL_DEF_AUDIT_PROXYS_DISCOVERY_MANAGER_ENABLE; private final HashSet<String> auditProxys = new HashSet<>(); private String auditFilePath = VAL_DEF_AUDIT_FILE_PATH; private int auditMaxCacheRows = VAL_DEF_AUDIT_MAX_CACHE_ROWS; private long auditFormatInvlMs = VAL_DEF_AUDIT_FORMAT_INTERVAL_MS; private boolean enableUnConfigTopicAccept = VAL_DEF_ENABLE_UNCONFIGURED_TOPIC_ACCEPT; private final List<String> defaultTopics = new ArrayList<>(); private boolean enableFileMetric = VAL_DEF_ENABLE_FILE_METRIC; private int fileMetricStatInvlSec = VAL_DEF_FILE_METRIC_STAT_INVL_SEC; private int fileMetricStatCacheCnt = VAL_DEF_FILE_METRIC_MAX_CACHE_CNT; private String fileMetricSourceOutName = VAL_DEF_FILE_METRIC_SOURCE_OUTPUT_NAME; private String fileMetricSinkOutName = VAL_DEF_FILE_METRIC_SINK_OUTPUT_NAME; private String fileMetricEventOutName = VAL_DEF_FILE_METRIC_EVENT_OUTPUT_NAME; private InlongCompressType defV1MsgCompressType = VAL_DEF_V1MSG_COMPRESS_TYPE; private boolean defV1MsgResponseBySink = VAL_DEF_V1MSG_RESPONSE_BY_SINK; private long maxResAfterSaveTimeout = VAL_DEF_MAX_RAS_TIMEOUT_MS; private boolean enableWhiteList = VAL_DEF_ENABLE_WHITELIST; private int defBufferQueueSizeKB = VAL_DEF_BUFFERQUEUE_SIZE_KB; private String eventHandler = VAL_DEF_EVENT_HANDLER; private String cacheClusterSelector = VAL_DEF_CACHE_CLUSTER_SELECTOR; private String proxyNodeId = VAL_DEF_PROXY_NODE_ID; private int prometheusHttpPort = VAL_DEF_PROMETHEUS_HTTP_PORT; private boolean sendRetryAfterFailure = VAL_DEF_ENABLE_SEND_RETRY_AFTER_FAILURE; private int maxRetriesAfterFailure = VAL_DEF_MAX_RETRIES_AFTER_FAILURE; /** * get instance for common.properties config manager */ public static CommonConfigHolder getInstance() { if (isInit && instance != null) { return instance; } synchronized (CommonConfigHolder.class) { if (!isInit) { instance = new CommonConfigHolder(); if (instance.loadConfigFile()) { instance.preReadFields(); LOG.info("{} load and read result is: {}", COMMON_CONFIG_FILE_NAME, instance.toString()); } isInit = true; } } return instance; } /** * Get the original attribute map * * Notice: only the non-pre-read fields need to be searched from the attribute map, * the pre-read fields MUST be got according to the methods in the class. */ public Map<String, String> getProperties() { return this.props; } /** * getStringFromContext * * @param context * @param key * @param defaultValue * @return */ public static String getStringFromContext(Context context, String key, String defaultValue) { String value = context.getString(key); value = (value != null) ? value : getInstance().getProperties().getOrDefault(key, defaultValue); return value; } public String getClusterTag() { return clusterTag; } public String getClusterName() { return this.clusterName; } public String getClusterIncharges() { return clusterIncharges; } public String getClusterExtTag() { return clusterExtTag; } public long getMetaConfigSyncInvlMs() { return metaConfigSyncInvlMs; } public long getMetaConfigWastAlarmMs() { return metaConfigWastAlarmMs; } public boolean isEnableUnConfigTopicAccept() { return enableUnConfigTopicAccept; } public List<String> getDefTopics() { return defaultTopics; } public String getRandDefTopics() { if (defaultTopics.isEmpty()) { return null; } SecureRandom rand = new SecureRandom(); return defaultTopics.get(rand.nextInt(defaultTopics.size())); } public boolean isEnableWhiteList() { return this.enableWhiteList; } public List<String> getManagerHosts() { return this.managerIpList; } public String getManagerAuthSecretId() { return managerAuthSecretId; } public String getManagerAuthSecretKey() { return managerAuthSecretKey; } public boolean isEnableAudit() { return enableAudit; } public boolean isEnableAuditProxysDiscoveryFromManager() { return enableAuditProxysDiscoveryFromManager; } public boolean isEnableFileMetric() { return enableFileMetric; } public int getFileMetricStatInvlSec() { return fileMetricStatInvlSec; } public int getFileMetricStatCacheCnt() { return fileMetricStatCacheCnt; } public HashSet<String> getAuditProxys() { return auditProxys; } public String getAuditFilePath() { return auditFilePath; } public int getAuditMaxCacheRows() { return auditMaxCacheRows; } public long getAuditFormatInvlMs() { return auditFormatInvlMs; } public boolean isDefV1MsgResponseBySink() { return defV1MsgResponseBySink; } public long getMaxResAfterSaveTimeout() { return maxResAfterSaveTimeout; } public int getDefBufferQueueSizeKB() { return defBufferQueueSizeKB; } public boolean isEnableStartupUsingLocalMetaFile() { return enableStartupUsingLocalMetaFile; } public String getEventHandler() { return eventHandler; } public String getCacheClusterSelector() { return cacheClusterSelector; } public int getPrometheusHttpPort() { return prometheusHttpPort; } public String getProxyNodeId() { return proxyNodeId; } public InlongCompressType getDefV1MsgCompressType() { return defV1MsgCompressType; } public String getFileMetricSourceOutName() { return fileMetricSourceOutName; } public String getFileMetricSinkOutName() { return fileMetricSinkOutName; } public String getFileMetricEventOutName() { return fileMetricEventOutName; } public boolean isSendRetryAfterFailure() { return sendRetryAfterFailure; } public int getMaxRetriesAfterFailure() { return maxRetriesAfterFailure; } private void preReadFields() { String tmpValue; // read cluster tag tmpValue = this.props.get(KEY_PROXY_CLUSTER_TAG); if (StringUtils.isNotBlank(tmpValue)) { this.clusterTag = tmpValue.trim(); } // read cluster name tmpValue = this.props.get(KEY_PROXY_CLUSTER_NAME); if (StringUtils.isNotBlank(tmpValue)) { this.clusterName = tmpValue.trim(); } // read cluster incharges tmpValue = compatGetValue(this.props, KEY_PROXY_CLUSTER_INCHARGESV2, KEY_PROXY_CLUSTER_INCHARGES); if (StringUtils.isNotEmpty(tmpValue)) { this.clusterIncharges = tmpValue.trim(); } tmpValue = compatGetValue(this.props, KEY_PROXY_CLUSTER_EXT_TAGV2, KEY_PROXY_CLUSTER_EXT_TAG); if (StringUtils.isNotEmpty(tmpValue)) { this.clusterExtTag = tmpValue.trim(); } // read the manager setting this.preReadManagerSetting(); // read the configuration related to the default topics this.preReadDefTopicSetting(); // read enable whitelist tmpValue = compatGetValue(this.props, KEY_ENABLE_WHITELISTV2, KEY_ENABLE_WHITELIST); if (StringUtils.isNotBlank(tmpValue)) { this.enableWhiteList = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read max response after save timeout tmpValue = this.props.get(KEY_MAX_RAS_TIMEOUT_MS); if (StringUtils.isNotEmpty(tmpValue)) { this.maxResAfterSaveTimeout = NumberUtils.toLong(tmpValue.trim(), VAL_DEF_MAX_RAS_TIMEOUT_MS); } // read default buffer queue size tmpValue = compatGetValue(this.props, KEY_DEF_BUFFERQUEUE_SIZE_KBV2, KEY_DEF_BUFFERQUEUE_SIZE_KB); if (StringUtils.isNotEmpty(tmpValue)) { this.defBufferQueueSizeKB = NumberUtils.toInt( tmpValue.trim(), VAL_DEF_BUFFERQUEUE_SIZE_KB); } // read cache cluster selector tmpValue = compatGetValue(this.props, KEY_CACHE_CLUSTER_SELECTORV2, KEY_CACHE_CLUSTER_SELECTOR); if (StringUtils.isNotBlank(tmpValue)) { this.cacheClusterSelector = tmpValue.trim(); } // read event handler tmpValue = this.props.get(KEY_EVENT_HANDLER); if (StringUtils.isNotBlank(tmpValue)) { this.eventHandler = tmpValue.trim(); } // read proxy node id tmpValue = compatGetValue(this.props, KEY_PROXY_NODE_IDV2, KEY_PROXY_NODE_ID); if (StringUtils.isBlank(tmpValue)) { this.proxyNodeId = AddressUtils.getSelfHost(); } else { this.proxyNodeId = tmpValue.trim(); } // read prometheus Http Port tmpValue = compatGetValue(this.props, KEY_PROMETHEUS_HTTP_PORTV2, KEY_PROMETHEUS_HTTP_PORT); if (StringUtils.isNotBlank(tmpValue)) { this.prometheusHttpPort = NumberUtils.toInt( tmpValue.trim(), VAL_DEF_PROMETHEUS_HTTP_PORT); } // read whether retry send message after sent failure tmpValue = compatGetValue(this.props, KEY_ENABLE_SEND_RETRY_AFTER_FAILUREV2, KEY_ENABLE_SEND_RETRY_AFTER_FAILURE); if (StringUtils.isNotEmpty(tmpValue)) { this.sendRetryAfterFailure = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read max retry count tmpValue = compatGetValue(this.props, KEY_MAX_RETRIES_AFTER_FAILUREV2, KEY_MAX_RETRIES_AFTER_FAILURE); if (StringUtils.isNotBlank(tmpValue)) { int retries = NumberUtils.toInt( tmpValue.trim(), VAL_DEF_MAX_RETRIES_AFTER_FAILURE); if (retries >= 0) { this.maxRetriesAfterFailure = retries; } } // Pre-read the fields related to Audit this.preReadAuditSetting(); // Pre-read the fields related to File metric this.preReadMetricSetting(); // pre-read v1msg default setting this.preReadV1MsgSetting(); } private void preReadManagerSetting() { String tmpValue; // read manager hosts String managerHosts = this.props.get(KEY_MANAGER_HOSTS); if (StringUtils.isBlank(managerHosts)) { LOG.error("Value of {} is required in {}, exit!", KEY_MANAGER_HOSTS, COMMON_CONFIG_FILE_NAME); System.exit(2); } managerHosts = managerHosts.trim(); String[] hostPort; String[] hostPortList = managerHosts.split(VAL_CONFIG_ITEMS_SEPARATOR); for (String tmpItem : hostPortList) { if (StringUtils.isBlank(tmpItem)) { continue; } hostPort = tmpItem.split(KEY_MANAGER_HOST_PORT_SEPARATOR); if (hostPort.length != 2 || StringUtils.isBlank(hostPort[0]) || StringUtils.isBlank(hostPort[1])) { continue; } managerIpList.add(hostPort[0].trim() + KEY_MANAGER_HOST_PORT_SEPARATOR + hostPort[1].trim()); } if (managerIpList.isEmpty()) { LOG.error("Invalid value {} in configure item {}, exit!", managerHosts, KEY_MANAGER_HOSTS); System.exit(2); } // read manager auth secret id tmpValue = compatGetValue(this.props, KEY_MANAGER_AUTH_SECRET_IDV2, KEY_MANAGER_AUTH_SECRET_ID); if (StringUtils.isNotBlank(tmpValue)) { this.managerAuthSecretId = tmpValue.trim(); } // read manager auth secret key tmpValue = compatGetValue(this.props, KEY_MANAGER_AUTH_SECRET_KEYV2, KEY_MANAGER_AUTH_SECRET_KEY); if (StringUtils.isNotBlank(tmpValue)) { this.managerAuthSecretKey = tmpValue.trim(); } // read enable startup using local meta file tmpValue = compatGetValue(this.props, KEY_ENABLE_STARTUP_USING_LOCAL_META_FILEV2, KEY_ENABLE_STARTUP_USING_LOCAL_META_FILE); if (StringUtils.isNotEmpty(tmpValue)) { this.enableStartupUsingLocalMetaFile = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read configure sync interval tmpValue = compatGetValue(this.props, KEY_META_CONFIG_SYNC_INTERVAL_MS, KEY_CONFIG_CHECK_INTERVAL_MS); if (StringUtils.isNotEmpty(tmpValue)) { long tmpSyncInvMs = NumberUtils.toLong( tmpValue.trim(), VAL_DEF_CONFIG_SYNC_INTERVAL_MS); if (tmpSyncInvMs >= VAL_MIN_CONFIG_SYNC_INTERVAL_MS) { this.metaConfigSyncInvlMs = tmpSyncInvMs; } } // read configure sync wast alarm ms tmpValue = this.props.get(KEY_META_CONFIG_SYNC_WAST_ALARM_MS); if (StringUtils.isNotBlank(tmpValue)) { this.metaConfigWastAlarmMs = NumberUtils.toLong( tmpValue.trim(), VAL_DEF_META_CONFIG_SYNC_WAST_ALARM_MS); } } private void preReadDefTopicSetting() { String tmpValue; // read whether accept msg without id2topic configure tmpValue = this.props.get(KEY_ENABLE_UNCONFIGURED_TOPIC_ACCEPT); if (StringUtils.isNotEmpty(tmpValue)) { this.enableUnConfigTopicAccept = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read default topics tmpValue = this.props.get(KEY_UNCONFIGURED_TOPIC_DEFAULT_TOPICS); if (StringUtils.isNotBlank(tmpValue)) { String[] topicItems = tmpValue.split(VAL_CONFIG_ITEMS_SEPARATOR); for (String item : topicItems) { if (StringUtils.isBlank(item)) { continue; } this.defaultTopics.add(item.trim()); } LOG.info("Configured {}, size is {}, value is {}", KEY_UNCONFIGURED_TOPIC_DEFAULT_TOPICS, defaultTopics.size(), defaultTopics); } // check whether configure default topics if (this.enableUnConfigTopicAccept && this.defaultTopics.isEmpty()) { LOG.error("Required {} field value is blank in {} for {} is true, exit!", KEY_UNCONFIGURED_TOPIC_DEFAULT_TOPICS, COMMON_CONFIG_FILE_NAME, KEY_ENABLE_UNCONFIGURED_TOPIC_ACCEPT); System.exit(2); } } private void preReadMetricSetting() { String tmpValue; // read whether enable file metric tmpValue = this.props.get(KEY_ENABLE_FILE_METRIC); if (StringUtils.isNotEmpty(tmpValue)) { this.enableFileMetric = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read file metric statistic interval tmpValue = this.props.get(KEY_FILE_METRIC_STAT_INTERVAL_SEC); if (StringUtils.isNotEmpty(tmpValue)) { int statInvl = NumberUtils.toInt( tmpValue.trim(), VAL_DEF_FILE_METRIC_STAT_INVL_SEC); if (statInvl >= VAL_MIN_FILE_METRIC_STAT_INVL_SEC) { this.fileMetricStatInvlSec = statInvl; } } // read file metric statistic max cache count tmpValue = this.props.get(KEY_FILE_METRIC_MAX_CACHE_CNT); if (StringUtils.isNotEmpty(tmpValue)) { int maxCacheCnt = NumberUtils.toInt( tmpValue.trim(), VAL_DEF_FILE_METRIC_MAX_CACHE_CNT); if (maxCacheCnt >= VAL_MIN_FILE_METRIC_MAX_CACHE_CNT) { this.fileMetricStatCacheCnt = maxCacheCnt; } } // read source file statistic output name tmpValue = this.props.get(KEY_FILE_METRIC_SOURCE_OUTPUT_NAME); if (StringUtils.isNotBlank(tmpValue)) { this.fileMetricSourceOutName = tmpValue.trim(); } // read sink file statistic output name tmpValue = this.props.get(KEY_FILE_METRIC_SINK_OUTPUT_NAME); if (StringUtils.isNotBlank(tmpValue)) { this.fileMetricSinkOutName = tmpValue.trim(); } // read event file statistic output name tmpValue = this.props.get(KEY_FILE_METRIC_EVENT_OUTPUT_NAME); if (StringUtils.isNotBlank(tmpValue)) { this.fileMetricEventOutName = tmpValue.trim(); } } private void preReadAuditSetting() { String tmpValue; // read whether enable audit tmpValue = this.props.get(KEY_ENABLE_AUDIT); if (StringUtils.isNotEmpty(tmpValue)) { this.enableAudit = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read whether discovery audit proxys from manager tmpValue = this.props.get(KEY_AUDIT_PROXYS_DISCOVERY_MANAGER_ENABLE); if (StringUtils.isNotEmpty(tmpValue)) { this.enableAuditProxysDiscoveryFromManager = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read audit proxys tmpValue = this.props.get(KEY_AUDIT_PROXYS); if (StringUtils.isNotBlank(tmpValue)) { String[] ipPorts = tmpValue.split(VAL_CONFIG_ITEMS_SEPARATOR); for (String tmpIPPort : ipPorts) { if (StringUtils.isBlank(tmpIPPort)) { continue; } this.auditProxys.add(tmpIPPort.trim()); } } // check auditProxys configure if (this.enableAudit) { if (!this.enableAuditProxysDiscoveryFromManager && this.auditProxys.isEmpty()) { LOG.error("{}'s {} must be configured when {} is true and {} is false, exist!", COMMON_CONFIG_FILE_NAME, KEY_AUDIT_PROXYS, KEY_ENABLE_AUDIT, KEY_AUDIT_PROXYS_DISCOVERY_MANAGER_ENABLE); System.exit(2); } } // read audit file path tmpValue = compatGetValue(this.props, KEY_AUDIT_FILE_PATHV2, KEY_AUDIT_FILE_PATH); if (StringUtils.isNotBlank(tmpValue)) { this.auditFilePath = tmpValue.trim(); } // read audit max cache rows tmpValue = compatGetValue(this.props, KEY_AUDIT_MAX_CACHE_ROWSV2, KEY_AUDIT_MAX_CACHE_ROWS); if (StringUtils.isNotEmpty(tmpValue)) { this.auditMaxCacheRows = NumberUtils.toInt( tmpValue.trim(), VAL_DEF_AUDIT_MAX_CACHE_ROWS); } // read audit format interval tmpValue = compatGetValue(this.props, KEY_AUDIT_TIME_FORMAT_INTERVAL, KEY_AUDIT_FORMAT_INTERVAL_MS); if (StringUtils.isNotEmpty(tmpValue)) { this.auditFormatInvlMs = NumberUtils.toLong( tmpValue.trim(), VAL_DEF_AUDIT_FORMAT_INTERVAL_MS); } } private void preReadV1MsgSetting() { String tmpValue; // read whether response v1 message by sink tmpValue = compatGetValue(this.props, KEY_V1MSG_RESPONSE_BY_SINKV2, KEY_V1MSG_RESPONSE_BY_SINK); if (StringUtils.isNotEmpty(tmpValue)) { this.defV1MsgResponseBySink = "TRUE".equalsIgnoreCase(tmpValue.trim()); } // read v1 msg compress type tmpValue = compatGetValue(this.props, KEY_V1MSG_SENT_COMPRESS_TYPEV2, KEY_V1MSG_SENT_COMPRESS_TYPE); if (StringUtils.isNotBlank(tmpValue)) { InlongCompressType tmpCompType = InlongCompressType.forType(tmpValue.trim()); if (tmpCompType == InlongCompressType.UNKNOWN) { LOG.error("{}'s {}({}) must be in allowed range [{}], exist!", COMMON_CONFIG_FILE_NAME, KEY_V1MSG_SENT_COMPRESS_TYPEV2, tmpValue, InlongCompressType.allowedCompressTypes); System.exit(2); } this.defV1MsgCompressType = tmpCompType; } } private boolean loadConfigFile() { InputStream inStream = null; try { URL url = getClass().getClassLoader().getResource(COMMON_CONFIG_FILE_NAME); inStream = url != null ? url.openStream() : null; if (inStream == null) { LOG.error("Fail to open {} as the input stream is null, exit!", COMMON_CONFIG_FILE_NAME); System.exit(1); return false; } String strKey; String strVal; Properties tmpProps = new Properties(); tmpProps.load(inStream); props = new HashMap<>(tmpProps.size()); for (Map.Entry<Object, Object> entry : tmpProps.entrySet()) { if (entry == null || entry.getKey() == null || entry.getValue() == null) { continue; } strKey = (String) entry.getKey(); strVal = (String) entry.getValue(); if (StringUtils.isBlank(strKey) || StringUtils.isBlank(strVal)) { continue; } props.put(strKey.trim(), strVal.trim()); } LOG.info("Read success from {}, content is {}", COMMON_CONFIG_FILE_NAME, props); } catch (Throwable e) { LOG.error("Fail to load properties from {}, exit!", COMMON_CONFIG_FILE_NAME, e); System.exit(1); return false; } finally { if (null != inStream) { try { inStream.close(); } catch (IOException e) { LOG.error("Fail to InputStream.close() for file {}, exit!", COMMON_CONFIG_FILE_NAME, e); System.exit(1); } } } return true; } @Override public String toString() { return new ToStringBuilder(this) .append("props", props) .append("clusterTag", clusterTag) .append("clusterName", clusterName) .append("clusterIncharges", clusterIncharges) .append("clusterExtTag", clusterExtTag) .append("managerIpList", managerIpList) .append("managerAuthSecretId", managerAuthSecretId) .append("managerAuthSecretKey", managerAuthSecretKey) .append("enableStartupUsingLocalMetaFile", enableStartupUsingLocalMetaFile) .append("metaConfigSyncInvlMs", metaConfigSyncInvlMs) .append("metaConfigWastAlarmMs", metaConfigWastAlarmMs) .append("enableAudit", enableAudit) .append("enableAuditProxysDiscoveryFromManager", enableAuditProxysDiscoveryFromManager) .append("auditProxys", auditProxys) .append("auditFilePath", auditFilePath) .append("auditMaxCacheRows", auditMaxCacheRows) .append("auditFormatInvlMs", auditFormatInvlMs) .append("enableUnConfigTopicAccept", enableUnConfigTopicAccept) .append("defaultTopics", defaultTopics) .append("enableFileMetric", enableFileMetric) .append("fileMetricStatInvlSec", fileMetricStatInvlSec) .append("fileMetricStatCacheCnt", fileMetricStatCacheCnt) .append("fileMetricSourceOutName", fileMetricSourceOutName) .append("fileMetricSinkOutName", fileMetricSinkOutName) .append("fileMetricEventOutName", fileMetricEventOutName) .append("defV1MsgCompressType", defV1MsgCompressType) .append("defV1MsgResponseBySink", defV1MsgResponseBySink) .append("maxResAfterSaveTimeout", maxResAfterSaveTimeout) .append("enableWhiteList", enableWhiteList) .append("defBufferQueueSizeKB", defBufferQueueSizeKB) .append("eventHandler", eventHandler) .append("cacheClusterSelector", cacheClusterSelector) .append("proxyNodeId", proxyNodeId) .append("prometheusHttpPort", prometheusHttpPort) .append("sendRetryAfterFailure", sendRetryAfterFailure) .append("maxRetriesAfterFailure", maxRetriesAfterFailure) .toString(); } private String compatGetValue(Map<String, String> attrs, String newKey, String depKey) { String tmpValue = attrs.get(newKey); if (StringUtils.isBlank(tmpValue)) { tmpValue = attrs.get(depKey); if (StringUtils.isNotEmpty(tmpValue)) { LOG.warn("** Deprecated configure key {}, replaced by {} **", depKey, newKey); } } return tmpValue; } }
apache/openjpa
36,812
openjpa-kernel/src/test/java/org/apache/openjpa/util/TestProxyManager.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.openjpa.util; import java.io.File; import java.io.InputStream; import java.lang.reflect.Method; import java.sql.Time; import java.sql.Timestamp; import java.util.AbstractMap; import java.util.AbstractSequentialList; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import org.apache.openjpa.lib.util.Files; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Test proxies generated by the proxy manager. * * @author Abe White */ public class TestProxyManager { private ProxyManagerImpl _mgr; @Before public void setUp() { _mgr = new ProxyManagerImpl(); } @Test public void testCopyLists() { List orig = new ArrayList(); populate(orig); assertListsEqual(orig, (List) _mgr.copyCollection(orig)); orig = new LinkedList(); populate(orig); assertListsEqual(orig, (List) _mgr.copyCollection(orig)); orig = new CustomList(); populate(orig); assertListsEqual(orig, (List) _mgr.copyCollection(orig)); } /** * Populate the given list with arbitrary data. */ private static void populate(Collection coll) { coll.add(1); coll.add("foo"); coll.add(99L); coll.add("bar"); coll.add((short) 50); } /** * Assert that the given lists are exactly the same. */ private static void assertListsEqual(List l1, List l2) { assertTrue(l1.getClass() == l2.getClass()); assertEquals(l1.size(), l2.size()); for (int i = 0; i < l1.size(); i++) assertTrue(l1.get(i) + " != " + l2.get(i), l1.get(i) == l2.get(i)); } @Test public void testCopySets() { Set orig = new HashSet(); populate(orig); assertSetsEqual(orig, (Set) _mgr.copyCollection(orig)); orig = new CustomSet(); populate(orig); assertSetsEqual(orig, (Set) _mgr.copyCollection(orig)); } /** * Assert that the given sets are exactly the same. */ private static void assertSetsEqual(Set s1, Set s2) { assertTrue(s1.getClass() == s2.getClass()); assertEquals(s1.size(), s2.size()); assertEquals(s1, s2); } @Test public void testCopySortedSets() { SortedSet orig = new TreeSet(); populate(orig); assertSortedSetsEqual(orig, (SortedSet) _mgr.copyCollection(orig)); orig = new TreeSet(new CustomComparator()); populate(orig); assertSortedSetsEqual(orig, (SortedSet) _mgr.copyCollection(orig)); orig = new CustomSortedSet(); populate(orig); assertSortedSetsEqual(orig, (SortedSet) _mgr.copyCollection(orig)); orig = new CustomComparatorSortedSet(new CustomComparator()); populate(orig); assertSortedSetsEqual(orig, (SortedSet) _mgr.copyCollection(orig)); } /** * Populate the given sorted set with arbitrary data. */ private static void populate(SortedSet coll) { coll.add(1); coll.add(99); coll.add(50); coll.add(-5); coll.add(10); } /** * Assert that the given sets are exactly the same. */ private static void assertSortedSetsEqual(SortedSet s1, SortedSet s2) { assertTrue(s1.getClass() == s2.getClass()); assertSortedSetsEquals(s1, s2); } /** * Assert that the given sets are exactly the same (minus the class). */ private static void assertSortedSetsEquals(SortedSet s1, SortedSet s2) { assertEquals(s1.comparator(), s2.comparator()); assertEquals(s1.size(), s2.size()); Iterator itr1 = s1.iterator(); Iterator itr2 = s2.iterator(); while (itr1.hasNext()) assertTrue(itr1.next() == itr2.next()); assertTrue(s1.equals(s2)); } @Test public void testCopyNullCollection() { assertNull(_mgr.copyCollection(null)); } @Test public void testCopyProxyCollection() { List orig = (List) _mgr.newCollectionProxy(ArrayList.class, null, null, true); populate(orig); assertListsEqual(new ArrayList(orig), (List) _mgr.copyCollection(orig)); TreeSet torig = (TreeSet) _mgr.newCollectionProxy(TreeSet.class, null, new CustomComparator(), true); assertTrue(torig.comparator() instanceof CustomComparator); populate(torig); assertSortedSetsEqual(new TreeSet(torig), (SortedSet) _mgr.copyCollection(torig)); } @Test public void testCloneProxyCollection() { // List doesn't support clone() TreeSet torig = (TreeSet) _mgr.newCollectionProxy(TreeSet.class, null, new CustomComparator(), true); assertTrue(torig.comparator() instanceof CustomComparator); populate(torig); assertSortedSetsEquals(new TreeSet(torig), (SortedSet) torig.clone()); } @Test public void testListMethodsProxied() throws Exception { Class proxy = _mgr.newCollectionProxy(ArrayList.class, null, null, true).getClass(); assertListMethodsProxied(proxy); proxy = _mgr.newCollectionProxy(CustomList.class, null, null, true).getClass(); assertListMethodsProxied(proxy); } /** * Assert that the methods we need to override to dirty the collection are proxied appropriately. */ private void assertCollectionMethodsProxied(Class cls) throws Exception { assertNotNull(cls.getDeclaredMethod("add", new Class[] { Object.class })); assertNotNull(cls.getDeclaredMethod("addAll", new Class[] { Collection.class })); assertNotNull(cls.getDeclaredMethod("clear", (Class[]) null)); assertNotNull(cls.getDeclaredMethod("iterator", (Class[]) null)); assertNotNull(cls.getDeclaredMethod("remove", new Class[] { Object.class })); assertNotNull(cls.getDeclaredMethod("removeAll", new Class[] { Collection.class })); assertNotNull(cls.getDeclaredMethod("retainAll", new Class[] { Collection.class })); // check a non-mutating method to make sure we're not just proxying // everything try { cls.getDeclaredMethod("contains", new Class[] { Object.class }); fail("Proxied non-mutating method."); } catch (NoSuchMethodException nsme) { // expected } } /** * Assert that the methods we need to override to dirty the list are proxied appropriately. */ private void assertListMethodsProxied(Class cls) throws Exception { assertCollectionMethodsProxied(cls); assertNotNull(cls.getDeclaredMethod("add", new Class[] { int.class, Object.class })); assertNotNull(cls.getDeclaredMethod("addAll", new Class[] { int.class, Collection.class })); assertNotNull(cls.getDeclaredMethod("listIterator", (Class[]) null)); assertNotNull(cls.getDeclaredMethod("listIterator", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("remove", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("set", new Class[] { int.class, Object.class })); } @Test public void testSetMethodsProxied() throws Exception { Class proxy = _mgr.newCollectionProxy(HashSet.class, null, null, true).getClass(); assertCollectionMethodsProxied(proxy); proxy = _mgr.newCollectionProxy(CustomSet.class, null, null, true).getClass(); assertCollectionMethodsProxied(proxy); proxy = _mgr.newCollectionProxy(CustomSortedSet.class, null, null, true).getClass(); assertCollectionMethodsProxied(proxy); proxy = _mgr.newCollectionProxy(CustomComparatorSortedSet.class, null, new CustomComparator(), true).getClass(); assertCollectionMethodsProxied(proxy); } @Test public void testQueueMethodsProxied() throws Exception { Class queue = getQueueClass(); if (queue == null) return; Class proxy = _mgr.newCollectionProxy(LinkedList.class, null, null, true).getClass(); assertTrue(queue.isAssignableFrom(proxy)); assertCollectionMethodsProxied(proxy); assertNotNull(proxy.getDeclaredMethod("offer", new Class[] { Object.class })); assertNotNull(proxy.getDeclaredMethod("poll", (Class[]) null)); assertNotNull(proxy.getDeclaredMethod("remove", (Class[]) null)); try { proxy.getDeclaredMethod("peek", (Class[]) null); fail("Proxied non-mutating method."); } catch (NoSuchMethodException nsme) { // expected } } @Test public void testLinkedListMethodsProxied() throws Exception { Class proxy = _mgr.newCollectionProxy(LinkedList.class, null, null, true).getClass(); assertListMethodsProxied(proxy); assertNotNull(proxy.getDeclaredMethod("addFirst", new Class[] { Object.class })); assertNotNull(proxy.getDeclaredMethod("addLast", new Class[] { Object.class })); assertNotNull(proxy.getDeclaredMethod("removeFirst", (Class[]) null)); assertNotNull(proxy.getDeclaredMethod("removeLast", (Class[]) null)); } @Test public void testVectorMethodsProxied() throws Exception { Class proxy = _mgr.newCollectionProxy(Vector.class, null, null, true).getClass(); assertListMethodsProxied(proxy); assertNotNull(proxy.getDeclaredMethod("addElement", new Class[] { Object.class })); assertNotNull(proxy.getDeclaredMethod("insertElementAt", new Class[] { Object.class, int.class })); assertNotNull(proxy.getDeclaredMethod("removeAllElements", (Class[]) null)); assertNotNull(proxy.getDeclaredMethod("removeElement", new Class[] { Object.class })); assertNotNull(proxy.getDeclaredMethod("removeElementAt", new Class[] { int.class })); assertNotNull(proxy.getDeclaredMethod("setElementAt", new Class[] { Object.class, int.class })); } @Test public void testListChangeTracker() { Proxy coll = _mgr.newCollectionProxy(ArrayList.class, null, null, true); assertNotNull(coll); assertNotNull(coll.getChangeTracker()); assertTrue(coll.getChangeTracker() instanceof CollectionChangeTrackerImpl); CollectionChangeTrackerImpl ct = (CollectionChangeTrackerImpl) coll.getChangeTracker(); assertTrue(ct.allowsDuplicates()); assertTrue(ct.isOrdered()); } @Test public void testSetChangeTracker() { Proxy coll = _mgr.newCollectionProxy(HashSet.class, null, null, true); assertNotNull(coll); assertNotNull(coll.getChangeTracker()); assertTrue(coll.getChangeTracker() instanceof CollectionChangeTrackerImpl); CollectionChangeTrackerImpl ct = (CollectionChangeTrackerImpl) coll.getChangeTracker(); assertFalse(ct.allowsDuplicates()); assertFalse(ct.isOrdered()); } @Test public void testCollectionInterfaceProxy() { Proxy coll = _mgr.newCollectionProxy(Collection.class, null, null, true); assertNotNull(coll); } @Test public void testListInterfaceProxy() { Proxy coll = _mgr.newCollectionProxy(List.class, null, null, true); assertNotNull(coll); assertTrue(coll instanceof List); } @Test public void testSetInterfaceProxy() { Proxy coll = _mgr.newCollectionProxy(Set.class, null, null, true); assertNotNull(coll); assertTrue(coll instanceof Set); assertFalse(coll instanceof SortedSet); } @Test public void testSortedSetInterfaceProxy() { Proxy coll = _mgr.newCollectionProxy(SortedSet.class, null, null, true); assertNotNull(coll); assertTrue(coll instanceof SortedSet); } @Test public void testQueueInterfaceProxy() { Class queue = getQueueClass(); if (queue == null) return; Proxy coll = _mgr.newCollectionProxy(queue, null, null, true); assertNotNull(coll); assertTrue(queue.isInstance(coll)); } @Test public void testProxyCustomDefaultScopedType() throws Exception { // Use reflection to instantiate a type that isn't in the current package. Class<?> cls = Class.forName("org.apache.openjpa.util.custom.CustomProxyDefaultScopeType"); assertNotNull(cls); Method meth = cls.getMethod("instance", new Class[0]); assertNotNull(meth); meth.setAccessible(true); Object obj = meth.invoke(cls, new Object[0]); assertNotNull(obj); assertNull(_mgr.newCustomProxy(obj, true)); } @Test public void testProxyCustomDefaultScopedList() throws Exception { // Use reflection to instantiate a type that isn't in the current package. Class<?> cls = Class.forName("org.apache.openjpa.util.custom.CustomProxyDefaultScopeList"); assertNotNull(cls); Method meth = cls.getMethod("instance", new Class[0]); assertNotNull(meth); meth.setAccessible(true); Object obj = meth.invoke(cls, new Object[0]); assertNotNull(obj); assertNull(_mgr.newCustomProxy(obj, true)); } /** * Return the {@link java.util.Queue} class if avaialble. */ private static Class getQueueClass() { try { return Class.forName("java.util.Queue"); } catch (Throwable t) { return null; } } @Test public void testCopyMaps() { Map orig = new HashMap(); populate(orig); assertMapsEqual(orig, (Map) _mgr.copyMap(orig)); orig = new CustomMap(); populate(orig); assertMapsEqual(orig, (Map) _mgr.copyMap(orig)); Properties porig = new Properties(); porig.setProperty("foo", "bar"); porig.setProperty("bar", "biz"); porig.setProperty("biz", "baz"); assertMapsEqual(orig, (Map) _mgr.copyMap(orig)); } /** * Populate the given map with arbitrary data. */ private static void populate(Map map) { map.put(1, "1"); map.put(99, "99"); map.put(-2, "-2"); map.put(50, "50"); } /** * Assert that the given maps are exactly the same. */ private static void assertMapsEqual(Map m1, Map m2) { assertTrue(m1.getClass() == m2.getClass()); assertEquals(m1.size(), m2.size()); assertEquals(m1, m2); } @Test public void testCopySortedMaps() { SortedMap orig = new TreeMap(); populate(orig); assertSortedMapsEqual(orig, (SortedMap) _mgr.copyMap(orig)); orig = new TreeMap(new CustomComparator()); populate(orig); assertSortedMapsEqual(orig, (SortedMap) _mgr.copyMap(orig)); orig = new CustomSortedMap(); populate(orig); assertSortedMapsEqual(orig, (SortedMap) _mgr.copyMap(orig)); orig = new CustomComparatorSortedMap(new CustomComparator()); populate(orig); assertSortedMapsEqual(orig, (SortedMap) _mgr.copyMap(orig)); } /** * Assert that the given maps are exactly the same. */ private static void assertSortedMapsEqual(SortedMap m1, SortedMap m2) { assertTrue(m1.getClass() == m2.getClass()); assertSortedMapsEquals(m1, m2); } /** * Assert that the given maps are exactly the same (minus the class). */ private static void assertSortedMapsEquals(SortedMap m1, SortedMap m2) { assertEquals(m1.comparator(), m2.comparator()); assertEquals(m1.size(), m2.size()); Map.Entry entry1; Map.Entry entry2; Iterator itr1 = m1.entrySet().iterator(); Iterator itr2 = m2.entrySet().iterator(); while (itr1.hasNext()) { entry1 = (Map.Entry) itr1.next(); entry2 = (Map.Entry) itr2.next(); assertTrue(entry1.getKey() == entry2.getKey()); assertTrue(entry1.getValue() == entry2.getValue()); } assertTrue(m1.equals(m2)); } @Test public void testCopyNullMap() { assertNull(_mgr.copyMap(null)); } @Test public void testCopyProxyMap() { Map orig = (Map) _mgr.newMapProxy(HashMap.class, null, null, null, true); populate(orig); assertMapsEqual(new HashMap(orig), (Map) _mgr.copyMap(orig)); TreeMap torig = (TreeMap) _mgr.newMapProxy(TreeMap.class, null, null, new CustomComparator(), true); assertTrue(torig.comparator() instanceof CustomComparator); populate(torig); assertSortedMapsEqual(new TreeMap(torig), (SortedMap) _mgr.copyMap(torig)); } @Test public void testCloneProxyMap() { // Map does not support clone() TreeMap torig = (TreeMap) _mgr.newMapProxy(TreeMap.class, null, null, new CustomComparator(), true); assertTrue(torig.comparator() instanceof CustomComparator); populate(torig); assertSortedMapsEquals(new TreeMap(torig), (SortedMap) torig.clone()); } @Test public void testMapMethodsProxied() throws Exception { Class proxy = _mgr.newMapProxy(HashMap.class, null, null, null, true).getClass(); assertMapMethodsProxied(proxy); proxy = _mgr.newMapProxy(TreeMap.class, null, null, null, true).getClass(); assertMapMethodsProxied(proxy); proxy = _mgr.newMapProxy(TreeMap.class, null, null, new CustomComparator(), true).getClass(); assertMapMethodsProxied(proxy); proxy = _mgr.newMapProxy(CustomMap.class, null, null, null, true).getClass(); assertMapMethodsProxied(proxy); proxy = _mgr.newMapProxy(CustomSortedMap.class, null, null, null, true).getClass(); assertMapMethodsProxied(proxy); proxy = _mgr.newMapProxy(CustomComparatorSortedMap.class, null, null, new CustomComparator(), true).getClass(); assertMapMethodsProxied(proxy); } /** * Assert that the methods we need to override to dirty the collection are proxied appropriately. */ private void assertMapMethodsProxied(Class cls) throws Exception { assertNotNull(cls.getDeclaredMethod("put", new Class[] { Object.class, Object.class })); assertNotNull(cls.getDeclaredMethod("putAll", new Class[] { Map.class })); assertNotNull(cls.getDeclaredMethod("clear", (Class[]) null)); assertNotNull(cls.getDeclaredMethod("remove", new Class[] { Object.class })); assertNotNull(cls.getDeclaredMethod("keySet", (Class[]) null)); assertNotNull(cls.getDeclaredMethod("values", (Class[]) null)); assertNotNull(cls.getDeclaredMethod("entrySet", (Class[]) null)); // check a non-mutating method to make sure we're not just proxying // everything try { cls.getDeclaredMethod("containsKey", new Class[] { Object.class }); fail("Proxied non-mutating method."); } catch (NoSuchMethodException nsme) { // expected } } @Test public void testPropertiesMethodsProxied() throws Exception { Class proxy = _mgr.newMapProxy(Properties.class, null, null, null, true).getClass(); assertMapMethodsProxied(proxy); assertNotNull(proxy.getDeclaredMethod("setProperty", new Class[] { String.class, String.class })); assertNotNull(proxy.getDeclaredMethod("load", new Class[] { InputStream.class })); assertNotNull(proxy.getDeclaredMethod("loadFromXML", new Class[] { InputStream.class })); } @Test public void testCopyDates() { Date orig = new Date(1999); assertDatesEqual(orig, (Date) _mgr.copyDate(orig)); orig = new java.sql.Date(1999); assertDatesEqual(orig, (Date) _mgr.copyDate(orig)); orig = new Time(1999); assertDatesEqual(orig, (Date) _mgr.copyDate(orig)); Timestamp torig = new Timestamp(1999); torig.setNanos(2001); assertDatesEqual(torig, (Date) _mgr.copyDate(torig)); torig = new CustomDate(1999); torig.setNanos(2001); assertDatesEqual(torig, (Date) _mgr.copyDate(torig)); } /** * Assert that the given dates are exactly the same. */ private static void assertDatesEqual(Date d1, Date d2) { assertTrue(d1.getClass() == d2.getClass()); assertDatesEquals(d1, d2); } /** * Assert that the given dates are exactly the same (minus the class). */ private static void assertDatesEquals(Date d1, Date d2) { assertTrue(d1.equals(d2)); } @Test public void testCopyNullDate() { assertNull(_mgr.copyDate(null)); } @Test public void testCopyProxyDate() { Date orig = (Date) _mgr.newDateProxy(Time.class); orig.setTime(1999); assertDatesEqual(new Time(orig.getTime()), (Date) _mgr.copyDate(orig)); } @Test public void testCloneProxyDate() { Date orig = (Date) _mgr.newDateProxy(Time.class); orig.setTime(1999); assertDatesEquals(new Time(orig.getTime()), (Date) orig.clone()); } @Test public void testDateMethodsProxied() throws Exception { Class proxy = _mgr.newDateProxy(Date.class).getClass(); assertDateMethodsProxied(proxy); proxy = _mgr.newDateProxy(java.sql.Date.class).getClass(); assertDateMethodsProxied(proxy); proxy = _mgr.newDateProxy(Time.class).getClass(); assertDateMethodsProxied(proxy); proxy = _mgr.newDateProxy(Timestamp.class).getClass(); assertTimestampMethodsProxied(proxy); proxy = _mgr.newDateProxy(CustomDate.class).getClass(); assertTimestampMethodsProxied(proxy); } /** * Assert that the methods we need to override to dirty the date are proxied appropriately. */ private void assertDateMethodsProxied(Class cls) throws Exception { assertNotNull(cls.getDeclaredMethod("setDate", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("setHours", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("setMinutes", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("setMonth", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("setSeconds", new Class[] { int.class })); assertNotNull(cls.getDeclaredMethod("setTime", new Class[] { long.class })); assertNotNull(cls.getDeclaredMethod("setYear", new Class[] { int.class })); // check a non-mutating method to make sure we're not just proxying // everything try { cls.getDeclaredMethod("getTime", (Class[]) null); fail("Proxied non-mutating method."); } catch (NoSuchMethodException nsme) { // expected } } /** * Assert that the methods we need to override to dirty the timestamp are proxied appropriately. */ private void assertTimestampMethodsProxied(Class cls) throws Exception { assertDateMethodsProxied(cls); assertNotNull(cls.getDeclaredMethod("setNanos", new Class[] { int.class })); } @Test public void testCopyCalendars() { Calendar orig = new GregorianCalendar(); populate(orig); assertCalendarsEqual(orig, _mgr.copyCalendar(orig)); orig = new CustomCalendar(); populate(orig); assertCalendarsEqual(orig, _mgr.copyCalendar(orig)); } /** * Populate calendar with arbitrary data. */ private static void populate(Calendar cal) { cal.setTimeInMillis(1999); cal.setTimeZone(TimeZone.getTimeZone("CST")); } /** * Assert that the given dates are exactly the same. */ private static void assertCalendarsEqual(Calendar c1, Calendar c2) { assertTrue(c1.getClass() == c2.getClass()); assertCalendarsEquals(c1, c2); } /** * Assert that the given dates are exactly the same (minus the class). */ private static void assertCalendarsEquals(Calendar c1, Calendar c2) { assertTrue(c1.equals(c2)); } @Test public void testCopyNullCalendar() { assertNull(_mgr.copyCalendar(null)); } @Test public void testCopyProxyCalendar() { Calendar orig = (Calendar) _mgr.newCalendarProxy(GregorianCalendar.class, TimeZone.getTimeZone("CST")); populate(orig); Calendar cal = new GregorianCalendar(); populate(cal); assertCalendarsEqual(cal, _mgr.copyCalendar(orig)); } @Test public void testCloneProxyCalendar() { Calendar orig = (Calendar) _mgr.newCalendarProxy(GregorianCalendar.class, TimeZone.getTimeZone("CST")); populate(orig); Calendar cal = new GregorianCalendar(); populate(cal); assertCalendarsEquals(cal, (Calendar) orig.clone()); } @Test public void testCalendarAbstractClassProxy() { Proxy cal = _mgr.newCalendarProxy(Calendar.class, null); assertNotNull(cal); } @Test public void testCalendarMethodsProxied() throws Exception { Class proxy = _mgr.newCalendarProxy(GregorianCalendar.class, TimeZone.getDefault()).getClass(); assertCalendarMethodsProxied(proxy); proxy = _mgr.newCalendarProxy(CustomCalendar.class, TimeZone.getDefault()).getClass(); assertCalendarMethodsProxied(proxy); proxy = _mgr.newCalendarProxy(Calendar.class, TimeZone.getDefault()).getClass(); assertCalendarMethodsProxied(proxy); } /** * Assert that the methods we need to override to dirty the calendar are proxied appropriately. */ private void assertCalendarMethodsProxied(Class cls) throws Exception { assertNotNull(cls.getDeclaredMethod("set", new Class[] { int.class, int.class })); assertNotNull(cls.getDeclaredMethod("roll", new Class[] { int.class, int.class })); assertNotNull(cls.getDeclaredMethod("setTimeInMillis", new Class[] { long.class })); assertNotNull(cls.getDeclaredMethod("setTimeZone", new Class[] { TimeZone.class })); assertNotNull(cls.getDeclaredMethod("computeFields", (Class[]) null)); // check a non-mutating method to make sure we're not just proxying // everything try { cls.getDeclaredMethod("getTimeInMillis", (Class[]) null); fail("Proxied non-mutating method."); } catch (NoSuchMethodException nsme) { // expected } } @Test public void testCopyBeans() { CustomBean orig = new CustomBean(); populate(orig); assertBeansEqual(orig, (CustomBean) _mgr.copyCustom(orig)); orig = new CustomCopyConstructorBean(orig); assertBeansEqual(orig, (CustomBean) _mgr.copyCustom(orig)); } //X @Test public void testBeanClassProxy() throws Exception { Class cls = CustomBean.class; final String proxyClassName = ProxyManagerImpl.getProxyClassName(cls, false); final byte[] bytes = _mgr.generateProxyBeanBytecode(cls, false, proxyClassName); File dir = Files.getClassFile(TestProxyManager.class).getParentFile(); final String fileName = cls.getName().replace('.', '$') + "$proxy" + ".class"; java.nio.file.Files.write(new File(dir, fileName).toPath(), bytes); _mgr.loadBuildTimeProxy(cls, this.getClass().getClassLoader()); } /** * Populate the given bean with arbitrary data. */ private void populate(CustomBean bean) { bean.setString("foo"); bean.setNumber(99); } @Test public void testNonproxyableBean() { NonproxyableBean orig = new NonproxyableBean(1); populate(orig); assertNull(_mgr.copyCustom(orig)); assertNull(_mgr.copyCustom(orig)); assertNull(_mgr.newCustomProxy(orig, true)); } @Test public void testIsUnproxyable() { CustomBean validBean = new CustomBean(); populate(validBean); assertNotNull(_mgr.copyCustom(validBean)); assertNotNull(_mgr.newCustomProxy(validBean, true)); assertFalse(_mgr.isUnproxyable(CustomBean.class)); NonproxyableBean bean1 = new NonproxyableBean(1); populate(bean1); NonproxyableBean2 bean2 = new NonproxyableBean2(); populate(bean2); assertFalse(_mgr.isUnproxyable(NonproxyableBean.class)); assertNull(_mgr.copyCustom(bean1)); assertTrue(_mgr.isUnproxyable(NonproxyableBean.class)); assertNull(_mgr.newCustomProxy(bean1, true)); assertTrue(_mgr.isUnproxyable(NonproxyableBean.class)); assertFalse(_mgr.isUnproxyable(NonproxyableBean2.class)); assertNull(_mgr.newCustomProxy(bean2, true)); assertTrue(_mgr.isUnproxyable(NonproxyableBean2.class)); assertNull(_mgr.copyCustom(bean2)); assertTrue(_mgr.isUnproxyable(NonproxyableBean2.class)); } /** * Assert that the given beans are exactly the same. */ private static void assertBeansEqual(CustomBean b1, CustomBean b2) { assertTrue(b1.getClass() == b2.getClass()); assertTrue(b1.getString() == b2.getString()); assertTrue(b1.getNumber() == b2.getNumber()); } @Test public void testCopyNullBean() { assertNull(_mgr.copyCustom(null)); } @Test public void testCopyProxyBean() { CustomBean orig = (CustomBean) _mgr.newCustomProxy(new CustomBean(), true); populate(orig); CustomBean comp = new CustomBean(); populate(comp); assertBeansEqual(comp, (CustomBean) _mgr.copyCustom(orig)); } @Test public void testBeanMethodsProxied() throws Exception { Class proxy = _mgr.newCustomProxy(new CustomBean(), true).getClass(); assertBeanMethodsProxied(proxy); proxy = _mgr.newCustomProxy(new CustomCopyConstructorBean(new CustomBean()), true).getClass(); assertBeanMethodsProxied(proxy); } /** * Assert that the methods we need to override to dirty the bean are proxied appropriately. */ private void assertBeanMethodsProxied(Class cls) throws Exception { assertNotNull(cls.getDeclaredMethod("setString", new Class[] { String.class })); assertNotNull(cls.getDeclaredMethod("setNumber", new Class[] { int.class })); // check a non-mutating method to make sure we're not just proxying // everything try { cls.getDeclaredMethod("getString", (Class[]) null); fail("Proxied non-mutating method."); } catch (NoSuchMethodException nsme) { // expected } } /** * Used to test custom list handling. Copy constructor intentionally ommitted. */ public static class CustomList extends AbstractSequentialList { private final List _delegate = new ArrayList(); @Override public int size() { return _delegate.size(); } @Override public ListIterator listIterator(int idx) { return _delegate.listIterator(idx); } } /** * Used to test custom set handling. Copy constructor intentionally ommitted. */ public static class CustomSet extends AbstractSet { private final Set _delegate = new HashSet(); @Override public int size() { return _delegate.size(); } @Override public Iterator iterator() { return _delegate.iterator(); } @Override public boolean add(Object o) { return _delegate.add(o); } } /** * Used to test custom set handling. Copy constructor intentionally ommitted. */ public static class CustomSortedSet extends TreeSet { private static final long serialVersionUID = 1L; } /** * Used to test custom set handling. Copy constructor intentionally ommitted. */ public static class CustomComparatorSortedSet extends TreeSet { private static final long serialVersionUID = 1L; public CustomComparatorSortedSet() { } public CustomComparatorSortedSet(Comparator comp) { super(comp); } } /** * Used to test custom map handling. Copy constructor intentionally ommitted. */ public static class CustomMap extends AbstractMap { private final Map _delegate = new HashMap(); @Override public Object put(Object key, Object value) { return _delegate.put(key, value); } @Override public Set entrySet() { return _delegate.entrySet(); } } /** * Used to test custom map handling. Copy constructor intentionally ommitted. */ public static class CustomSortedMap extends TreeMap { private static final long serialVersionUID = 1L; } /** * Used to test custom map handling. Copy constructor intentionally ommitted. */ public static class CustomComparatorSortedMap extends TreeMap { private static final long serialVersionUID = 1L; public CustomComparatorSortedMap() { } public CustomComparatorSortedMap(Comparator comp) { super(comp); } } /** * Used to test transfer of comparators to proxies. */ private static class CustomComparator implements Comparator { @Override public int compare(Object o1, Object o2) { return ((Comparable) o1).compareTo(o2); } } /** * Used to test custom date handling. */ public static class CustomDate extends Timestamp { private static final long serialVersionUID = 1L; public CustomDate(long time) { super(time); } } /** * Used to test custom bean handling. */ public static class CustomBean { private String _string; private int _number; private double d1; private double d2; public String getString() { return _string; } public void setString(String str) { _string = str; } public int getNumber() { return _number; } public void setNumber(int number) { _number = number; } public void setLocation(double d1, double d2) { this.d1 = d1; this.d2 = d2; } public double getD1() { return d1; } public double getD2() { return d2; } } /** * Used to test custom bean handling. */ public static class CustomCopyConstructorBean extends CustomBean { public CustomCopyConstructorBean(CustomBean bean) { setString(bean.getString()); setNumber(bean.getNumber()); } } /** * Used to non-proxyable custom bean handling. */ public static class NonproxyableBean extends CustomBean { public NonproxyableBean(long x) { // single non-default, non-copy constructor } } /** * Used to non-proxyable custom bean handling. */ public class NonproxyableBean2 extends CustomBean { // class is not static } /** * Used to test custom calendar handling. */ public static class CustomCalendar extends GregorianCalendar { private static final long serialVersionUID = 1L; } }
apache/tomcat
37,020
java/org/apache/coyote/AbstractProcessor.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.coyote; import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletConnection; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.parser.Host; import org.apache.tomcat.util.log.UserDataHelper; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.DispatchType; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SocketEvent; import org.apache.tomcat.util.net.SocketWrapperBase; import org.apache.tomcat.util.res.StringManager; /** * Provides functionality and attributes common to all supported protocols (currently HTTP and AJP) for processing a * single request/response. */ public abstract class AbstractProcessor extends AbstractProcessorLight implements ActionHook { private static final StringManager sm = StringManager.getManager(AbstractProcessor.class); // Used to avoid useless B2C conversion on the host name. private char[] hostNameC = new char[0]; protected final Adapter adapter; protected final AsyncStateMachine asyncStateMachine; private volatile long asyncTimeout = -1; /* * Tracks the current async generation when a timeout is dispatched. In the time it takes for a container thread to * be allocated and the timeout processing to start, it is possible that the application completes this generation * of async processing and starts a new one. If the timeout is then processed against the new generation, response * mix-up can occur. This field is used to ensure that any timeout event processed is for the current async * generation. This prevents the response mix-up. */ private volatile long asyncTimeoutGeneration = 0; protected final Request request; protected final Response response; protected volatile SocketWrapperBase<?> socketWrapper = null; protected volatile SSLSupport sslSupport; /** * Error state for the request/response currently being processed. */ private ErrorState errorState = ErrorState.NONE; protected final UserDataHelper userDataHelper; public AbstractProcessor(Adapter adapter) { this(adapter, new Request(), new Response()); } protected AbstractProcessor(Adapter adapter, Request coyoteRequest, Response coyoteResponse) { this.adapter = adapter; asyncStateMachine = new AsyncStateMachine(this); request = coyoteRequest; response = coyoteResponse; response.setHook(this); request.setResponse(response); request.setHook(this); userDataHelper = new UserDataHelper(getLog()); } /** * Update the current error state to the new error state if the new error state is more severe than the current * error state. * * @param errorState The error status details * @param t The error which occurred */ protected void setErrorState(ErrorState errorState, Throwable t) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("abstractProcessor.setErrorState", errorState), t); } // Use the return value to avoid processing more than one async error // in a single async cycle. response.setError(); boolean blockIo = this.errorState.isIoAllowed() && !errorState.isIoAllowed(); this.errorState = this.errorState.getMostSevere(errorState); // Don't change the status code for IOException since that is almost // certainly a client disconnect in which case it is preferable to keep // the original status code http://markmail.org/message/4cxpwmxhtgnrwh7n if (response.getStatus() < 400 && !(t instanceof IOException)) { response.setStatus(500); } if (t != null) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); } if (blockIo && isAsync()) { if (asyncStateMachine.asyncError()) { processSocketEvent(SocketEvent.ERROR, true); } } } protected ErrorState getErrorState() { return errorState; } @Override public Request getRequest() { return request; } /** * Get the associated adapter. * * @return the associated adapter */ public Adapter getAdapter() { return adapter; } /** * Set the socket wrapper being used. * * @param socketWrapper The socket wrapper */ protected void setSocketWrapper(SocketWrapperBase<?> socketWrapper) { this.socketWrapper = socketWrapper; } /** * @return the socket wrapper being used. */ protected final SocketWrapperBase<?> getSocketWrapper() { return socketWrapper; } @Override public final void setSslSupport(SSLSupport sslSupport) { this.sslSupport = sslSupport; } /** * Provides a mechanism to trigger processing on a container thread. * * @param runnable The task representing the processing that needs to take place on a container thread */ protected void execute(Runnable runnable) { SocketWrapperBase<?> socketWrapper = this.socketWrapper; if (socketWrapper == null) { throw new RejectedExecutionException(sm.getString("abstractProcessor.noExecute")); } else { socketWrapper.execute(runnable); } } @Override public boolean isAsync() { return asyncStateMachine.isAsync(); } @Override public SocketState asyncPostProcess() throws IOException { return asyncStateMachine.asyncPostProcess(); } @Override public final SocketState dispatch(SocketEvent status) throws IOException { if (status == SocketEvent.OPEN_WRITE && response.getWriteListener() != null) { asyncStateMachine.asyncOperation(); try { if (flushBufferedWrite()) { return SocketState.LONG; } } catch (IOException ioe) { if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("abstractProcessor.asyncFail"), ioe); } status = SocketEvent.ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); } } else if (status == SocketEvent.OPEN_READ && request.getReadListener() != null) { dispatchNonBlockingRead(); } else if (status == SocketEvent.ERROR) { // An I/O error occurred on a non-container thread. This includes: // - read/write timeouts fired by the Poller in NIO // - completion handler failures in NIO2 if (request.getAttribute(RequestDispatcher.ERROR_EXCEPTION) == null) { // Because the error did not occur on a container thread the // request's error attribute has not been set. If an exception // is available from the socketWrapper, use it to set the // request's error attribute here so it is visible to the error // handling. request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, socketWrapper.getError()); } if (request.getReadListener() != null || response.getWriteListener() != null) { // The error occurred during non-blocking I/O. Set the correct // state else the error handling will trigger an ISE. asyncStateMachine.asyncOperation(); } } RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(Constants.STAGE_SERVICE); if (!getAdapter().asyncDispatch(request, response, status)) { setErrorState(ErrorState.CLOSE_NOW, null); } } catch (InterruptedIOException e) { setErrorState(ErrorState.CLOSE_CONNECTION_NOW, e); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); setErrorState(ErrorState.CLOSE_NOW, t); getLog().error(sm.getString("http11processor.request.process"), t); } rp.setStage(Constants.STAGE_ENDED); SocketState state; if (getErrorState().isError()) { request.updateCounters(); state = SocketState.CLOSED; } else if (isAsync()) { state = SocketState.LONG; } else { request.updateCounters(); state = dispatchEndRequest(); } if (getLog().isTraceEnabled()) { getLog().trace("Socket: [" + socketWrapper + "], Status in: [" + status + "], State out: [" + state + "]"); } return state; } protected void parseHost(MessageBytes valueMB) { if (valueMB == null || valueMB.isNull()) { populateHost(); populatePort(); return; } else if (valueMB.getLength() == 0) { // Empty Host header so set sever name to empty string request.serverName().setString(""); populatePort(); return; } ByteChunk valueBC = valueMB.getByteChunk(); byte[] valueB = valueBC.getBytes(); int valueL = valueBC.getLength(); int valueS = valueBC.getStart(); if (hostNameC.length < valueL) { hostNameC = new char[valueL]; } try { // Validates the host name int colonPos = Host.parse(valueMB); // Extract the port information first, if any if (colonPos != -1) { int port = 0; for (int i = colonPos + 1; i < valueL; i++) { char c = (char) valueB[i + valueS]; if (c < '0' || c > '9') { response.setStatus(400); setErrorState(ErrorState.CLOSE_CLEAN, null); return; } port = port * 10 + c - '0'; } request.setServerPort(port); // Only need to copy the host name up to the : valueL = colonPos; } // Extract the host name for (int i = 0; i < valueL; i++) { hostNameC[i] = (char) valueB[i + valueS]; } request.serverName().setChars(hostNameC, 0, valueL); } catch (IllegalArgumentException e) { // IllegalArgumentException indicates that the host name is invalid UserDataHelper.Mode logMode = userDataHelper.getNextMode(); if (logMode != null) { String message = sm.getString("abstractProcessor.hostInvalid", valueMB.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("abstractProcessor.fallToDebug"); //$FALL-THROUGH$ case INFO: getLog().info(message, e); break; case DEBUG: getLog().debug(message, e); } } response.setStatus(400); setErrorState(ErrorState.CLOSE_CLEAN, e); } } /** * Called when a host header is not present in the request (e.g. HTTP/1.0). It populates the server name with * appropriate information. The source is expected to vary by protocol. * <p> * The default implementation is a NO-OP. */ protected void populateHost() { // NO-OP } /** * Called when a host header is not present or is empty in the request (e.g. HTTP/1.0). It populates the server port * with appropriate information. The source is expected to vary by protocol. * <p> * The default implementation is a NO-OP. */ protected void populatePort() { // NO-OP } @Override public final void action(ActionCode actionCode, Object param) { switch (actionCode) { // 'Normal' servlet support case COMMIT: { if (!response.isCommitted()) { try { // Validate and write response headers prepareResponse(); } catch (IOException ioe) { handleIOException(ioe); } } break; } case CLOSE: { action(ActionCode.COMMIT, null); try { finishResponse(); } catch (IOException ioe) { handleIOException(ioe); } break; } case ACK: { ack((ContinueResponseTiming) param); break; } case EARLY_HINTS: { try { earlyHints(); } catch (IOException ioe) { handleIOException(ioe); } break; } case CLIENT_FLUSH: { action(ActionCode.COMMIT, null); try { flush(); } catch (IOException ioe) { handleIOException(ioe); response.setErrorException(ioe); } break; } case AVAILABLE: { request.setAvailable(available(Boolean.TRUE.equals(param))); break; } case REQ_SET_BODY_REPLAY: { ByteChunk body = (ByteChunk) param; setRequestBody(body); break; } // Error handling case IS_ERROR: { ((AtomicBoolean) param).set(getErrorState().isError()); break; } case IS_IO_ALLOWED: { ((AtomicBoolean) param).set(getErrorState().isIoAllowed()); break; } case CLOSE_NOW: { // Prevent further writes to the response setSwallowResponse(); if (param instanceof Throwable) { setErrorState(ErrorState.CLOSE_NOW, (Throwable) param); } else { setErrorState(ErrorState.CLOSE_NOW, null); } break; } case DISABLE_SWALLOW_INPUT: { // Cancelled upload or similar. // No point reading the remainder of the request. disableSwallowRequest(); // This is an error state. Make sure it is marked as such. setErrorState(ErrorState.CLOSE_CLEAN, null); break; } // Request attribute support case REQ_HOST_ADDR_ATTRIBUTE: { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.remoteAddr().setString(socketWrapper.getRemoteAddr()); } break; } case REQ_PEER_ADDR_ATTRIBUTE: { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.peerAddr().setString(socketWrapper.getRemoteAddr()); } break; } case REQ_HOST_ATTRIBUTE: { populateRequestAttributeRemoteHost(); break; } case REQ_LOCALPORT_ATTRIBUTE: { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.setLocalPort(socketWrapper.getLocalPort()); } break; } case REQ_LOCAL_ADDR_ATTRIBUTE: { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.localAddr().setString(socketWrapper.getLocalAddr()); } break; } case REQ_LOCAL_NAME_ATTRIBUTE: { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.localName().setString(socketWrapper.getLocalName()); } break; } case REQ_REMOTEPORT_ATTRIBUTE: { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.setRemotePort(socketWrapper.getRemotePort()); } break; } // SSL request attribute support case REQ_SSL_ATTRIBUTE: { populateSslRequestAttributes(); break; } case REQ_SSL_CERTIFICATE: { try { sslReHandShake(); } catch (IOException ioe) { setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe); } break; } // Servlet 3.0 asynchronous support case ASYNC_START: { asyncStateMachine.asyncStart((AsyncContextCallback) param); break; } case ASYNC_COMPLETE: { clearDispatches(); if (asyncStateMachine.asyncComplete()) { processSocketEvent(SocketEvent.OPEN_READ, true); } break; } case ASYNC_DISPATCH: { if (asyncStateMachine.asyncDispatch()) { processSocketEvent(SocketEvent.OPEN_READ, true); } break; } case ASYNC_DISPATCHED: { asyncStateMachine.asyncDispatched(); break; } case ASYNC_ERROR: { asyncStateMachine.asyncError(); break; } case ASYNC_IS_ASYNC: { ((AtomicBoolean) param).set(asyncStateMachine.isAsync()); break; } case ASYNC_IS_COMPLETING: { ((AtomicBoolean) param).set(asyncStateMachine.isCompleting()); break; } case ASYNC_IS_DISPATCHING: { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching()); break; } case ASYNC_IS_ERROR: { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError()); break; } case ASYNC_IS_STARTED: { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted()); break; } case ASYNC_IS_TIMINGOUT: { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut()); break; } case ASYNC_RUN: { asyncStateMachine.asyncRun((Runnable) param); break; } case ASYNC_SETTIMEOUT: { if (param == null) { return; } long timeout = ((Long) param).longValue(); setAsyncTimeout(timeout); break; } case ASYNC_TIMEOUT: { AtomicBoolean result = (AtomicBoolean) param; result.set(asyncStateMachine.asyncTimeout()); break; } case ASYNC_POST_PROCESS: { try { asyncStateMachine.asyncPostProcess(); } catch (IOException ioe) { handleIOException(ioe); } break; } // Servlet 3.1 non-blocking I/O case REQUEST_BODY_FULLY_READ: { AtomicBoolean result = (AtomicBoolean) param; result.set(isRequestBodyFullyRead()); break; } case NB_READ_INTEREST: { AtomicBoolean isReady = (AtomicBoolean) param; isReady.set(isReadyForRead()); break; } case NB_WRITE_INTEREST: { AtomicBoolean isReady = (AtomicBoolean) param; isReady.set(isReadyForWrite()); break; } case DISPATCH_READ: { addDispatch(DispatchType.NON_BLOCKING_READ); break; } case DISPATCH_WRITE: { addDispatch(DispatchType.NON_BLOCKING_WRITE); break; } case DISPATCH_ERROR: { addDispatch(DispatchType.NON_BLOCKING_ERROR); break; } case DISPATCH_EXECUTE: { executeDispatches(); break; } // Servlet 3.1 HTTP Upgrade case UPGRADE: { doHttpUpgrade((UpgradeToken) param); break; } // Servlet 4.0 Trailers case IS_TRAILER_FIELDS_READY: { AtomicBoolean result = (AtomicBoolean) param; result.set(isTrailerFieldsReady()); break; } case IS_TRAILER_FIELDS_SUPPORTED: { AtomicBoolean result = (AtomicBoolean) param; result.set(isTrailerFieldsSupported()); break; } // Identifiers case PROTOCOL_REQUEST_ID: { @SuppressWarnings("unchecked") AtomicReference<Object> result = (AtomicReference<Object>) param; result.set(getProtocolRequestId()); break; } case SERVLET_CONNECTION: { @SuppressWarnings("unchecked") AtomicReference<Object> result = (AtomicReference<Object>) param; result.set(getServletConnection()); break; } } } private void handleIOException(IOException ioe) { if (ioe instanceof CloseNowException) { // Close the channel but keep the connection open setErrorState(ErrorState.CLOSE_NOW, ioe); } else { // Close the connection and all channels within that connection setErrorState(ErrorState.CLOSE_CONNECTION_NOW, ioe); } } /** * Perform any necessary processing for a non-blocking read before dispatching to the adapter. */ protected void dispatchNonBlockingRead() { asyncStateMachine.asyncOperation(); } /** * {@inheritDoc} * <p> * Subclasses of this base class represent a single request/response pair. The timeout to be processed is, * therefore, the Servlet asynchronous processing timeout. */ @Override public void timeoutAsync(long now) { if (now < 0) { doTimeoutAsync(); } else { long asyncTimeout = getAsyncTimeout(); if (asyncTimeout > 0) { long asyncStart = asyncStateMachine.getLastAsyncStart(); if ((now - asyncStart) > asyncTimeout) { doTimeoutAsync(); } } else if (!asyncStateMachine.isAvailable()) { // Timeout the async process if the associated web application // is no longer running. doTimeoutAsync(); } } } private void doTimeoutAsync() { // Avoid multiple timeouts setAsyncTimeout(-1); asyncTimeoutGeneration = asyncStateMachine.getCurrentGeneration(); processSocketEvent(SocketEvent.TIMEOUT, true); } @Override public boolean checkAsyncTimeoutGeneration() { return asyncTimeoutGeneration == asyncStateMachine.getCurrentGeneration(); } public void setAsyncTimeout(long timeout) { asyncTimeout = timeout; } public long getAsyncTimeout() { return asyncTimeout; } @Override public void recycle() { errorState = ErrorState.NONE; asyncStateMachine.recycle(); } /** * When committing the response, we have to validate the set of headers, as well as set up the response filters. * * @throws IOException IO exception during commit */ protected abstract void prepareResponse() throws IOException; /** * Finish the current response. * * @throws IOException IO exception during the write */ protected abstract void finishResponse() throws IOException; /** * Process acknowledgment of the request. * * @param continueResponseTiming specifies when an acknowledgment should be sent */ protected abstract void ack(ContinueResponseTiming continueResponseTiming); protected abstract void earlyHints() throws IOException; /** * Callback to write data from the buffer. * * @throws IOException IO exception during the write */ protected abstract void flush() throws IOException; /** * Queries if bytes are available in buffers. * * @param doRead {@code true} to perform a read when no bytes are availble * * @return the amount of bytes that are known to be available */ protected abstract int available(boolean doRead); /** * Set the specified byte chunk as the request body that will be read. This allows saving and processing requests. * * @param body the byte chunk containing all the request bytes */ protected abstract void setRequestBody(ByteChunk body); /** * The response is finished and no additional bytes need to be sent to the client. */ protected abstract void setSwallowResponse(); /** * Swallowing bytes is required for pipelining requests, so this allows to avoid doing extra operations in case an * error occurs and the connection is to be closed instead. */ protected abstract void disableSwallowRequest(); /** * Processors that populate request attributes directly (e.g. AJP) should over-ride this method and return * {@code false}. * * @return {@code true} if the SocketWrapper should be used to populate the request attributes, otherwise * {@code false}. */ protected boolean getPopulateRequestAttributesFromSocket() { return true; } /** * Populate the remote host request attribute. Processors (e.g. AJP) that populate this from an alternative source * should override this method. */ protected void populateRequestAttributeRemoteHost() { if (getPopulateRequestAttributesFromSocket() && socketWrapper != null) { request.remoteHost().setString(socketWrapper.getRemoteHost()); } } /** * Populate the TLS related request attributes from the {@link SSLSupport} instance associated with this processor. * Protocols that populate TLS attributes from a different source (e.g. AJP) should override this method. */ protected void populateSslRequestAttributes() { try { if (sslSupport != null) { Object sslO = sslSupport.getProtocol(); if (sslO != null) { request.setAttribute(SSLSupport.SECURE_PROTOCOL_KEY, sslO); } sslO = sslSupport.getCipherSuite(); if (sslO != null) { request.setAttribute(SSLSupport.CIPHER_SUITE_KEY, sslO); } sslO = sslSupport.getPeerCertificateChain(); if (sslO != null) { request.setAttribute(SSLSupport.CERTIFICATE_KEY, sslO); } sslO = sslSupport.getKeySize(); if (sslO != null) { request.setAttribute(SSLSupport.KEY_SIZE_KEY, sslO); } sslO = sslSupport.getSessionId(); if (sslO != null) { request.setAttribute(SSLSupport.SESSION_ID_KEY, sslO); } sslO = sslSupport.getRequestedProtocols(); if (sslO != null) { request.setAttribute(SSLSupport.REQUESTED_PROTOCOL_VERSIONS_KEY, sslO); } sslO = sslSupport.getRequestedCiphers(); if (sslO != null) { request.setAttribute(SSLSupport.REQUESTED_CIPHERS_KEY, sslO); } request.setAttribute(SSLSupport.SESSION_MGR, sslSupport); } } catch (Exception e) { getLog().warn(sm.getString("abstractProcessor.socket.ssl"), e); } } /** * Processors that can perform a TLS re-handshake (e.g. HTTP/1.1) should override this method and implement the * re-handshake. * * @throws IOException If authentication is required then there will be I/O with the client and this exception will * be thrown if that goes wrong */ protected void sslReHandShake() throws IOException { // NO-OP } protected void processSocketEvent(SocketEvent event, boolean dispatch) { SocketWrapperBase<?> socketWrapper = getSocketWrapper(); if (socketWrapper != null) { socketWrapper.processSocket(event, dispatch); } } protected boolean isReadyForRead() { if (available(true) > 0) { return true; } if (!isRequestBodyFullyRead()) { registerReadInterest(); } return false; } /** * @return {@code true} if it is known that the request body has been fully read */ protected abstract boolean isRequestBodyFullyRead(); /** * When using non blocking IO, register to get a callback when polling determines that bytes are available for * reading. */ protected abstract void registerReadInterest(); /** * @return {@code true} if bytes can be written without blocking */ protected abstract boolean isReadyForWrite(); protected void executeDispatches() { SocketWrapperBase<?> socketWrapper = getSocketWrapper(); Iterator<DispatchType> dispatches = getIteratorAndClearDispatches(); if (socketWrapper != null) { Lock lock = socketWrapper.getLock(); lock.lock(); try { /* * This method is called when non-blocking IO is initiated by defining a read and/or write listener in a * non-container thread. It is called once the non-container thread completes so that the first calls to * onWritePossible() and/or onDataAvailable() as appropriate are made by the container. * * Processing the dispatches requires (TODO confirm applies without APR) that the socket has been added * to the waitingRequests queue. This may not have occurred by the time that the non-container thread * completes triggering the call to this method. Therefore, the coded syncs on the SocketWrapper as the * container thread that initiated this non-container thread holds a lock on the SocketWrapper. The * container thread will add the socket to the waitingRequests queue before releasing the lock on the * socketWrapper. Therefore, by obtaining the lock on socketWrapper before processing the dispatches, we * can be sure that the socket has been added to the waitingRequests queue. */ while (dispatches != null && dispatches.hasNext()) { DispatchType dispatchType = dispatches.next(); socketWrapper.processSocket(dispatchType.getSocketStatus(), false); } } finally { lock.unlock(); } } } /** * {@inheritDoc} Processors that implement HTTP upgrade must override this method and provide the necessary token. */ @Override public UpgradeToken getUpgradeToken() { // Should never reach this code but in case we do... throw new IllegalStateException(sm.getString("abstractProcessor.httpupgrade.notsupported")); } /** * Process an HTTP upgrade. Processors that support HTTP upgrade should override this method and process the * provided token. * * @param upgradeToken Contains all the information necessary for the Processor to process the upgrade * * @throws UnsupportedOperationException if the protocol does not support HTTP upgrade */ protected void doHttpUpgrade(UpgradeToken upgradeToken) { // Should never happen throw new UnsupportedOperationException(sm.getString("abstractProcessor.httpupgrade.notsupported")); } /** * {@inheritDoc} Processors that implement HTTP upgrade must override this method. */ @Override public ByteBuffer getLeftoverInput() { // Should never reach this code but in case we do... throw new IllegalStateException(sm.getString("abstractProcessor.httpupgrade.notsupported")); } /** * {@inheritDoc} Processors that implement HTTP upgrade must override this method. */ @Override public boolean isUpgrade() { return false; } protected abstract boolean isTrailerFieldsReady(); /** * Protocols that support trailer fields should override this method and return {@code true}. * * @return {@code true} if trailer fields are supported by this processor, otherwise {@code false}. */ protected boolean isTrailerFieldsSupported() { return false; } /** * Protocols that provide per HTTP request IDs (e.g. Stream ID for HTTP/2) should override this method and return * the appropriate ID. * * @return The ID associated with this request or the empty string if no such ID is defined */ protected Object getProtocolRequestId() { return null; } /** * Protocols must override this method and return an appropriate ServletConnection instance * * @return the ServletConnection instance associated with the current request. */ protected abstract ServletConnection getServletConnection(); /** * Flush any pending writes. Used during non-blocking writes to flush any remaining data from a previous incomplete * write. * * @return <code>true</code> if data remains to be flushed at the end of method * * @throws IOException If an I/O error occurs while attempting to flush the data */ protected abstract boolean flushBufferedWrite() throws IOException; /** * Perform any necessary clean-up processing if the dispatch resulted in the completion of processing for the * current request. * * @return The state to return for the socket once the clean-up for the current request has completed * * @throws IOException If an I/O error occurs while attempting to end the request */ protected abstract SocketState dispatchEndRequest() throws IOException; @Override protected final void logAccess(SocketWrapperBase<?> socketWrapper) throws IOException { // Set the socket wrapper so the access log can read the socket related // information (e.g. client IP) setSocketWrapper(socketWrapper); // Set up the minimal request information request.markStartTime(); // Set up the minimal response information response.setStatus(400); response.setError(); getAdapter().log(request, response, 0); } }
googleapis/google-cloud-java
36,887
java-marketingplatformadminapi/proto-admin-v1alpha/src/main/java/com/google/ads/marketingplatform/admin/v1alpha/SetPropertyServiceLevelRequest.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/marketingplatform/admin/v1alpha/marketingplatform_admin.proto // Protobuf Java Version: 3.25.8 package com.google.ads.marketingplatform.admin.v1alpha; /** * * * <pre> * Request message for SetPropertyServiceLevel RPC. * </pre> * * Protobuf type {@code google.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest} */ public final class SetPropertyServiceLevelRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) SetPropertyServiceLevelRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SetPropertyServiceLevelRequest.newBuilder() to construct. private SetPropertyServiceLevelRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SetPropertyServiceLevelRequest() { analyticsAccountLink_ = ""; analyticsProperty_ = ""; serviceLevel_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SetPropertyServiceLevelRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminProto .internal_static_google_marketingplatform_admin_v1alpha_SetPropertyServiceLevelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminProto .internal_static_google_marketingplatform_admin_v1alpha_SetPropertyServiceLevelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest.class, com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest.Builder .class); } public static final int ANALYTICS_ACCOUNT_LINK_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object analyticsAccountLink_ = ""; /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The analyticsAccountLink. */ @java.lang.Override public java.lang.String getAnalyticsAccountLink() { java.lang.Object ref = analyticsAccountLink_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); analyticsAccountLink_ = s; return s; } } /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for analyticsAccountLink. */ @java.lang.Override public com.google.protobuf.ByteString getAnalyticsAccountLinkBytes() { java.lang.Object ref = analyticsAccountLink_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); analyticsAccountLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ANALYTICS_PROPERTY_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object analyticsProperty_ = ""; /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The analyticsProperty. */ @java.lang.Override public java.lang.String getAnalyticsProperty() { java.lang.Object ref = analyticsProperty_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); analyticsProperty_ = s; return s; } } /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for analyticsProperty. */ @java.lang.Override public com.google.protobuf.ByteString getAnalyticsPropertyBytes() { java.lang.Object ref = analyticsProperty_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); analyticsProperty_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICE_LEVEL_FIELD_NUMBER = 3; private int serviceLevel_ = 0; /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for serviceLevel. */ @java.lang.Override public int getServiceLevelValue() { return serviceLevel_; } /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The serviceLevel. */ @java.lang.Override public com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel getServiceLevel() { com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel result = com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel.forNumber( serviceLevel_); return result == null ? com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel.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(analyticsAccountLink_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, analyticsAccountLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(analyticsProperty_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, analyticsProperty_); } if (serviceLevel_ != com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel .ANALYTICS_SERVICE_LEVEL_UNSPECIFIED .getNumber()) { output.writeEnum(3, serviceLevel_); } 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(analyticsAccountLink_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, analyticsAccountLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(analyticsProperty_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, analyticsProperty_); } if (serviceLevel_ != com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel .ANALYTICS_SERVICE_LEVEL_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, serviceLevel_); } 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest)) { return super.equals(obj); } com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest other = (com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) obj; if (!getAnalyticsAccountLink().equals(other.getAnalyticsAccountLink())) return false; if (!getAnalyticsProperty().equals(other.getAnalyticsProperty())) return false; if (serviceLevel_ != other.serviceLevel_) 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) + ANALYTICS_ACCOUNT_LINK_FIELD_NUMBER; hash = (53 * hash) + getAnalyticsAccountLink().hashCode(); hash = (37 * hash) + ANALYTICS_PROPERTY_FIELD_NUMBER; hash = (53 * hash) + getAnalyticsProperty().hashCode(); hash = (37 * hash) + SERVICE_LEVEL_FIELD_NUMBER; hash = (53 * hash) + serviceLevel_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest 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 SetPropertyServiceLevel RPC. * </pre> * * Protobuf type {@code google.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminProto .internal_static_google_marketingplatform_admin_v1alpha_SetPropertyServiceLevelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminProto .internal_static_google_marketingplatform_admin_v1alpha_SetPropertyServiceLevelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest.class, com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest.Builder .class); } // Construct using // com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; analyticsAccountLink_ = ""; analyticsProperty_ = ""; serviceLevel_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminProto .internal_static_google_marketingplatform_admin_v1alpha_SetPropertyServiceLevelRequest_descriptor; } @java.lang.Override public com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest getDefaultInstanceForType() { return com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest .getDefaultInstance(); } @java.lang.Override public com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest build() { com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest buildPartial() { com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest result = new com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.analyticsAccountLink_ = analyticsAccountLink_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.analyticsProperty_ = analyticsProperty_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.serviceLevel_ = serviceLevel_; } } @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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) { return mergeFrom( (com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest other) { if (other == com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest .getDefaultInstance()) return this; if (!other.getAnalyticsAccountLink().isEmpty()) { analyticsAccountLink_ = other.analyticsAccountLink_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAnalyticsProperty().isEmpty()) { analyticsProperty_ = other.analyticsProperty_; bitField0_ |= 0x00000002; onChanged(); } if (other.serviceLevel_ != 0) { setServiceLevelValue(other.getServiceLevelValue()); } 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: { analyticsAccountLink_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { analyticsProperty_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { serviceLevel_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object analyticsAccountLink_ = ""; /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The analyticsAccountLink. */ public java.lang.String getAnalyticsAccountLink() { java.lang.Object ref = analyticsAccountLink_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); analyticsAccountLink_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for analyticsAccountLink. */ public com.google.protobuf.ByteString getAnalyticsAccountLinkBytes() { java.lang.Object ref = analyticsAccountLink_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); analyticsAccountLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The analyticsAccountLink to set. * @return This builder for chaining. */ public Builder setAnalyticsAccountLink(java.lang.String value) { if (value == null) { throw new NullPointerException(); } analyticsAccountLink_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearAnalyticsAccountLink() { analyticsAccountLink_ = getDefaultInstance().getAnalyticsAccountLink(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent AnalyticsAccountLink scope where this property is in. * Format: * organizations/{org_id}/analyticsAccountLinks/{analytics_account_link_id} * </pre> * * <code>string analytics_account_link = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for analyticsAccountLink to set. * @return This builder for chaining. */ public Builder setAnalyticsAccountLinkBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); analyticsAccountLink_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object analyticsProperty_ = ""; /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The analyticsProperty. */ public java.lang.String getAnalyticsProperty() { java.lang.Object ref = analyticsProperty_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); analyticsProperty_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for analyticsProperty. */ public com.google.protobuf.ByteString getAnalyticsPropertyBytes() { java.lang.Object ref = analyticsProperty_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); analyticsProperty_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The analyticsProperty to set. * @return This builder for chaining. */ public Builder setAnalyticsProperty(java.lang.String value) { if (value == null) { throw new NullPointerException(); } analyticsProperty_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearAnalyticsProperty() { analyticsProperty_ = getDefaultInstance().getAnalyticsProperty(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. The Analytics property to change the ServiceLevel setting. This * field is the name of the Google Analytics Admin API property resource. * * Format: analyticsadmin.googleapis.com/properties/{property_id} * </pre> * * <code> * string analytics_property = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for analyticsProperty to set. * @return This builder for chaining. */ public Builder setAnalyticsPropertyBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); analyticsProperty_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int serviceLevel_ = 0; /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for serviceLevel. */ @java.lang.Override public int getServiceLevelValue() { return serviceLevel_; } /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The enum numeric value on the wire for serviceLevel to set. * @return This builder for chaining. */ public Builder setServiceLevelValue(int value) { serviceLevel_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The serviceLevel. */ @java.lang.Override public com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel getServiceLevel() { com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel result = com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel.forNumber( serviceLevel_); return result == null ? com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel.UNRECOGNIZED : result; } /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The serviceLevel to set. * @return This builder for chaining. */ public Builder setServiceLevel( com.google.ads.marketingplatform.admin.v1alpha.AnalyticsServiceLevel value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; serviceLevel_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Required. The service level to set for this property. * </pre> * * <code> * .google.marketingplatform.admin.v1alpha.AnalyticsServiceLevel service_level = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearServiceLevel() { bitField0_ = (bitField0_ & ~0x00000004); serviceLevel_ = 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.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) } // @@protoc_insertion_point(class_scope:google.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest) private static final com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest(); } public static com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SetPropertyServiceLevelRequest> PARSER = new com.google.protobuf.AbstractParser<SetPropertyServiceLevelRequest>() { @java.lang.Override public SetPropertyServiceLevelRequest 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<SetPropertyServiceLevelRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SetPropertyServiceLevelRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.marketingplatform.admin.v1alpha.SetPropertyServiceLevelRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,836
java-kms/proto-google-cloud-kms-v1/src/main/java/com/google/cloud/kms/v1/CreateImportJobRequest.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/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.kms.v1; /** * * * <pre> * Request message for * [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. * </pre> * * Protobuf type {@code google.cloud.kms.v1.CreateImportJobRequest} */ public final class CreateImportJobRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.kms.v1.CreateImportJobRequest) CreateImportJobRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateImportJobRequest.newBuilder() to construct. private CreateImportJobRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateImportJobRequest() { parent_ = ""; importJobId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateImportJobRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.kms.v1.KmsProto .internal_static_google_cloud_kms_v1_CreateImportJobRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.kms.v1.KmsProto .internal_static_google_cloud_kms_v1_CreateImportJobRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.kms.v1.CreateImportJobRequest.class, com.google.cloud.kms.v1.CreateImportJobRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The [name][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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 IMPORT_JOB_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object importJobId_ = ""; /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The importJobId. */ @java.lang.Override public java.lang.String getImportJobId() { java.lang.Object ref = importJobId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); importJobId_ = s; return s; } } /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for importJobId. */ @java.lang.Override public com.google.protobuf.ByteString getImportJobIdBytes() { java.lang.Object ref = importJobId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); importJobId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IMPORT_JOB_FIELD_NUMBER = 3; private com.google.cloud.kms.v1.ImportJob importJob_; /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code>.google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the importJob field is set. */ @java.lang.Override public boolean hasImportJob() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code>.google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The importJob. */ @java.lang.Override public com.google.cloud.kms.v1.ImportJob getImportJob() { return importJob_ == null ? com.google.cloud.kms.v1.ImportJob.getDefaultInstance() : importJob_; } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code>.google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.kms.v1.ImportJobOrBuilder getImportJobOrBuilder() { return importJob_ == null ? com.google.cloud.kms.v1.ImportJob.getDefaultInstance() : importJob_; } 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(importJobId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, importJobId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getImportJob()); } 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(importJobId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, importJobId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getImportJob()); } 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.CreateImportJobRequest)) { return super.equals(obj); } com.google.cloud.kms.v1.CreateImportJobRequest other = (com.google.cloud.kms.v1.CreateImportJobRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getImportJobId().equals(other.getImportJobId())) return false; if (hasImportJob() != other.hasImportJob()) return false; if (hasImportJob()) { if (!getImportJob().equals(other.getImportJob())) 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) + IMPORT_JOB_ID_FIELD_NUMBER; hash = (53 * hash) + getImportJobId().hashCode(); if (hasImportJob()) { hash = (37 * hash) + IMPORT_JOB_FIELD_NUMBER; hash = (53 * hash) + getImportJob().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.kms.v1.CreateImportJobRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.kms.v1.CreateImportJobRequest 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.CreateImportJobRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.kms.v1.CreateImportJobRequest 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.CreateImportJobRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.kms.v1.CreateImportJobRequest 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.CreateImportJobRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.kms.v1.CreateImportJobRequest 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.CreateImportJobRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.kms.v1.CreateImportJobRequest 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.CreateImportJobRequest 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.CreateImportJobRequest 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.CreateImportJobRequest 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 * [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. * </pre> * * Protobuf type {@code google.cloud.kms.v1.CreateImportJobRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.kms.v1.CreateImportJobRequest) com.google.cloud.kms.v1.CreateImportJobRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.kms.v1.KmsProto .internal_static_google_cloud_kms_v1_CreateImportJobRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.kms.v1.KmsProto .internal_static_google_cloud_kms_v1_CreateImportJobRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.kms.v1.CreateImportJobRequest.class, com.google.cloud.kms.v1.CreateImportJobRequest.Builder.class); } // Construct using com.google.cloud.kms.v1.CreateImportJobRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getImportJobFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; importJobId_ = ""; importJob_ = null; if (importJobBuilder_ != null) { importJobBuilder_.dispose(); importJobBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.kms.v1.KmsProto .internal_static_google_cloud_kms_v1_CreateImportJobRequest_descriptor; } @java.lang.Override public com.google.cloud.kms.v1.CreateImportJobRequest getDefaultInstanceForType() { return com.google.cloud.kms.v1.CreateImportJobRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.kms.v1.CreateImportJobRequest build() { com.google.cloud.kms.v1.CreateImportJobRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.kms.v1.CreateImportJobRequest buildPartial() { com.google.cloud.kms.v1.CreateImportJobRequest result = new com.google.cloud.kms.v1.CreateImportJobRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.kms.v1.CreateImportJobRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.importJobId_ = importJobId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.importJob_ = importJobBuilder_ == null ? importJob_ : importJobBuilder_.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.kms.v1.CreateImportJobRequest) { return mergeFrom((com.google.cloud.kms.v1.CreateImportJobRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.kms.v1.CreateImportJobRequest other) { if (other == com.google.cloud.kms.v1.CreateImportJobRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getImportJobId().isEmpty()) { importJobId_ = other.importJobId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasImportJob()) { mergeImportJob(other.getImportJob()); } 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: { importJobId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getImportJobFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The [name][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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][google.cloud.kms.v1.KeyRing.name] of the * [KeyRing][google.cloud.kms.v1.KeyRing] associated with the * [ImportJobs][google.cloud.kms.v1.ImportJob]. * </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 importJobId_ = ""; /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The importJobId. */ public java.lang.String getImportJobId() { java.lang.Object ref = importJobId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); importJobId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for importJobId. */ public com.google.protobuf.ByteString getImportJobIdBytes() { java.lang.Object ref = importJobId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); importJobId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The importJobId to set. * @return This builder for chaining. */ public Builder setImportJobId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } importJobId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearImportJobId() { importJobId_ = getDefaultInstance().getImportJobId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. It must be unique within a KeyRing and match the regular * expression `[a-zA-Z0-9_-]{1,63}` * </pre> * * <code>string import_job_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for importJobId to set. * @return This builder for chaining. */ public Builder setImportJobIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); importJobId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.kms.v1.ImportJob importJob_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.kms.v1.ImportJob, com.google.cloud.kms.v1.ImportJob.Builder, com.google.cloud.kms.v1.ImportJobOrBuilder> importJobBuilder_; /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the importJob field is set. */ public boolean hasImportJob() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The importJob. */ public com.google.cloud.kms.v1.ImportJob getImportJob() { if (importJobBuilder_ == null) { return importJob_ == null ? com.google.cloud.kms.v1.ImportJob.getDefaultInstance() : importJob_; } else { return importJobBuilder_.getMessage(); } } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setImportJob(com.google.cloud.kms.v1.ImportJob value) { if (importJobBuilder_ == null) { if (value == null) { throw new NullPointerException(); } importJob_ = value; } else { importJobBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setImportJob(com.google.cloud.kms.v1.ImportJob.Builder builderForValue) { if (importJobBuilder_ == null) { importJob_ = builderForValue.build(); } else { importJobBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeImportJob(com.google.cloud.kms.v1.ImportJob value) { if (importJobBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && importJob_ != null && importJob_ != com.google.cloud.kms.v1.ImportJob.getDefaultInstance()) { getImportJobBuilder().mergeFrom(value); } else { importJob_ = value; } } else { importJobBuilder_.mergeFrom(value); } if (importJob_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearImportJob() { bitField0_ = (bitField0_ & ~0x00000004); importJob_ = null; if (importJobBuilder_ != null) { importJobBuilder_.dispose(); importJobBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.kms.v1.ImportJob.Builder getImportJobBuilder() { bitField0_ |= 0x00000004; onChanged(); return getImportJobFieldBuilder().getBuilder(); } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.kms.v1.ImportJobOrBuilder getImportJobOrBuilder() { if (importJobBuilder_ != null) { return importJobBuilder_.getMessageOrBuilder(); } else { return importJob_ == null ? com.google.cloud.kms.v1.ImportJob.getDefaultInstance() : importJob_; } } /** * * * <pre> * Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field * values. * </pre> * * <code> * .google.cloud.kms.v1.ImportJob import_job = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.kms.v1.ImportJob, com.google.cloud.kms.v1.ImportJob.Builder, com.google.cloud.kms.v1.ImportJobOrBuilder> getImportJobFieldBuilder() { if (importJobBuilder_ == null) { importJobBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.kms.v1.ImportJob, com.google.cloud.kms.v1.ImportJob.Builder, com.google.cloud.kms.v1.ImportJobOrBuilder>( getImportJob(), getParentForChildren(), isClean()); importJob_ = null; } return importJobBuilder_; } @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.CreateImportJobRequest) } // @@protoc_insertion_point(class_scope:google.cloud.kms.v1.CreateImportJobRequest) private static final com.google.cloud.kms.v1.CreateImportJobRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.kms.v1.CreateImportJobRequest(); } public static com.google.cloud.kms.v1.CreateImportJobRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateImportJobRequest> PARSER = new com.google.protobuf.AbstractParser<CreateImportJobRequest>() { @java.lang.Override public CreateImportJobRequest 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<CreateImportJobRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateImportJobRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.kms.v1.CreateImportJobRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hudi
37,076
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/cdc/CdcInputFormat.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.table.format.cdc; import org.apache.hudi.avro.AvroSchemaCache; import org.apache.hudi.avro.HoodieAvroUtils; import org.apache.hudi.client.model.HoodieFlinkRecord; import org.apache.hudi.common.config.TypedProperties; import org.apache.hudi.common.engine.HoodieReaderContext; import org.apache.hudi.common.fs.FSUtils; import org.apache.hudi.common.model.BaseFile; import org.apache.hudi.common.model.FileSlice; import org.apache.hudi.common.model.HoodieLogFile; import org.apache.hudi.common.model.HoodieOperation; import org.apache.hudi.common.model.HoodieRecord; import org.apache.hudi.common.table.HoodieTableMetaClient; import org.apache.hudi.common.table.cdc.HoodieCDCFileSplit; import org.apache.hudi.common.table.cdc.HoodieCDCSupplementalLoggingMode; import org.apache.hudi.common.table.cdc.HoodieCDCUtils; import org.apache.hudi.common.table.log.HoodieCDCLogRecordIterator; import org.apache.hudi.common.table.read.BufferedRecord; import org.apache.hudi.common.table.read.BufferedRecordMerger; import org.apache.hudi.common.table.read.BufferedRecordMergerFactory; import org.apache.hudi.common.table.read.BufferedRecords; import org.apache.hudi.common.table.read.DeleteContext; import org.apache.hudi.common.table.read.HoodieFileGroupReader; import org.apache.hudi.common.util.CollectionUtils; import org.apache.hudi.common.util.ConfigUtils; import org.apache.hudi.common.util.Option; import org.apache.hudi.common.util.ValidationUtils; import org.apache.hudi.common.util.collection.ClosableIterator; import org.apache.hudi.common.util.collection.ExternalSpillableMap; import org.apache.hudi.common.util.collection.Pair; import org.apache.hudi.config.HoodieWriteConfig; import org.apache.hudi.configuration.FlinkOptions; import org.apache.hudi.configuration.OptionsResolver; import org.apache.hudi.exception.HoodieException; import org.apache.hudi.exception.HoodieIOException; import org.apache.hudi.source.ExpressionPredicates.Predicate; import org.apache.hudi.storage.HoodieStorage; import org.apache.hudi.storage.StoragePath; import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; import org.apache.hudi.table.format.FlinkReaderContextFactory; import org.apache.hudi.table.format.FormatUtils; import org.apache.hudi.table.format.InternalSchemaManager; import org.apache.hudi.table.format.mor.MergeOnReadInputFormat; import org.apache.hudi.table.format.mor.MergeOnReadInputSplit; import org.apache.hudi.table.format.mor.MergeOnReadTableState; import org.apache.hudi.util.AvroToRowDataConverters; import org.apache.hudi.util.FlinkWriteClients; import org.apache.hudi.util.RowDataProjection; import org.apache.hudi.util.StreamerUtil; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.table.data.RowData; import org.apache.flink.table.runtime.typeutils.RowDataSerializer; import org.apache.flink.table.types.DataType; import org.apache.flink.table.types.logical.RowType; import org.apache.flink.types.RowKind; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; import static org.apache.hudi.hadoop.utils.HoodieInputFormatUtils.HOODIE_RECORD_KEY_COL_POS; import static org.apache.hudi.table.format.FormatUtils.buildAvroRecordBySchema; /** * The base InputFormat class to read Hoodie data set as change logs. */ public class CdcInputFormat extends MergeOnReadInputFormat { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(CdcInputFormat.class); private CdcInputFormat( Configuration conf, MergeOnReadTableState tableState, List<DataType> fieldTypes, List<Predicate> predicates, long limit, boolean emitDelete) { super(conf, tableState, fieldTypes, predicates, limit, emitDelete, InternalSchemaManager.DISABLED); } @Override protected ClosableIterator<RowData> initIterator(MergeOnReadInputSplit split) throws IOException { if (split instanceof CdcInputSplit) { HoodieCDCSupplementalLoggingMode mode = OptionsResolver.getCDCSupplementalLoggingMode(conf); ImageManager manager = new ImageManager(conf, tableState.getRowType(), this::getFileSliceIterator); Function<HoodieCDCFileSplit, ClosableIterator<RowData>> recordIteratorFunc = cdcFileSplit -> getRecordIteratorV2(split.getTablePath(), split.getMaxCompactionMemoryInBytes(), cdcFileSplit, mode, manager); return new CdcFileSplitsIterator((CdcInputSplit) split, manager, recordIteratorFunc); } else { return super.initIterator(split); } } /** * Returns the builder for {@link MergeOnReadInputFormat}. */ public static Builder builder() { return new Builder(); } private ClosableIterator<RowData> getFileSliceIterator(MergeOnReadInputSplit split) { try { // get full schema iterator. final Schema tableSchema = AvroSchemaCache.intern(new Schema.Parser().parse(tableState.getAvroSchema())); // before/after images have assumption of snapshot scan, so `emitDelete` is set as false return getSplitRowIterator(split, tableSchema, tableSchema, FlinkOptions.REALTIME_PAYLOAD_COMBINE, false); } catch (IOException e) { throw new HoodieException("Failed to create iterator for split: " + split, e); } } private ClosableIterator<RowData> getRecordIteratorV2( String tablePath, long maxCompactionMemoryInBytes, HoodieCDCFileSplit fileSplit, HoodieCDCSupplementalLoggingMode mode, ImageManager imageManager) { try { return getRecordIterator(tablePath, maxCompactionMemoryInBytes, fileSplit, mode, imageManager); } catch (IOException e) { throw new HoodieException("Get record iterator error", e); } } private ClosableIterator<RowData> getRecordIterator( String tablePath, long maxCompactionMemoryInBytes, HoodieCDCFileSplit fileSplit, HoodieCDCSupplementalLoggingMode mode, ImageManager imageManager) throws IOException { switch (fileSplit.getCdcInferCase()) { case BASE_FILE_INSERT: ValidationUtils.checkState(fileSplit.getCdcFiles() != null && fileSplit.getCdcFiles().size() == 1, "CDC file path should exist and be singleton"); String path = new Path(tablePath, fileSplit.getCdcFiles().get(0)).toString(); return new AddBaseFileIterator(getBaseFileIterator(path)); case BASE_FILE_DELETE: ValidationUtils.checkState(fileSplit.getBeforeFileSlice().isPresent(), "Before file slice should exist"); FileSlice fileSlice = fileSplit.getBeforeFileSlice().get(); MergeOnReadInputSplit inputSplit = fileSlice2Split(tablePath, fileSlice, maxCompactionMemoryInBytes); return new RemoveBaseFileIterator(tableState, getFileSliceIterator(inputSplit)); case AS_IS: Schema dataSchema = HoodieAvroUtils.removeMetadataFields(new Schema.Parser().parse(tableState.getAvroSchema())); Schema cdcSchema = HoodieCDCUtils.schemaBySupplementalLoggingMode(mode, dataSchema); switch (mode) { case DATA_BEFORE_AFTER: return new BeforeAfterImageIterator(tablePath, tableState, hadoopConf, cdcSchema, fileSplit); case DATA_BEFORE: return new BeforeImageIterator(conf, hadoopConf, tablePath, tableState, cdcSchema, fileSplit, imageManager); case OP_KEY_ONLY: return new RecordKeyImageIterator(conf, hadoopConf, tablePath, tableState, cdcSchema, fileSplit, imageManager); default: throw new AssertionError("Unexpected mode" + mode); } case LOG_FILE: ValidationUtils.checkState(fileSplit.getCdcFiles() != null && fileSplit.getCdcFiles().size() == 1, "CDC file path should exist and be singleton"); String logFilepath = new Path(tablePath, fileSplit.getCdcFiles().get(0)).toString(); MergeOnReadInputSplit split = singleLogFile2Split(tablePath, logFilepath, maxCompactionMemoryInBytes); ClosableIterator<HoodieRecord<RowData>> recordIterator = getSplitRecordIterator(split); return new DataLogFileIterator(maxCompactionMemoryInBytes, imageManager, fileSplit, tableState, recordIterator, metaClient); case REPLACE_COMMIT: return new ReplaceCommitIterator(conf, tablePath, tableState, fileSplit, this::getFileSliceIterator); default: throw new AssertionError("Unexpected cdc file split infer case: " + fileSplit.getCdcInferCase()); } } /** * Get a {@link HoodieRecord} iterator using {@link HoodieFileGroupReader}. * * @param split input split * * @return {@link RowData} iterator for the given split. */ private ClosableIterator<HoodieRecord<RowData>> getSplitRecordIterator(MergeOnReadInputSplit split) throws IOException { final Schema tableSchema = AvroSchemaCache.intern(new Schema.Parser().parse(tableState.getAvroSchema())); HoodieFileGroupReader<RowData> fileGroupReader = createFileGroupReader(split, tableSchema, tableSchema, FlinkOptions.REALTIME_PAYLOAD_COMBINE, true); return fileGroupReader.getClosableHoodieRecordIterator(); } // ------------------------------------------------------------------------- // Inner Class // ------------------------------------------------------------------------- static class CdcFileSplitsIterator implements ClosableIterator<RowData> { private ImageManager imageManager; // keep a reference to release resource private final Iterator<HoodieCDCFileSplit> fileSplitIterator; private final Function<HoodieCDCFileSplit, ClosableIterator<RowData>> recordIteratorFunc; private ClosableIterator<RowData> recordIterator; CdcFileSplitsIterator( CdcInputSplit inputSplit, ImageManager imageManager, Function<HoodieCDCFileSplit, ClosableIterator<RowData>> recordIteratorFunc) { this.fileSplitIterator = Arrays.asList(inputSplit.getChanges()).iterator(); this.imageManager = imageManager; this.recordIteratorFunc = recordIteratorFunc; } @Override public boolean hasNext() { if (recordIterator != null) { if (recordIterator.hasNext()) { return true; } else { recordIterator.close(); // release resource recordIterator = null; } } if (fileSplitIterator.hasNext()) { HoodieCDCFileSplit fileSplit = fileSplitIterator.next(); recordIterator = recordIteratorFunc.apply(fileSplit); return recordIterator.hasNext(); } return false; } @Override public RowData next() { return recordIterator.next(); } @Override public void close() { if (recordIterator != null) { recordIterator.close(); } if (imageManager != null) { imageManager.close(); imageManager = null; } } } static class AddBaseFileIterator implements ClosableIterator<RowData> { // base file record iterator private ClosableIterator<RowData> nested; private RowData currentRecord; AddBaseFileIterator(ClosableIterator<RowData> nested) { this.nested = nested; } @Override public boolean hasNext() { if (this.nested.hasNext()) { currentRecord = this.nested.next(); currentRecord.setRowKind(RowKind.INSERT); return true; } return false; } @Override public RowData next() { return currentRecord; } @Override public void close() { if (this.nested != null) { this.nested.close(); this.nested = null; } } } static class RemoveBaseFileIterator implements ClosableIterator<RowData> { private ClosableIterator<RowData> nested; private final RowDataProjection projection; RemoveBaseFileIterator(MergeOnReadTableState tableState, ClosableIterator<RowData> iterator) { this.nested = iterator; this.projection = RowDataProjection.instance(tableState.getRequiredRowType(), tableState.getRequiredPositions()); } @Override public boolean hasNext() { return nested.hasNext(); } @Override public RowData next() { RowData row = nested.next(); row.setRowKind(RowKind.DELETE); return this.projection.project(row); } @Override public void close() { if (this.nested != null) { this.nested.close(); this.nested = null; } } } // accounting to HoodieCDCInferenceCase.LOG_FILE static class DataLogFileIterator implements ClosableIterator<RowData> { private final Schema tableSchema; private final long maxCompactionMemoryInBytes; private final ImageManager imageManager; private final RowDataProjection projection; private final BufferedRecordMerger recordMerger; private final ClosableIterator<HoodieRecord<RowData>> logRecordIterator; private final DeleteContext deleteContext; private ExternalSpillableMap<String, byte[]> beforeImages; private RowData currentImage; private RowData sideImage; private HoodieReaderContext<RowData> readerContext; private String[] orderingFields; private TypedProperties props; DataLogFileIterator( long maxCompactionMemoryInBytes, ImageManager imageManager, HoodieCDCFileSplit cdcFileSplit, MergeOnReadTableState tableState, ClosableIterator<HoodieRecord<RowData>> logRecordIterator, HoodieTableMetaClient metaClient) throws IOException { this.tableSchema = new Schema.Parser().parse(tableState.getAvroSchema()); this.maxCompactionMemoryInBytes = maxCompactionMemoryInBytes; this.imageManager = imageManager; this.projection = tableState.getRequiredRowType().equals(tableState.getRowType()) ? null : RowDataProjection.instance(tableState.getRequiredRowType(), tableState.getRequiredPositions()); HoodieWriteConfig writeConfig = this.imageManager.writeConfig; this.props = writeConfig.getProps(); this.readerContext = new FlinkReaderContextFactory(metaClient).getContext(); readerContext.initRecordMerger(props); this.orderingFields = ConfigUtils.getOrderingFields(props); this.recordMerger = BufferedRecordMergerFactory.create( readerContext, readerContext.getMergeMode(), false, Option.of(imageManager.writeConfig.getRecordMerger()), tableSchema, Option.ofNullable(Pair.of(metaClient.getTableConfig().getPayloadClass(), writeConfig.getPayloadClass())), props, metaClient.getTableConfig().getPartialUpdateMode()); this.logRecordIterator = logRecordIterator; initImages(cdcFileSplit); this.deleteContext = new DeleteContext(props, tableSchema).withReaderSchema(tableSchema); } private void initImages(HoodieCDCFileSplit fileSplit) throws IOException { // init before images if (fileSplit.getBeforeFileSlice().isPresent() && !fileSplit.getBeforeFileSlice().get().isEmpty()) { this.beforeImages = this.imageManager.getOrLoadImages( maxCompactionMemoryInBytes, fileSplit.getBeforeFileSlice().get()); } else { // still initializes an empty map this.beforeImages = FormatUtils.spillableMap(this.imageManager.writeConfig, maxCompactionMemoryInBytes, getClass().getSimpleName()); } } @Override public boolean hasNext() { if (this.sideImage != null) { this.currentImage = this.sideImage; this.sideImage = null; return true; } while (logRecordIterator.hasNext()) { HoodieRecord<RowData> record = logRecordIterator.next(); RowData existed = imageManager.removeImageRecord(record.getRecordKey(), beforeImages); if (isDelete(record)) { // it's a deleted record. if (existed != null) { // there is a real record deleted. existed.setRowKind(RowKind.DELETE); this.currentImage = existed; return true; } } else { if (existed == null) { // a new record is inserted. RowData newRow = record.getData(); newRow.setRowKind(RowKind.INSERT); this.currentImage = newRow; return true; } else { // an existed record is updated, assuming new record and existing record share the same hoodie key HoodieOperation operation = HoodieOperation.fromValue(existed.getRowKind().toByteValue()); HoodieRecord<RowData> historyRecord = new HoodieFlinkRecord(record.getKey(), operation, existed); HoodieRecord<RowData> merged = mergeRowWithLog(historyRecord, record).get(); if (merged.getData() != existed) { // update happens existed.setRowKind(RowKind.UPDATE_BEFORE); this.currentImage = existed; RowData mergedRow = merged.getData(); mergedRow.setRowKind(RowKind.UPDATE_AFTER); this.imageManager.updateImageRecord(record.getRecordKey(), beforeImages, mergedRow); this.sideImage = mergedRow; return true; } } } } return false; } @Override public RowData next() { return this.projection != null ? this.projection.project(this.currentImage) : this.currentImage; } @Override public void close() { this.logRecordIterator.close(); this.imageManager.close(); } @SuppressWarnings("unchecked") private Option<HoodieRecord<RowData>> mergeRowWithLog(HoodieRecord<RowData> historyRecord, HoodieRecord<RowData> newRecord) { try { BufferedRecord<RowData> historyBufferedRecord = BufferedRecords.fromHoodieRecord(historyRecord, tableSchema, readerContext.getRecordContext(), props, orderingFields, deleteContext); BufferedRecord<RowData> newBufferedRecord = BufferedRecords.fromHoodieRecord(newRecord, tableSchema, readerContext.getRecordContext(), props, orderingFields, deleteContext); BufferedRecord<RowData> mergedRecord = recordMerger.finalMerge(historyBufferedRecord, newBufferedRecord); return Option.ofNullable(readerContext.getRecordContext().constructHoodieRecord(mergedRecord, historyRecord.getPartitionPath())); } catch (IOException e) { throw new HoodieIOException("Merge base and delta payloads exception", e); } } private boolean isDelete(HoodieRecord<RowData> record) { return record.isDelete(deleteContext, CollectionUtils.emptyProps()); } } abstract static class BaseImageIterator implements ClosableIterator<RowData> { private final Schema requiredSchema; private final int[] requiredPos; private final GenericRecordBuilder recordBuilder; private final AvroToRowDataConverters.AvroToRowDataConverter avroToRowDataConverter; // the changelog records iterator private HoodieCDCLogRecordIterator cdcItr; private GenericRecord cdcRecord; private RowData sideImage; private RowData currentImage; BaseImageIterator( org.apache.hadoop.conf.Configuration hadoopConf, String tablePath, MergeOnReadTableState tableState, Schema cdcSchema, HoodieCDCFileSplit fileSplit) { this.requiredSchema = new Schema.Parser().parse(tableState.getRequiredAvroSchema()); this.requiredPos = getRequiredPos(tableState.getAvroSchema(), this.requiredSchema); this.recordBuilder = new GenericRecordBuilder(requiredSchema); this.avroToRowDataConverter = AvroToRowDataConverters.createRowConverter(tableState.getRequiredRowType()); StoragePath hadoopTablePath = new StoragePath(tablePath); HoodieStorage storage = new HoodieHadoopStorage(tablePath, hadoopConf); HoodieLogFile[] cdcLogFiles = fileSplit.getCdcFiles().stream().map(cdcFile -> { try { return new HoodieLogFile( storage.getPathInfo(new StoragePath(hadoopTablePath, cdcFile))); } catch (IOException e) { throw new HoodieIOException("Fail to call getFileStatus", e); } }).toArray(HoodieLogFile[]::new); this.cdcItr = new HoodieCDCLogRecordIterator(storage, cdcLogFiles, cdcSchema); } private int[] getRequiredPos(String tableSchema, Schema required) { Schema dataSchema = HoodieAvroUtils.removeMetadataFields(new Schema.Parser().parse(tableSchema)); List<String> fields = dataSchema.getFields().stream().map(Schema.Field::name).collect(Collectors.toList()); return required.getFields().stream() .map(f -> fields.indexOf(f.name())) .mapToInt(i -> i) .toArray(); } @Override public boolean hasNext() { if (this.sideImage != null) { currentImage = this.sideImage; this.sideImage = null; return true; } else if (this.cdcItr.hasNext()) { cdcRecord = (GenericRecord) this.cdcItr.next(); String op = String.valueOf(cdcRecord.get(0)); resolveImage(op); return true; } return false; } protected abstract RowData getAfterImage(RowKind rowKind, GenericRecord cdcRecord); protected abstract RowData getBeforeImage(RowKind rowKind, GenericRecord cdcRecord); @Override public RowData next() { return currentImage; } @Override public void close() { if (this.cdcItr != null) { this.cdcItr.close(); this.cdcItr = null; } } private void resolveImage(String op) { switch (op) { case "i": currentImage = getAfterImage(RowKind.INSERT, cdcRecord); break; case "u": currentImage = getBeforeImage(RowKind.UPDATE_BEFORE, cdcRecord); sideImage = getAfterImage(RowKind.UPDATE_AFTER, cdcRecord); break; case "d": currentImage = getBeforeImage(RowKind.DELETE, cdcRecord); break; default: throw new AssertionError("Unexpected"); } } protected RowData resolveAvro(RowKind rowKind, GenericRecord avroRecord) { GenericRecord requiredAvroRecord = buildAvroRecordBySchema( avroRecord, requiredSchema, requiredPos, recordBuilder); RowData resolved = (RowData) avroToRowDataConverter.convert(requiredAvroRecord); resolved.setRowKind(rowKind); return resolved; } } // op, ts, before_image, after_image static class BeforeAfterImageIterator extends BaseImageIterator { BeforeAfterImageIterator( String tablePath, MergeOnReadTableState tableState, org.apache.hadoop.conf.Configuration hadoopConf, Schema cdcSchema, HoodieCDCFileSplit fileSplit) { super(hadoopConf, tablePath, tableState, cdcSchema, fileSplit); } @Override protected RowData getAfterImage(RowKind rowKind, GenericRecord cdcRecord) { return resolveAvro(rowKind, (GenericRecord) cdcRecord.get(3)); } @Override protected RowData getBeforeImage(RowKind rowKind, GenericRecord cdcRecord) { return resolveAvro(rowKind, (GenericRecord) cdcRecord.get(2)); } } // op, key, before_image static class BeforeImageIterator extends BaseImageIterator { protected ExternalSpillableMap<String, byte[]> afterImages; protected final long maxCompactionMemoryInBytes; protected final RowDataProjection projection; protected final ImageManager imageManager; BeforeImageIterator( Configuration flinkConf, org.apache.hadoop.conf.Configuration hadoopConf, String tablePath, MergeOnReadTableState tableState, Schema cdcSchema, HoodieCDCFileSplit fileSplit, ImageManager imageManager) throws IOException { super(hadoopConf, tablePath, tableState, cdcSchema, fileSplit); this.maxCompactionMemoryInBytes = StreamerUtil.getMaxCompactionMemoryInBytes(flinkConf); this.projection = RowDataProjection.instance(tableState.getRequiredRowType(), tableState.getRequiredPositions()); this.imageManager = imageManager; initImages(fileSplit); } protected void initImages( HoodieCDCFileSplit fileSplit) throws IOException { ValidationUtils.checkState(fileSplit.getAfterFileSlice().isPresent(), "Current file slice does not exist for instant: " + fileSplit.getInstant()); this.afterImages = this.imageManager.getOrLoadImages( maxCompactionMemoryInBytes, fileSplit.getAfterFileSlice().get()); } @Override protected RowData getAfterImage(RowKind rowKind, GenericRecord cdcRecord) { String recordKey = cdcRecord.get(1).toString(); RowData row = imageManager.getImageRecord(recordKey, this.afterImages, rowKind); row.setRowKind(rowKind); return this.projection.project(row); } @Override protected RowData getBeforeImage(RowKind rowKind, GenericRecord cdcRecord) { return resolveAvro(rowKind, (GenericRecord) cdcRecord.get(2)); } } // op, key static class RecordKeyImageIterator extends BeforeImageIterator { protected ExternalSpillableMap<String, byte[]> beforeImages; RecordKeyImageIterator( Configuration flinkConf, org.apache.hadoop.conf.Configuration hadoopConf, String tablePath, MergeOnReadTableState tableState, Schema cdcSchema, HoodieCDCFileSplit fileSplit, ImageManager imageManager) throws IOException { super(flinkConf, hadoopConf, tablePath, tableState, cdcSchema, fileSplit, imageManager); } protected void initImages(HoodieCDCFileSplit fileSplit) throws IOException { // init after images super.initImages(fileSplit); // init before images ValidationUtils.checkState(fileSplit.getBeforeFileSlice().isPresent(), "Before file slice does not exist for instant: " + fileSplit.getInstant()); this.beforeImages = this.imageManager.getOrLoadImages( maxCompactionMemoryInBytes, fileSplit.getBeforeFileSlice().get()); } @Override protected RowData getBeforeImage(RowKind rowKind, GenericRecord cdcRecord) { String recordKey = cdcRecord.get(1).toString(); RowData row = this.imageManager.getImageRecord(recordKey, this.beforeImages, rowKind); row.setRowKind(rowKind); return this.projection.project(row); } } static class ReplaceCommitIterator implements ClosableIterator<RowData> { private final ClosableIterator<RowData> itr; private final RowDataProjection projection; ReplaceCommitIterator( Configuration flinkConf, String tablePath, MergeOnReadTableState tableState, HoodieCDCFileSplit fileSplit, Function<MergeOnReadInputSplit, ClosableIterator<RowData>> splitIteratorFunc) { this.itr = initIterator(tablePath, StreamerUtil.getMaxCompactionMemoryInBytes(flinkConf), fileSplit, splitIteratorFunc); this.projection = RowDataProjection.instance(tableState.getRequiredRowType(), tableState.getRequiredPositions()); } private ClosableIterator<RowData> initIterator( String tablePath, long maxCompactionMemoryInBytes, HoodieCDCFileSplit fileSplit, Function<MergeOnReadInputSplit, ClosableIterator<RowData>> splitIteratorFunc) { // init before images // the before file slice must exist, // see HoodieCDCExtractor#extractCDCFileSplits for details ValidationUtils.checkState(fileSplit.getBeforeFileSlice().isPresent(), "Before file slice does not exist for instant: " + fileSplit.getInstant()); MergeOnReadInputSplit inputSplit = CdcInputFormat.fileSlice2Split( tablePath, fileSplit.getBeforeFileSlice().get(), maxCompactionMemoryInBytes); return splitIteratorFunc.apply(inputSplit); } @Override public boolean hasNext() { return this.itr.hasNext(); } @Override public RowData next() { RowData row = this.itr.next(); row.setRowKind(RowKind.DELETE); return this.projection.project(row); } @Override public void close() { this.itr.close(); } } public static final class BytesArrayInputView extends DataInputStream implements DataInputView { public BytesArrayInputView(byte[] data) { super(new ByteArrayInputStream(data)); } public void skipBytesToRead(int numBytes) throws IOException { while (numBytes > 0) { int skipped = this.skipBytes(numBytes); numBytes -= skipped; } } } public static final class BytesArrayOutputView extends DataOutputStream implements DataOutputView { public BytesArrayOutputView(ByteArrayOutputStream baos) { super(baos); } public void skipBytesToWrite(int numBytes) throws IOException { for (int i = 0; i < numBytes; ++i) { this.write(0); } } public void write(DataInputView source, int numBytes) throws IOException { byte[] buffer = new byte[numBytes]; source.readFully(buffer); this.write(buffer); } } /** * A before/after image manager * that caches the image records by versions(file slices). */ private static class ImageManager implements AutoCloseable { private final HoodieWriteConfig writeConfig; private final RowDataSerializer serializer; private final Function<MergeOnReadInputSplit, ClosableIterator<RowData>> splitIteratorFunc; private final Map<String, ExternalSpillableMap<String, byte[]>> cache; public ImageManager( Configuration flinkConf, RowType rowType, Function<MergeOnReadInputSplit, ClosableIterator<RowData>> splitIteratorFunc) { this.serializer = new RowDataSerializer(rowType); this.splitIteratorFunc = splitIteratorFunc; this.cache = new TreeMap<>(); this.writeConfig = FlinkWriteClients.getHoodieClientConfig(flinkConf); } public ExternalSpillableMap<String, byte[]> getOrLoadImages( long maxCompactionMemoryInBytes, FileSlice fileSlice) throws IOException { final String instant = fileSlice.getBaseInstantTime(); if (this.cache.containsKey(instant)) { return cache.get(instant); } // clean the earliest file slice first if (this.cache.size() > 1) { // keep at most 2 versions: before & after String instantToClean = this.cache.keySet().iterator().next(); this.cache.remove(instantToClean).close(); } ExternalSpillableMap<String, byte[]> images = loadImageRecords(maxCompactionMemoryInBytes, fileSlice); this.cache.put(instant, images); return images; } private ExternalSpillableMap<String, byte[]> loadImageRecords( long maxCompactionMemoryInBytes, FileSlice fileSlice) throws IOException { MergeOnReadInputSplit inputSplit = CdcInputFormat.fileSlice2Split(writeConfig.getBasePath(), fileSlice, maxCompactionMemoryInBytes); // initialize the image records map ExternalSpillableMap<String, byte[]> imageRecordsMap = FormatUtils.spillableMap(writeConfig, maxCompactionMemoryInBytes, getClass().getSimpleName()); try (ClosableIterator<RowData> itr = splitIteratorFunc.apply(inputSplit)) { while (itr.hasNext()) { RowData row = itr.next(); String recordKey = row.getString(HOODIE_RECORD_KEY_COL_POS).toString(); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); serializer.serialize(row, new BytesArrayOutputView(baos)); imageRecordsMap.put(recordKey, baos.toByteArray()); } } return imageRecordsMap; } public RowData getImageRecord( String recordKey, ExternalSpillableMap<String, byte[]> cache, RowKind rowKind) { byte[] bytes = cache.get(recordKey); ValidationUtils.checkState(bytes != null, "Key " + recordKey + " does not exist in current file group"); try { RowData row = serializer.deserialize(new BytesArrayInputView(bytes)); row.setRowKind(rowKind); return row; } catch (IOException e) { throw new HoodieException("Deserialize bytes into row data exception", e); } } public void updateImageRecord( String recordKey, ExternalSpillableMap<String, byte[]> cache, RowData row) { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); try { serializer.serialize(row, new BytesArrayOutputView(baos)); } catch (IOException e) { throw new HoodieException("Serialize row data into bytes exception", e); } cache.put(recordKey, baos.toByteArray()); } public RowData removeImageRecord( String recordKey, ExternalSpillableMap<String, byte[]> cache) { byte[] bytes = cache.remove(recordKey); if (bytes == null) { return null; } try { return serializer.deserialize(new BytesArrayInputView(bytes)); } catch (IOException e) { throw new HoodieException("Deserialize bytes into row data exception", e); } } @Override public void close() { this.cache.values().forEach(ExternalSpillableMap::close); this.cache.clear(); } } /** * Builder for {@link CdcInputFormat}. */ public static class Builder extends MergeOnReadInputFormat.Builder { public Builder config(Configuration conf) { this.conf = conf; return this; } public Builder tableState(MergeOnReadTableState tableState) { this.tableState = tableState; return this; } public Builder fieldTypes(List<DataType> fieldTypes) { this.fieldTypes = fieldTypes; return this; } public Builder predicates(List<Predicate> predicates) { this.predicates = predicates; return this; } public Builder limit(long limit) { this.limit = limit; return this; } public Builder emitDelete(boolean emitDelete) { this.emitDelete = emitDelete; return this; } public CdcInputFormat build() { return new CdcInputFormat(conf, tableState, fieldTypes, predicates, limit, emitDelete); } } // ------------------------------------------------------------------------- // Utilities // ------------------------------------------------------------------------- public static MergeOnReadInputSplit fileSlice2Split( String tablePath, FileSlice fileSlice, long maxCompactionMemoryInBytes) { Option<List<String>> logPaths = Option.ofNullable(fileSlice.getLogFiles() .sorted(HoodieLogFile.getLogFileComparator()) .map(logFile -> logFile.getPath().toString()) // filter out the cdc logs .filter(path -> !path.endsWith(HoodieCDCUtils.CDC_LOGFILE_SUFFIX)) .collect(Collectors.toList())); String basePath = fileSlice.getBaseFile().map(BaseFile::getPath).orElse(null); return new MergeOnReadInputSplit(0, basePath, logPaths, fileSlice.getLatestInstantTime(), tablePath, maxCompactionMemoryInBytes, FlinkOptions.REALTIME_PAYLOAD_COMBINE, null, fileSlice.getFileId()); } public static MergeOnReadInputSplit singleLogFile2Split(String tablePath, String filePath, long maxCompactionMemoryInBytes) { return new MergeOnReadInputSplit(0, null, Option.of(Collections.singletonList(filePath)), FSUtils.getDeltaCommitTimeFromLogPath(new StoragePath(filePath)), tablePath, maxCompactionMemoryInBytes, FlinkOptions.REALTIME_PAYLOAD_COMBINE, null, FSUtils.getFileIdFromLogPath(new StoragePath(filePath))); } }
googleapis/google-cloud-java
36,812
java-retail/proto-google-cloud-retail-v2alpha/src/main/java/com/google/cloud/retail/v2alpha/CreateControlRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/retail/v2alpha/control_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.retail.v2alpha; /** * * * <pre> * Request for CreateControl method. * </pre> * * Protobuf type {@code google.cloud.retail.v2alpha.CreateControlRequest} */ public final class CreateControlRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.retail.v2alpha.CreateControlRequest) CreateControlRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateControlRequest.newBuilder() to construct. private CreateControlRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateControlRequest() { parent_ = ""; controlId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateControlRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2alpha.ControlServiceProto .internal_static_google_cloud_retail_v2alpha_CreateControlRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2alpha.ControlServiceProto .internal_static_google_cloud_retail_v2alpha_CreateControlRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2alpha.CreateControlRequest.class, com.google.cloud.retail.v2alpha.CreateControlRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONTROL_FIELD_NUMBER = 2; private com.google.cloud.retail.v2alpha.Control control_; /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the control field is set. */ @java.lang.Override public boolean hasControl() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The control. */ @java.lang.Override public com.google.cloud.retail.v2alpha.Control getControl() { return control_ == null ? com.google.cloud.retail.v2alpha.Control.getDefaultInstance() : control_; } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.retail.v2alpha.ControlOrBuilder getControlOrBuilder() { return control_ == null ? com.google.cloud.retail.v2alpha.Control.getDefaultInstance() : control_; } public static final int CONTROL_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object controlId_ = ""; /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The controlId. */ @java.lang.Override public java.lang.String getControlId() { java.lang.Object ref = controlId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); controlId_ = s; return s; } } /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for controlId. */ @java.lang.Override public com.google.protobuf.ByteString getControlIdBytes() { java.lang.Object ref = controlId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); controlId_ = 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, getControl()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(controlId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, controlId_); } 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, getControl()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(controlId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, controlId_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.retail.v2alpha.CreateControlRequest)) { return super.equals(obj); } com.google.cloud.retail.v2alpha.CreateControlRequest other = (com.google.cloud.retail.v2alpha.CreateControlRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasControl() != other.hasControl()) return false; if (hasControl()) { if (!getControl().equals(other.getControl())) return false; } if (!getControlId().equals(other.getControlId())) 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 (hasControl()) { hash = (37 * hash) + CONTROL_FIELD_NUMBER; hash = (53 * hash) + getControl().hashCode(); } hash = (37 * hash) + CONTROL_ID_FIELD_NUMBER; hash = (53 * hash) + getControlId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.retail.v2alpha.CreateControlRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.retail.v2alpha.CreateControlRequest 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 CreateControl method. * </pre> * * Protobuf type {@code google.cloud.retail.v2alpha.CreateControlRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.retail.v2alpha.CreateControlRequest) com.google.cloud.retail.v2alpha.CreateControlRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2alpha.ControlServiceProto .internal_static_google_cloud_retail_v2alpha_CreateControlRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2alpha.ControlServiceProto .internal_static_google_cloud_retail_v2alpha_CreateControlRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2alpha.CreateControlRequest.class, com.google.cloud.retail.v2alpha.CreateControlRequest.Builder.class); } // Construct using com.google.cloud.retail.v2alpha.CreateControlRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getControlFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; control_ = null; if (controlBuilder_ != null) { controlBuilder_.dispose(); controlBuilder_ = null; } controlId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.retail.v2alpha.ControlServiceProto .internal_static_google_cloud_retail_v2alpha_CreateControlRequest_descriptor; } @java.lang.Override public com.google.cloud.retail.v2alpha.CreateControlRequest getDefaultInstanceForType() { return com.google.cloud.retail.v2alpha.CreateControlRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.retail.v2alpha.CreateControlRequest build() { com.google.cloud.retail.v2alpha.CreateControlRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.retail.v2alpha.CreateControlRequest buildPartial() { com.google.cloud.retail.v2alpha.CreateControlRequest result = new com.google.cloud.retail.v2alpha.CreateControlRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.retail.v2alpha.CreateControlRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.control_ = controlBuilder_ == null ? control_ : controlBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.controlId_ = controlId_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.retail.v2alpha.CreateControlRequest) { return mergeFrom((com.google.cloud.retail.v2alpha.CreateControlRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.retail.v2alpha.CreateControlRequest other) { if (other == com.google.cloud.retail.v2alpha.CreateControlRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasControl()) { mergeControl(other.getControl()); } if (!other.getControlId().isEmpty()) { controlId_ = other.controlId_; 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(getControlFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { controlId_ = 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. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Full resource name of parent catalog. Format: * `projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.retail.v2alpha.Control control_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.retail.v2alpha.Control, com.google.cloud.retail.v2alpha.Control.Builder, com.google.cloud.retail.v2alpha.ControlOrBuilder> controlBuilder_; /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the control field is set. */ public boolean hasControl() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The control. */ public com.google.cloud.retail.v2alpha.Control getControl() { if (controlBuilder_ == null) { return control_ == null ? com.google.cloud.retail.v2alpha.Control.getDefaultInstance() : control_; } else { return controlBuilder_.getMessage(); } } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setControl(com.google.cloud.retail.v2alpha.Control value) { if (controlBuilder_ == null) { if (value == null) { throw new NullPointerException(); } control_ = value; } else { controlBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setControl(com.google.cloud.retail.v2alpha.Control.Builder builderForValue) { if (controlBuilder_ == null) { control_ = builderForValue.build(); } else { controlBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeControl(com.google.cloud.retail.v2alpha.Control value) { if (controlBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && control_ != null && control_ != com.google.cloud.retail.v2alpha.Control.getDefaultInstance()) { getControlBuilder().mergeFrom(value); } else { control_ = value; } } else { controlBuilder_.mergeFrom(value); } if (control_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearControl() { bitField0_ = (bitField0_ & ~0x00000002); control_ = null; if (controlBuilder_ != null) { controlBuilder_.dispose(); controlBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.retail.v2alpha.Control.Builder getControlBuilder() { bitField0_ |= 0x00000002; onChanged(); return getControlFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.retail.v2alpha.ControlOrBuilder getControlOrBuilder() { if (controlBuilder_ != null) { return controlBuilder_.getMessageOrBuilder(); } else { return control_ == null ? com.google.cloud.retail.v2alpha.Control.getDefaultInstance() : control_; } } /** * * * <pre> * Required. The Control to create. * </pre> * * <code> * .google.cloud.retail.v2alpha.Control control = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.retail.v2alpha.Control, com.google.cloud.retail.v2alpha.Control.Builder, com.google.cloud.retail.v2alpha.ControlOrBuilder> getControlFieldBuilder() { if (controlBuilder_ == null) { controlBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.retail.v2alpha.Control, com.google.cloud.retail.v2alpha.Control.Builder, com.google.cloud.retail.v2alpha.ControlOrBuilder>( getControl(), getParentForChildren(), isClean()); control_ = null; } return controlBuilder_; } private java.lang.Object controlId_ = ""; /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The controlId. */ public java.lang.String getControlId() { java.lang.Object ref = controlId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); controlId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for controlId. */ public com.google.protobuf.ByteString getControlIdBytes() { java.lang.Object ref = controlId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); controlId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The controlId to set. * @return This builder for chaining. */ public Builder setControlId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } controlId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearControlId() { controlId_ = getDefaultInstance().getControlId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. The ID to use for the Control, which will become the final * component of the Control's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-_/. * </pre> * * <code>string control_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for controlId to set. * @return This builder for chaining. */ public Builder setControlIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); controlId_ = 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.retail.v2alpha.CreateControlRequest) } // @@protoc_insertion_point(class_scope:google.cloud.retail.v2alpha.CreateControlRequest) private static final com.google.cloud.retail.v2alpha.CreateControlRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.retail.v2alpha.CreateControlRequest(); } public static com.google.cloud.retail.v2alpha.CreateControlRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateControlRequest> PARSER = new com.google.protobuf.AbstractParser<CreateControlRequest>() { @java.lang.Override public CreateControlRequest 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<CreateControlRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateControlRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.retail.v2alpha.CreateControlRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,101
java-resourcemanager/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/v3/stub/HttpJsonTagValuesStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.resourcemanager.v3.stub; import static com.google.cloud.resourcemanager.v3.TagValuesClient.ListTagValuesPagedResponse; 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.resourcemanager.v3.CreateTagValueMetadata; import com.google.cloud.resourcemanager.v3.CreateTagValueRequest; import com.google.cloud.resourcemanager.v3.DeleteTagValueMetadata; import com.google.cloud.resourcemanager.v3.DeleteTagValueRequest; import com.google.cloud.resourcemanager.v3.GetNamespacedTagValueRequest; import com.google.cloud.resourcemanager.v3.GetTagValueRequest; import com.google.cloud.resourcemanager.v3.ListTagValuesRequest; import com.google.cloud.resourcemanager.v3.ListTagValuesResponse; import com.google.cloud.resourcemanager.v3.TagValue; import com.google.cloud.resourcemanager.v3.UpdateTagValueMetadata; import com.google.cloud.resourcemanager.v3.UpdateTagValueRequest; import com.google.common.collect.ImmutableMap; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.protobuf.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 TagValues service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonTagValuesStub extends TagValuesStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder() .add(TagValue.getDescriptor()) .add(CreateTagValueMetadata.getDescriptor()) .add(UpdateTagValueMetadata.getDescriptor()) .add(DeleteTagValueMetadata.getDescriptor()) .build(); private static final ApiMethodDescriptor<ListTagValuesRequest, ListTagValuesResponse> listTagValuesMethodDescriptor = ApiMethodDescriptor.<ListTagValuesRequest, ListTagValuesResponse>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/ListTagValues") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListTagValuesRequest>newBuilder() .setPath( "/v3/tagValues", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListTagValuesRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListTagValuesRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "pageSize", request.getPageSize()); serializer.putQueryParam(fields, "pageToken", request.getPageToken()); serializer.putQueryParam(fields, "parent", request.getParent()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListTagValuesResponse>newBuilder() .setDefaultInstance(ListTagValuesResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetTagValueRequest, TagValue> getTagValueMethodDescriptor = ApiMethodDescriptor.<GetTagValueRequest, TagValue>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/GetTagValue") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetTagValueRequest>newBuilder() .setPath( "/v3/{name=tagValues/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<TagValue>newBuilder() .setDefaultInstance(TagValue.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetNamespacedTagValueRequest, TagValue> getNamespacedTagValueMethodDescriptor = ApiMethodDescriptor.<GetNamespacedTagValueRequest, TagValue>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/GetNamespacedTagValue") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetNamespacedTagValueRequest>newBuilder() .setPath( "/v3/tagValues/namespaced", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetNamespacedTagValueRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetNamespacedTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "name", request.getName()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<TagValue>newBuilder() .setDefaultInstance(TagValue.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<CreateTagValueRequest, Operation> createTagValueMethodDescriptor = ApiMethodDescriptor.<CreateTagValueRequest, Operation>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/CreateTagValue") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CreateTagValueRequest>newBuilder() .setPath( "/v3/tagValues", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CreateTagValueRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CreateTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("tagValue", request.getTagValue(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (CreateTagValueRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<UpdateTagValueRequest, Operation> updateTagValueMethodDescriptor = ApiMethodDescriptor.<UpdateTagValueRequest, Operation>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/UpdateTagValue") .setHttpMethod("PATCH") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<UpdateTagValueRequest>newBuilder() .setPath( "/v3/{tagValue.name=tagValues/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<UpdateTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "tagValue.name", request.getTagValue().getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<UpdateTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "updateMask", request.getUpdateMask()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("tagValue", request.getTagValue(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (UpdateTagValueRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<DeleteTagValueRequest, Operation> deleteTagValueMethodDescriptor = ApiMethodDescriptor.<DeleteTagValueRequest, Operation>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/DeleteTagValue") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteTagValueRequest>newBuilder() .setPath( "/v3/{name=tagValues/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteTagValueRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "etag", request.getEtag()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeleteTagValueRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor = ApiMethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/GetIamPolicy") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetIamPolicyRequest>newBuilder() .setPath( "/v3/{resource=tagValues/*}:getIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor = ApiMethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/SetIamPolicy") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<SetIamPolicyRequest>newBuilder() .setPath( "/v3/{resource=tagValues/*}:setIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsMethodDescriptor = ApiMethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setFullMethodName("google.cloud.resourcemanager.v3.TagValues/TestIamPermissions") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<TestIamPermissionsRequest>newBuilder() .setPath( "/v3/{resource=tagValues/*}:testIamPermissions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<TestIamPermissionsResponse>newBuilder() .setDefaultInstance(TestIamPermissionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<ListTagValuesRequest, ListTagValuesResponse> listTagValuesCallable; private final UnaryCallable<ListTagValuesRequest, ListTagValuesPagedResponse> listTagValuesPagedCallable; private final UnaryCallable<GetTagValueRequest, TagValue> getTagValueCallable; private final UnaryCallable<GetNamespacedTagValueRequest, TagValue> getNamespacedTagValueCallable; private final UnaryCallable<CreateTagValueRequest, Operation> createTagValueCallable; private final OperationCallable<CreateTagValueRequest, TagValue, CreateTagValueMetadata> createTagValueOperationCallable; private final UnaryCallable<UpdateTagValueRequest, Operation> updateTagValueCallable; private final OperationCallable<UpdateTagValueRequest, TagValue, UpdateTagValueMetadata> updateTagValueOperationCallable; private final UnaryCallable<DeleteTagValueRequest, Operation> deleteTagValueCallable; private final OperationCallable<DeleteTagValueRequest, TagValue, DeleteTagValueMetadata> deleteTagValueOperationCallable; private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable; private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable; private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final HttpJsonOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonTagValuesStub create(TagValuesStubSettings settings) throws IOException { return new HttpJsonTagValuesStub(settings, ClientContext.create(settings)); } public static final HttpJsonTagValuesStub create(ClientContext clientContext) throws IOException { return new HttpJsonTagValuesStub( TagValuesStubSettings.newHttpJsonBuilder().build(), clientContext); } public static final HttpJsonTagValuesStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonTagValuesStub( TagValuesStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonTagValuesStub, 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 HttpJsonTagValuesStub(TagValuesStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonTagValuesCallableFactory()); } /** * Constructs an instance of HttpJsonTagValuesStub, 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 HttpJsonTagValuesStub( TagValuesStubSettings 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.GetOperation", HttpRule.newBuilder().setGet("/v3/{name=operations/**}").build()) .build()); HttpJsonCallSettings<ListTagValuesRequest, ListTagValuesResponse> listTagValuesTransportSettings = HttpJsonCallSettings.<ListTagValuesRequest, ListTagValuesResponse>newBuilder() .setMethodDescriptor(listTagValuesMethodDescriptor) .setTypeRegistry(typeRegistry) .build(); HttpJsonCallSettings<GetTagValueRequest, TagValue> getTagValueTransportSettings = HttpJsonCallSettings.<GetTagValueRequest, TagValue>newBuilder() .setMethodDescriptor(getTagValueMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<GetNamespacedTagValueRequest, TagValue> getNamespacedTagValueTransportSettings = HttpJsonCallSettings.<GetNamespacedTagValueRequest, TagValue>newBuilder() .setMethodDescriptor(getNamespacedTagValueMethodDescriptor) .setTypeRegistry(typeRegistry) .build(); HttpJsonCallSettings<CreateTagValueRequest, Operation> createTagValueTransportSettings = HttpJsonCallSettings.<CreateTagValueRequest, Operation>newBuilder() .setMethodDescriptor(createTagValueMethodDescriptor) .setTypeRegistry(typeRegistry) .build(); HttpJsonCallSettings<UpdateTagValueRequest, Operation> updateTagValueTransportSettings = HttpJsonCallSettings.<UpdateTagValueRequest, Operation>newBuilder() .setMethodDescriptor(updateTagValueMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("tag_value.name", String.valueOf(request.getTagValue().getName())); return builder.build(); }) .build(); HttpJsonCallSettings<DeleteTagValueRequest, Operation> deleteTagValueTransportSettings = HttpJsonCallSettings.<DeleteTagValueRequest, Operation>newBuilder() .setMethodDescriptor(deleteTagValueMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings = HttpJsonCallSettings.<GetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(getIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings = HttpJsonCallSettings.<SetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(setIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsTransportSettings = HttpJsonCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.listTagValuesCallable = callableFactory.createUnaryCallable( listTagValuesTransportSettings, settings.listTagValuesSettings(), clientContext); this.listTagValuesPagedCallable = callableFactory.createPagedCallable( listTagValuesTransportSettings, settings.listTagValuesSettings(), clientContext); this.getTagValueCallable = callableFactory.createUnaryCallable( getTagValueTransportSettings, settings.getTagValueSettings(), clientContext); this.getNamespacedTagValueCallable = callableFactory.createUnaryCallable( getNamespacedTagValueTransportSettings, settings.getNamespacedTagValueSettings(), clientContext); this.createTagValueCallable = callableFactory.createUnaryCallable( createTagValueTransportSettings, settings.createTagValueSettings(), clientContext); this.createTagValueOperationCallable = callableFactory.createOperationCallable( createTagValueTransportSettings, settings.createTagValueOperationSettings(), clientContext, httpJsonOperationsStub); this.updateTagValueCallable = callableFactory.createUnaryCallable( updateTagValueTransportSettings, settings.updateTagValueSettings(), clientContext); this.updateTagValueOperationCallable = callableFactory.createOperationCallable( updateTagValueTransportSettings, settings.updateTagValueOperationSettings(), clientContext, httpJsonOperationsStub); this.deleteTagValueCallable = callableFactory.createUnaryCallable( deleteTagValueTransportSettings, settings.deleteTagValueSettings(), clientContext); this.deleteTagValueOperationCallable = callableFactory.createOperationCallable( deleteTagValueTransportSettings, settings.deleteTagValueOperationSettings(), clientContext, httpJsonOperationsStub); this.getIamPolicyCallable = callableFactory.createUnaryCallable( getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); this.setIamPolicyCallable = callableFactory.createUnaryCallable( setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); 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(listTagValuesMethodDescriptor); methodDescriptors.add(getTagValueMethodDescriptor); methodDescriptors.add(getNamespacedTagValueMethodDescriptor); methodDescriptors.add(createTagValueMethodDescriptor); methodDescriptors.add(updateTagValueMethodDescriptor); methodDescriptors.add(deleteTagValueMethodDescriptor); methodDescriptors.add(getIamPolicyMethodDescriptor); methodDescriptors.add(setIamPolicyMethodDescriptor); methodDescriptors.add(testIamPermissionsMethodDescriptor); return methodDescriptors; } public HttpJsonOperationsStub getHttpJsonOperationsStub() { return httpJsonOperationsStub; } @Override public UnaryCallable<ListTagValuesRequest, ListTagValuesResponse> listTagValuesCallable() { return listTagValuesCallable; } @Override public UnaryCallable<ListTagValuesRequest, ListTagValuesPagedResponse> listTagValuesPagedCallable() { return listTagValuesPagedCallable; } @Override public UnaryCallable<GetTagValueRequest, TagValue> getTagValueCallable() { return getTagValueCallable; } @Override public UnaryCallable<GetNamespacedTagValueRequest, TagValue> getNamespacedTagValueCallable() { return getNamespacedTagValueCallable; } @Override public UnaryCallable<CreateTagValueRequest, Operation> createTagValueCallable() { return createTagValueCallable; } @Override public OperationCallable<CreateTagValueRequest, TagValue, CreateTagValueMetadata> createTagValueOperationCallable() { return createTagValueOperationCallable; } @Override public UnaryCallable<UpdateTagValueRequest, Operation> updateTagValueCallable() { return updateTagValueCallable; } @Override public OperationCallable<UpdateTagValueRequest, TagValue, UpdateTagValueMetadata> updateTagValueOperationCallable() { return updateTagValueOperationCallable; } @Override public UnaryCallable<DeleteTagValueRequest, Operation> deleteTagValueCallable() { return deleteTagValueCallable; } @Override public OperationCallable<DeleteTagValueRequest, TagValue, DeleteTagValueMetadata> deleteTagValueOperationCallable() { return deleteTagValueOperationCallable; } @Override public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return getIamPolicyCallable; } @Override public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return setIamPolicyCallable; } @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/cxf
37,117
core/src/main/java/org/apache/cxf/ws/addressing/EndpointReferenceUtils.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.ws.addressing; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.InputSource; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBElement; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.common.jaxb.JAXBContextCache; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.xmlschema.LSInputImpl; import org.apache.cxf.endpoint.EndpointResolverRegistry; import org.apache.cxf.endpoint.Server; import org.apache.cxf.endpoint.ServerRegistry; import org.apache.cxf.helpers.IOUtils; import org.apache.cxf.helpers.LoadingByteArrayOutputStream; import org.apache.cxf.resource.ExtendedURIResolver; import org.apache.cxf.resource.ResourceManager; import org.apache.cxf.service.model.SchemaInfo; import org.apache.cxf.service.model.ServiceInfo; import org.apache.cxf.staxutils.StaxUtils; import org.apache.cxf.staxutils.W3CDOMStreamWriter; import org.apache.cxf.transport.Destination; import org.apache.cxf.transport.MultiplexDestination; import org.apache.cxf.ws.addressing.wsdl.AttributedQNameType; import org.apache.cxf.ws.addressing.wsdl.ServiceNameType; import org.apache.ws.commons.schema.XmlSchema; /** * Provides utility methods for obtaining endpoint references, wsdl definitions, etc. */ public final class EndpointReferenceUtils { /** * We want to load the schemas, including references to external schemas, into a SchemaFactory * to validate. There seem to be bugs in resolving inter-schema references in Xerces, so even when we are * handing the factory all the schemas, interrelated with &lt;import&gt; elements, we need * to also hand over extra copies (!) as character images when requested. * * To do this, we use the DOM representation kept in the SchemaInfo. This has the bonus * of benefiting from the use of the catalog resolver in there, which is missing from * the code in here. */ private static final class SchemaLSResourceResolver implements LSResourceResolver { private final Map<String, byte[]> schemas; private final Set<String> done = new HashSet<>(); private final ExtendedURIResolver resolver = new ExtendedURIResolver(); private final Bus bus; private SchemaLSResourceResolver(Map<String, byte[]> schemas, Bus b) { this.schemas = schemas; this.bus = b; } public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { String newId = systemId; if (baseURI != null && systemId != null) { //add additional systemId null check try { URI uri = new URI(baseURI); uri = uri.resolve(systemId); newId = uri.toString(); if (newId.equals(systemId)) { URL url = new URL(baseURI); url = new URL(url, systemId); newId = url.toExternalForm(); } } catch (IllegalArgumentException e) { //ignore - systemId not a valid URI } catch (URISyntaxException e) { //ignore - baseURI not a valid URI } catch (MalformedURLException e) { //ignore - baseURI or systemId not a URL either } } LSInputImpl impl = null; if (done.contains(newId + ":" + namespaceURI)) { return null; } if (schemas.containsKey(newId + ":" + namespaceURI)) { byte[] ds = schemas.remove(newId + ":" + namespaceURI); impl = createInput(newId, ds); done.add(newId + ":" + namespaceURI); } if (impl == null && schemas.containsKey(newId + ":null")) { byte[] ds = schemas.get(newId + ":null"); impl = createInput(newId, ds); done.add(newId + ":" + namespaceURI); } if (impl == null && bus != null && systemId != null) { ResourceManager rm = bus.getExtension(ResourceManager.class); URL url = rm == null ? null : rm.resolveResource(systemId, URL.class); if (url != null) { newId = url.toString(); if (done.contains(newId + ":" + namespaceURI)) { return null; } if (schemas.containsKey(newId + ":" + namespaceURI)) { byte[] ds = schemas.remove(newId + ":" + namespaceURI); impl = createInput(newId, ds); done.add(newId + ":" + namespaceURI); } } } if (impl == null) { for (Map.Entry<String, byte[]> ent : schemas.entrySet()) { if (ent.getKey().endsWith(systemId + ":" + namespaceURI)) { schemas.remove(ent.getKey()); impl = createInput(newId, ent.getValue()); done.add(newId + ":" + namespaceURI); return impl; } } // there can be multiple includes on the same namespace. This scenario is not envisioned yet. // hence the filename part is included as well. if (systemId != null) { String systemIdFileName = systemId.substring(systemId.lastIndexOf('/') + 1); for (Map.Entry<String, byte[]> ent : schemas.entrySet()) { if (ent.getKey().endsWith(systemIdFileName + ":" + namespaceURI)) { schemas.remove(ent.getKey()); impl = createInput(newId, ent.getValue()); done.add(newId + ":" + namespaceURI); return impl; } } } // handle case where given systemId is null (so that // direct key lookup fails) by scanning through map // searching for a namespace match if (namespaceURI != null) { for (Map.Entry<String, byte[]> ent : schemas.entrySet()) { if (ent.getKey().endsWith(":" + namespaceURI)) { schemas.remove(ent.getKey()); impl = createInput(newId, ent.getValue()); done.add(newId + ":" + namespaceURI); return impl; } } } //REVIST - we need to get catalogs in here somehow :-( if (systemId == null) { systemId = publicId; } if (systemId != null) { InputSource source = resolver.resolve(systemId, baseURI); if (source != null) { impl = new LSInputImpl(); impl.setByteStream(source.getByteStream()); impl.setSystemId(source.getSystemId()); impl.setPublicId(source.getPublicId()); return impl; } } LOG.warning("Could not resolve Schema for " + systemId); } return impl; } private LSInputImpl createInput(String newId, byte[] value) { LSInputImpl impl = new LSInputImpl(); impl.setSystemId(newId); impl.setBaseURI(newId); impl.setByteStream(new ByteArrayInputStream(value)); return impl; } } public static final String ANONYMOUS_ADDRESS = "http://www.w3.org/2005/08/addressing/anonymous"; private static final Logger LOG = LogUtils.getL7dLogger(EndpointReferenceUtils.class); private static final String NS_WSAW_2005 = "http://www.w3.org/2005/02/addressing/wsdl"; private static final String WSDL_INSTANCE_NAMESPACE2 = "http://www.w3.org/2006/01/wsdl-instance"; private static final String WSDL_INSTANCE_NAMESPACE = "http://www.w3.org/ns/wsdl-instance"; private static final QName WSA_WSDL_NAMESPACE_NS = new QName("xmlns:" + JAXWSAConstants.WSAW_PREFIX); private static final String XML_SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"; private static final String XML_SCHEMA_NAMESPACE_PREFIX = "xs"; private static final QName XML_SCHEMA_NAMESPACE_NS = new QName("xmlns:" + XML_SCHEMA_NAMESPACE_PREFIX); private static final String XML_SCHEMA_INSTANCE_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"; private static final QName WSDL_LOCATION2 = new QName(WSDL_INSTANCE_NAMESPACE2, "wsdlLocation"); private static final QName WSDL_LOCATION = new QName(WSDL_INSTANCE_NAMESPACE, "wsdlLocation"); private static final QName XSI_TYPE = new QName(XML_SCHEMA_INSTANCE_NAMESPACE, "type", "xsi"); private static final org.apache.cxf.ws.addressing.wsdl.ObjectFactory WSA_WSDL_OBJECT_FACTORY = new org.apache.cxf.ws.addressing.wsdl.ObjectFactory(); private static final Set<Class<?>> ADDRESSING_CLASSES = new HashSet<>(); private static final AtomicReference<Reference<JAXBContext>> ADDRESSING_CONTEXT = new AtomicReference<>(new SoftReference<JAXBContext>(null)); static { ADDRESSING_CLASSES.add(WSA_WSDL_OBJECT_FACTORY.getClass()); ADDRESSING_CLASSES.add(org.apache.cxf.ws.addressing.ObjectFactory.class); } private EndpointReferenceUtils() { // Utility class - never constructed } /** * Sets the service and port name of the provided endpoint reference. * @param ref the endpoint reference. * @param serviceName the name of service. * @param portName the port name. */ public static void setServiceAndPortName(EndpointReferenceType ref, QName serviceName, String portName) { if (null != serviceName) { JAXBElement<ServiceNameType> jaxbElement = getServiceNameType(serviceName, portName); MetadataType mt = getSetMetadata(ref); mt.getAny().add(jaxbElement); } } public static MetadataType getSetMetadata(EndpointReferenceType ref) { MetadataType mt = ref.getMetadata(); if (null == mt) { mt = new MetadataType(); ref.setMetadata(mt); } return mt; } public static JAXBElement<ServiceNameType> getServiceNameType(QName serviceName, String portName) { ServiceNameType serviceNameType = WSA_WSDL_OBJECT_FACTORY.createServiceNameType(); serviceNameType.setValue(serviceName); serviceNameType.setEndpointName(portName); serviceNameType.getOtherAttributes().put(WSA_WSDL_NAMESPACE_NS, JAXWSAConstants.NS_WSAW); serviceNameType.getOtherAttributes().put(XSI_TYPE, JAXWSAConstants.WSAW_PREFIX + ":" + serviceNameType.getClass().getSimpleName()); return WSA_WSDL_OBJECT_FACTORY.createServiceName(serviceNameType); } /** * Gets the service name of the provided endpoint reference. * @param ref the endpoint reference. * @return the service name. */ public static QName getServiceName(EndpointReferenceType ref, Bus bus) { MetadataType metadata = ref.getMetadata(); if (metadata == null) { return null; } for (Object obj : metadata.getAny()) { if (obj instanceof Element) { Node node = (Element)obj; if ((node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAW) || node.getNamespaceURI().equals(NS_WSAW_2005) || node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAM)) && "ServiceName".equals(node.getLocalName())) { String content = node.getTextContent(); String namespaceURI = node.getFirstChild().getNamespaceURI(); String service = content; if (content.contains(":")) { namespaceURI = getNameSpaceUri(node, content, namespaceURI); service = getService(content); } else { Node nodeAttr = node.getAttributes().getNamedItem("xmlns"); namespaceURI = nodeAttr.getNodeValue(); } return new QName(namespaceURI, service); } } else if (obj instanceof JAXBElement) { Object val = ((JAXBElement<?>)obj).getValue(); if (val instanceof ServiceNameType) { return ((ServiceNameType)val).getValue(); } } else if (obj instanceof ServiceNameType) { return ((ServiceNameType)obj).getValue(); } } return null; } /** * Gets the port name of the provided endpoint reference. * @param ref the endpoint reference. * @return the port name. */ public static String getPortName(EndpointReferenceType ref) { MetadataType metadata = ref.getMetadata(); if (metadata != null) { for (Object obj : metadata.getAny()) { if (obj instanceof Element) { Node node = (Element)obj; if ((node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAW) || node.getNamespaceURI().equals(NS_WSAW_2005) || node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAM)) && node.getNodeName().contains("ServiceName")) { Node item = node.getAttributes().getNamedItem("EndpointName"); return item != null ? item.getTextContent() : null; } } else if (obj instanceof JAXBElement) { Object val = ((JAXBElement<?>)obj).getValue(); if (val instanceof ServiceNameType) { return ((ServiceNameType)val).getEndpointName(); } } else if (obj instanceof ServiceNameType) { return ((ServiceNameType)obj).getEndpointName(); } } } return null; } public static QName getPortQName(EndpointReferenceType ref, Bus bus) { QName serviceName = getServiceName(ref, bus); return new QName(serviceName.getNamespaceURI(), getPortName(ref)); } public static void setPortName(EndpointReferenceType ref, String portName) { MetadataType metadata = ref.getMetadata(); if (metadata != null) { for (Object obj : metadata.getAny()) { if (obj instanceof Element) { Element node = (Element)obj; if (node.getNodeName().contains("ServiceName") && (node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAW) || node.getNamespaceURI().equals(NS_WSAW_2005) || node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAM))) { node.setAttribute(JAXWSAConstants.WSAM_ENDPOINT_NAME, portName); } } else if (obj instanceof JAXBElement) { Object val = ((JAXBElement<?>)obj).getValue(); if (val instanceof ServiceNameType) { ((ServiceNameType)val).setEndpointName(portName); } } else if (obj instanceof ServiceNameType) { ((ServiceNameType)obj).setEndpointName(portName); } } } } public static void setInterfaceName(EndpointReferenceType ref, QName portTypeName) { if (null != portTypeName) { AttributedQNameType interfaceNameType = WSA_WSDL_OBJECT_FACTORY.createAttributedQNameType(); interfaceNameType.setValue(portTypeName); interfaceNameType.getOtherAttributes().put(XML_SCHEMA_NAMESPACE_NS, XML_SCHEMA_NAMESPACE); interfaceNameType.getOtherAttributes().put(XSI_TYPE, XML_SCHEMA_NAMESPACE_PREFIX + ":" + portTypeName.getClass().getSimpleName()); JAXBElement<AttributedQNameType> jaxbElement = WSA_WSDL_OBJECT_FACTORY.createInterfaceName(interfaceNameType); MetadataType mt = getSetMetadata(ref); mt.getAny().add(jaxbElement); } } public static QName getInterfaceName(EndpointReferenceType ref, Bus bus) { MetadataType metadata = ref.getMetadata(); if (metadata == null) { return null; } for (Object obj : metadata.getAny()) { if (obj instanceof Element) { Node node = (Element)obj; if ((node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAW) || node.getNamespaceURI().equals(JAXWSAConstants.NS_WSAM)) && node.getNodeName().contains("InterfaceName")) { String content = node.getTextContent(); String namespaceURI = node.getFirstChild().getNamespaceURI(); //String service = content; if (content.contains(":")) { namespaceURI = getNameSpaceUri(node, content, namespaceURI); content = getService(content); } else { Node nodeAttr = node.getAttributes().getNamedItem("xmlns"); namespaceURI = nodeAttr.getNodeValue(); } return new QName(namespaceURI, content); } } else if (obj instanceof JAXBElement) { Object val = ((JAXBElement<?>)obj).getValue(); if (val instanceof AttributedQNameType) { return ((AttributedQNameType)val).getValue(); } } else if (obj instanceof AttributedQNameType) { return ((AttributedQNameType)obj).getValue(); } } return null; } public static void setWSDLLocation(EndpointReferenceType ref, String... wsdlLocation) { MetadataType metadata = getSetMetadata(ref); //wsdlLocation attribute is a list of anyURI. metadata.getOtherAttributes().put(WSDL_LOCATION, String.join(" ", wsdlLocation).trim()); } public static String getWSDLLocation(EndpointReferenceType ref) { String wsdlLocation = null; MetadataType metadata = ref.getMetadata(); if (metadata != null) { wsdlLocation = metadata.getOtherAttributes().get(WSDL_LOCATION); if (wsdlLocation == null) { wsdlLocation = metadata.getOtherAttributes().get(WSDL_LOCATION2); } } if (null == wsdlLocation) { return null; } return wsdlLocation; } private static Schema createSchema(ServiceInfo serviceInfo, Bus b) { Schema schema = serviceInfo.getProperty(Schema.class.getName(), Schema.class); if (schema == null) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Map<String, byte[]> schemaSourcesMap = new LinkedHashMap<>(); Map<String, Source> schemaSourcesMap2 = new LinkedHashMap<>(); XMLStreamWriter writer = null; try { for (SchemaInfo si : serviceInfo.getSchemas()) { Element el = si.getElement(); String baseURI = null; try { baseURI = el.getBaseURI(); } catch (Exception ex) { //ignore - not DOM level 3 } if (baseURI == null) { baseURI = si.getSystemId(); } DOMSource ds = new DOMSource(el, baseURI); schemaSourcesMap2.put(si.getSystemId() + ':' + si.getNamespaceURI(), ds); LoadingByteArrayOutputStream out = new LoadingByteArrayOutputStream(); writer = StaxUtils.createXMLStreamWriter(out); StaxUtils.copy(el, writer); writer.flush(); schemaSourcesMap.put(si.getSystemId() + ':' + si.getNamespaceURI(), out.toByteArray()); } for (XmlSchema sch : serviceInfo.getXmlSchemaCollection().getXmlSchemas()) { if (sch.getSourceURI() != null && !schemaSourcesMap.containsKey(sch.getSourceURI() + ':' + sch.getTargetNamespace())) { InputStream ins = null; try { URL url = new URL(sch.getSourceURI()); ins = url.openStream(); } catch (Exception e) { //ignore, we'll just use what we have. (though //bugs in XmlSchema could make this less useful) } LoadingByteArrayOutputStream out = new LoadingByteArrayOutputStream(); if (ins == null) { sch.write(out); } else { IOUtils.copyAndCloseInput(ins, out); } schemaSourcesMap.put(sch.getSourceURI() + ':' + sch.getTargetNamespace(), out.toByteArray()); Source source = new StreamSource(out.createInputStream(), sch.getSourceURI()); schemaSourcesMap2.put(sch.getSourceURI() + ':' + sch.getTargetNamespace(), source); } } factory.setResourceResolver(new SchemaLSResourceResolver(schemaSourcesMap, b != null ? b : BusFactory.getThreadDefaultBus(false))); schema = factory.newSchema(schemaSourcesMap2.values() .toArray(new Source[schemaSourcesMap2.size()])); } catch (Exception ex) { // Something not right with the schema from the wsdl. LOG.log(Level.WARNING, "SAXException for newSchema()", ex); for (SchemaInfo schemaInfo : serviceInfo.getSchemas()) { String s = StaxUtils.toString(schemaInfo.getElement(), 4); LOG.log(Level.INFO, "Schema for: " + schemaInfo.getNamespaceURI() + "\n" + s); } } finally { StaxUtils.close(writer); } serviceInfo.setProperty(Schema.class.getName(), schema); } return schema; } public static Schema getSchema(ServiceInfo serviceInfo) { return getSchema(serviceInfo, null); } public static Schema getSchema(ServiceInfo serviceInfo, Bus b) { if (serviceInfo == null) { return null; } Schema schema = serviceInfo.getProperty(Schema.class.getName(), Schema.class); if (schema == null && !serviceInfo.hasProperty(Schema.class.getName() + ".CHECKED")) { try { synchronized (serviceInfo) { return createSchema(serviceInfo, b); } } finally { serviceInfo.setProperty(Schema.class.getName() + ".CHECKED", Boolean.TRUE); } } return schema; } /** * Get the address from the provided endpoint reference. * @param ref - the endpoint reference * @return String the address of the endpoint */ public static String getAddress(EndpointReferenceType ref) { AttributedURIType a = ref.getAddress(); if (null != a) { return a.getValue(); } return null; } /** * Set the address of the provided endpoint reference. * @param ref - the endpoint reference * @param address - the address */ public static void setAddress(EndpointReferenceType ref, String address) { AttributedURIType a = new AttributedURIType(); a.setValue(address); ref.setAddress(a); } /** * Create an endpoint reference for the provided wsdl, service and portname. * @param wsdlUrl - url of the wsdl that describes the service. * @param serviceName - the <code>QName</code> of the service. * @param portName - the name of the port. * @return EndpointReferenceType - the endpoint reference */ public static EndpointReferenceType getEndpointReference(URL wsdlUrl, QName serviceName, String portName) { EndpointReferenceType reference = new EndpointReferenceType(); reference.setMetadata(new MetadataType()); setServiceAndPortName(reference, serviceName, portName); setWSDLLocation(reference, wsdlUrl.toString()); return reference; } /** * Create a duplicate endpoint reference sharing all atributes * @param ref the reference to duplicate * @return EndpointReferenceType - the duplicate endpoint reference */ public static EndpointReferenceType duplicate(EndpointReferenceType ref) { EndpointReferenceType reference = new EndpointReferenceType(); reference.setMetadata(ref.getMetadata()); reference.getAny().addAll(ref.getAny()); reference.setAddress(ref.getAddress()); return reference; } /** * Create an endpoint reference for the provided address. * @param address - address URI * @return EndpointReferenceType - the endpoint reference */ public static EndpointReferenceType getEndpointReference(String address) { EndpointReferenceType reference = new EndpointReferenceType(); setAddress(reference, address); return reference; } public static EndpointReferenceType getEndpointReference(AttributedURIType address) { EndpointReferenceType reference = new EndpointReferenceType(); reference.setAddress(address); return reference; } /** * Create an anonymous endpoint reference. * @return EndpointReferenceType - the endpoint reference */ public static EndpointReferenceType getAnonymousEndpointReference() { final EndpointReferenceType reference = new EndpointReferenceType(); setAddress(reference, ANONYMOUS_ADDRESS); return reference; } /** * Resolve logical endpoint reference via the Bus EndpointResolverRegistry. * * @param logical the abstract EPR to resolve * @return the resolved concrete EPR if appropriate, null otherwise */ public static EndpointReferenceType resolve(EndpointReferenceType logical, Bus bus) { EndpointReferenceType physical = null; if (bus != null) { EndpointResolverRegistry registry = bus.getExtension(EndpointResolverRegistry.class); if (registry != null) { physical = registry.resolve(logical); } } return physical != null ? physical : logical; } /** * Renew logical endpoint reference via the Bus EndpointResolverRegistry. * * @param logical the original abstract EPR (if still available) * @param physical the concrete EPR to renew * @return the renewed concrete EPR if appropriate, null otherwise */ public static EndpointReferenceType renew(EndpointReferenceType logical, EndpointReferenceType physical, Bus bus) { EndpointReferenceType renewed = null; if (bus != null) { EndpointResolverRegistry registry = bus.getExtension(EndpointResolverRegistry.class); if (registry != null) { renewed = registry.renew(logical, physical); } } return renewed != null ? renewed : physical; } /** * Mint logical endpoint reference via the Bus EndpointResolverRegistry. * * @param serviceName the given serviceName * @return the newly minted EPR if appropriate, null otherwise */ public static EndpointReferenceType mint(QName serviceName, Bus bus) { EndpointReferenceType logical = null; if (bus != null) { EndpointResolverRegistry registry = bus.getExtension(EndpointResolverRegistry.class); if (registry != null) { logical = registry.mint(serviceName); } } return logical; } /** * Mint logical endpoint reference via the Bus EndpointResolverRegistry. * * @param physical the concrete template EPR * @return the newly minted EPR if appropriate, null otherwise */ public static EndpointReferenceType mint(EndpointReferenceType physical, Bus bus) { EndpointReferenceType logical = null; if (bus != null) { EndpointResolverRegistry registry = bus.getExtension(EndpointResolverRegistry.class); if (registry != null) { logical = registry.mint(physical); } } return logical != null ? logical : physical; } private static String getNameSpaceUri(Node node, String content, String namespaceURI) { if (namespaceURI == null) { namespaceURI = node.lookupNamespaceURI(content.substring(0, content.indexOf(':'))); } return namespaceURI; } private static String getService(String content) { return content.substring(content.indexOf(':') + 1, content.length()); } /** * Obtain a multiplexed endpoint reference for the deployed service that contains the provided id * @param serviceQName identified the target service * @param portName identifies a particular port of the service, may be null * @param id that must be embedded in the returned reference * @param bus the current bus * @return a new reference or null if the target destination does not support destination mutiplexing */ public static EndpointReferenceType getEndpointReferenceWithId(QName serviceQName, String portName, String id, Bus bus) { EndpointReferenceType epr = null; MultiplexDestination destination = getMatchingMultiplexDestination(serviceQName, portName, bus); if (null != destination) { epr = destination.getAddressWithId(id); } return epr; } /** * Obtain the id String from the endpoint reference of the current dispatch. * @param messageContext the current message context * @return the id embedded in the current endpoint reference or null if not found */ public static String getEndpointReferenceId(Map<String, Object> messageContext) { String id = null; Destination destination = (Destination) messageContext.get(Destination.class.getName()); if (destination instanceof MultiplexDestination) { id = ((MultiplexDestination) destination).getId(messageContext); } return id; } private static synchronized JAXBContext createContextForEPR() throws JAXBException { Reference<JAXBContext> rctx = ADDRESSING_CONTEXT.get(); JAXBContext ctx = rctx.get(); if (ctx == null) { ctx = JAXBContextCache.getCachedContextAndSchemas(ADDRESSING_CLASSES, null, null, null, true).getContext(); ADDRESSING_CONTEXT.set(new SoftReference<JAXBContext>(ctx)); } return ctx; } private static JAXBContext getJAXBContextForEPR() throws JAXBException { Reference<JAXBContext> rctx = ADDRESSING_CONTEXT.get(); JAXBContext ctx = rctx.get(); if (ctx == null) { ctx = createContextForEPR(); } return ctx; } public static Source convertToXML(EndpointReferenceType epr) { try { Marshaller jm = getJAXBContextForEPR().createMarshaller(); jm.setProperty(Marshaller.JAXB_FRAGMENT, true); QName qname = new QName("http://www.w3.org/2005/08/addressing", "EndpointReference"); JAXBElement<EndpointReferenceType> jaxEle = new JAXBElement<>(qname, EndpointReferenceType.class, epr); W3CDOMStreamWriter writer = new W3CDOMStreamWriter(); jm.marshal(jaxEle, writer); return new DOMSource(writer.getDocument()); } catch (JAXBException e) { //ignore } return null; } private static MultiplexDestination getMatchingMultiplexDestination(QName serviceQName, String portName, Bus bus) { MultiplexDestination destination = null; ServerRegistry serverRegistry = bus.getExtension(ServerRegistry.class); if (null != serverRegistry) { List<Server> servers = serverRegistry.getServers(); for (Server s : servers) { QName targetServiceQName = s.getEndpoint().getEndpointInfo().getService().getName(); if (serviceQName.equals(targetServiceQName) && portNameMatches(s, portName)) { Destination dest = s.getDestination(); if (dest instanceof MultiplexDestination) { destination = (MultiplexDestination)dest; break; } } } } else { LOG.log(Level.WARNING, "Failed to locate service matching " + serviceQName + ", because the bus ServerRegistry extension provider is null"); } return destination; } private static boolean portNameMatches(Server s, String portName) { return null == portName || portName.equals(s.getEndpoint().getEndpointInfo().getName().getLocalPart()); } }
apache/pinot
36,907
pinot-spi/src/main/java/org/apache/pinot/spi/data/Schema.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.spi.data; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Preconditions; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang3.tuple.Pair; import org.apache.pinot.spi.data.FieldSpec.DataType; import org.apache.pinot.spi.data.FieldSpec.FieldType; import org.apache.pinot.spi.utils.EqualityUtils; import org.apache.pinot.spi.utils.JsonUtils; import org.apache.pinot.spi.utils.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <code>Schema</code> class is defined for each table to describe the details of the table's fields (columns). * <p>Four field types are supported: DIMENSION, METRIC, TIME, DATE_TIME. * ({@link DimensionFieldSpec}, {@link MetricFieldSpec}, * {@link TimeFieldSpec}, {@link DateTimeFieldSpec}) * <p>For each field, a {@link FieldSpec} is defined to provide the details of the field. * <p>There could be multiple DIMENSION or METRIC or DATE_TIME fields, but at most 1 TIME field. * <p>In pinot, we store data using 5 <code>DataType</code>s: INT, LONG, FLOAT, DOUBLE, STRING. All other * <code>DataType</code>s will be converted to one of them. */ @SuppressWarnings("unused") @JsonIgnoreProperties(ignoreUnknown = true) public final class Schema implements Serializable { private static final Logger LOGGER = LoggerFactory.getLogger(Schema.class); private String _schemaName; private boolean _enableColumnBasedNullHandling; private final List<DimensionFieldSpec> _dimensionFieldSpecs = new ArrayList<>(); private final List<MetricFieldSpec> _metricFieldSpecs = new ArrayList<>(); private TimeFieldSpec _timeFieldSpec; private final List<DateTimeFieldSpec> _dateTimeFieldSpecs = new ArrayList<>(); private final List<ComplexFieldSpec> _complexFieldSpecs = new ArrayList<>(); // names of the columns that used as primary keys // TODO(yupeng): add validation checks like duplicate columns and use of time column @Nullable private List<String> _primaryKeyColumns; // Json ignored fields // NOTE: Use TreeMap so that the columns are ordered alphabetically private final TreeMap<String, FieldSpec> _fieldSpecMap = new TreeMap<>(); private final List<String> _dimensionNames = new ArrayList<>(); private final List<String> _metricNames = new ArrayList<>(); private final List<String> _dateTimeNames = new ArrayList<>(); private final List<String> _complexNames = new ArrayList<>(); // Set to true if this schema has a JSON column (used to quickly decide whether to run JsonStatementOptimizer on // queries or not). private boolean _hasJSONColumn; public static Schema fromFile(File schemaFile) throws IOException { return JsonUtils.fileToObject(schemaFile, Schema.class); } public static Schema fromString(String schemaString) throws IOException { return JsonUtils.stringToObject(schemaString, Schema.class); } public static Pair<Schema, Map<String, Object>> parseSchemaAndUnrecognizedPropsfromInputStream( InputStream schemaInputStream) throws IOException { return JsonUtils.inputStreamToObjectAndUnrecognizedProperties(schemaInputStream, Schema.class); } public static Schema fromInputStream(InputStream schemaInputStream) throws IOException { return JsonUtils.inputStreamToObject(schemaInputStream, Schema.class); } public static void validate(FieldType fieldType, DataType dataType) { switch (fieldType) { case DIMENSION: case TIME: case DATE_TIME: switch (dataType) { case INT: case LONG: case FLOAT: case DOUBLE: case BIG_DECIMAL: case BOOLEAN: case TIMESTAMP: case STRING: case JSON: case BYTES: break; default: throw new IllegalStateException( "Unsupported data type: " + dataType + " in DIMENSION/TIME field"); } break; case METRIC: switch (dataType) { case INT: case LONG: case FLOAT: case DOUBLE: case BIG_DECIMAL: case BYTES: break; default: throw new IllegalStateException("Unsupported data type: " + dataType + " in METRIC field"); } break; case COMPLEX: switch (dataType) { case STRUCT: case MAP: case LIST: break; default: throw new IllegalStateException("Unsupported data type: " + dataType + " in COMPLEX field"); } break; default: throw new IllegalStateException("Unsupported data type: " + dataType + " for field"); } } /** * NOTE: schema name could be null in tests */ public String getSchemaName() { return _schemaName; } public void setSchemaName(String schemaName) { _schemaName = schemaName; } public boolean isEnableColumnBasedNullHandling() { return _enableColumnBasedNullHandling; } public void setEnableColumnBasedNullHandling(boolean enableColumnBasedNullHandling) { _enableColumnBasedNullHandling = enableColumnBasedNullHandling; } @Nullable public List<String> getPrimaryKeyColumns() { return _primaryKeyColumns; } public void setPrimaryKeyColumns(List<String> primaryKeyColumns) { _primaryKeyColumns = primaryKeyColumns; } public List<DimensionFieldSpec> getDimensionFieldSpecs() { return _dimensionFieldSpecs; } /** * Required by JSON deserializer. DO NOT USE. DO NOT REMOVE. * Adding @Deprecated to prevent usage */ @Deprecated public void setDimensionFieldSpecs(List<DimensionFieldSpec> dimensionFieldSpecs) { Preconditions.checkState(_dimensionFieldSpecs.isEmpty()); for (DimensionFieldSpec dimensionFieldSpec : dimensionFieldSpecs) { addField(dimensionFieldSpec); } } public List<MetricFieldSpec> getMetricFieldSpecs() { return _metricFieldSpecs; } /** * Required by JSON deserializer. DO NOT USE. DO NOT REMOVE. * Adding @Deprecated to prevent usage */ @Deprecated public void setMetricFieldSpecs(List<MetricFieldSpec> metricFieldSpecs) { Preconditions.checkState(_metricFieldSpecs.isEmpty()); for (MetricFieldSpec metricFieldSpec : metricFieldSpecs) { addField(metricFieldSpec); } } public List<DateTimeFieldSpec> getDateTimeFieldSpecs() { return _dateTimeFieldSpecs; } /** * Required by JSON deserializer. DO NOT USE. DO NOT REMOVE. * Adding @Deprecated to prevent usage */ @Deprecated public void setDateTimeFieldSpecs(List<DateTimeFieldSpec> dateTimeFieldSpecs) { Preconditions.checkState(_dateTimeFieldSpecs.isEmpty()); for (DateTimeFieldSpec dateTimeFieldSpec : dateTimeFieldSpecs) { addField(dateTimeFieldSpec); } } public TimeFieldSpec getTimeFieldSpec() { return _timeFieldSpec; } /** * Required by JSON deserializer. DO NOT USE. DO NOT REMOVE. * Adding @Deprecated to prevent usage */ @Deprecated public void setTimeFieldSpec(TimeFieldSpec timeFieldSpec) { if (timeFieldSpec != null) { addField(timeFieldSpec); } } public List<ComplexFieldSpec> getComplexFieldSpecs() { return _complexFieldSpecs; } /** * Required by JSON deserializer. DO NOT USE. DO NOT REMOVE. * Adding @Deprecated to prevent usage */ @Deprecated public void setComplexFieldSpecs(List<ComplexFieldSpec> complexFieldSpecs) { Preconditions.checkState(_complexFieldSpecs.isEmpty()); for (ComplexFieldSpec complexFieldSpec : complexFieldSpecs) { addField(complexFieldSpec); } } public void addField(FieldSpec fieldSpec) { Preconditions.checkNotNull(fieldSpec); String columnName = fieldSpec.getName(); Preconditions.checkNotNull(columnName); Preconditions.checkState(!_fieldSpecMap.containsKey(columnName), "Field spec already exists for column: " + columnName); FieldType fieldType = fieldSpec.getFieldType(); switch (fieldType) { case DIMENSION: _dimensionNames.add(columnName); _dimensionFieldSpecs.add((DimensionFieldSpec) fieldSpec); break; case METRIC: _metricNames.add(columnName); _metricFieldSpecs.add((MetricFieldSpec) fieldSpec); break; case TIME: _timeFieldSpec = (TimeFieldSpec) fieldSpec; break; case DATE_TIME: _dateTimeNames.add(columnName); _dateTimeFieldSpecs.add((DateTimeFieldSpec) fieldSpec); break; case COMPLEX: _complexNames.add(columnName); _complexFieldSpecs.add((ComplexFieldSpec) fieldSpec); break; default: throw new UnsupportedOperationException("Unsupported field type: " + fieldType); } _hasJSONColumn |= fieldSpec.getDataType().equals(DataType.JSON); _fieldSpecMap.put(columnName, fieldSpec); } @Deprecated // For third-eye backward compatible. public void addField(String columnName, FieldSpec fieldSpec) { addField(fieldSpec); } public boolean removeField(String columnName) { FieldSpec existingFieldSpec = _fieldSpecMap.remove(columnName); if (existingFieldSpec != null) { FieldType fieldType = existingFieldSpec.getFieldType(); switch (fieldType) { case DIMENSION: int index = _dimensionNames.indexOf(columnName); _dimensionNames.remove(index); _dimensionFieldSpecs.remove(index); break; case METRIC: index = _metricNames.indexOf(columnName); _metricNames.remove(index); _metricFieldSpecs.remove(index); break; case TIME: _timeFieldSpec = null; break; case DATE_TIME: index = _dateTimeNames.indexOf(columnName); _dateTimeNames.remove(index); _dateTimeFieldSpecs.remove(index); break; case COMPLEX: index = _complexNames.indexOf(columnName); _complexNames.remove(index); _complexFieldSpecs.remove(index); break; default: throw new UnsupportedOperationException("Unsupported field type: " + fieldType); } return true; } else { return false; } } public boolean hasColumn(String columnName) { return _fieldSpecMap.containsKey(columnName); } @JsonIgnore public boolean hasJSONColumn() { return _hasJSONColumn; } @JsonIgnore public TreeMap<String, FieldSpec> getFieldSpecMap() { return _fieldSpecMap; } @JsonIgnore public NavigableSet<String> getColumnNames() { return _fieldSpecMap.navigableKeySet(); } @JsonIgnore public TreeSet<String> getPhysicalColumnNames() { TreeSet<String> physicalColumnNames = new TreeSet<>(); for (FieldSpec fieldSpec : _fieldSpecMap.values()) { if (!fieldSpec.isVirtualColumn()) { physicalColumnNames.add(fieldSpec.getName()); } } return physicalColumnNames; } /** * Returns a new schema containing only physical columns. * * All properties but the fields are the same. * All field attributes are a shallow copy without the virtual column. */ public Schema withoutVirtualColumns() { Schema newSchema = new Schema(); newSchema.setSchemaName(getSchemaName()); newSchema.setEnableColumnBasedNullHandling(isEnableColumnBasedNullHandling()); List<String> primaryKeyColumns = getPrimaryKeyColumns(); if (primaryKeyColumns != null) { newSchema.setPrimaryKeyColumns(primaryKeyColumns.stream() .filter(primaryKey -> { FieldSpec fieldSpec = _fieldSpecMap.get(primaryKey); return fieldSpec != null && !fieldSpec.isVirtualColumn(); }) .collect(Collectors.toList()) ); } for (FieldSpec fieldSpec : getAllFieldSpecs()) { if (!fieldSpec.isVirtualColumn()) { newSchema.addField(fieldSpec); } } return newSchema; } /** * NOTE: The returned FieldSpecs are sorted with the column name alphabetically. */ @JsonIgnore public Collection<FieldSpec> getAllFieldSpecs() { return _fieldSpecMap.values(); } public int size() { return _fieldSpecMap.size(); } @JsonIgnore public FieldSpec getFieldSpecFor(String columnName) { return _fieldSpecMap.get(columnName); } @JsonIgnore public MetricFieldSpec getMetricSpec(String metricName) { FieldSpec fieldSpec = _fieldSpecMap.get(metricName); if (fieldSpec != null && fieldSpec.getFieldType() == FieldType.METRIC) { return (MetricFieldSpec) fieldSpec; } return null; } @JsonIgnore public DimensionFieldSpec getDimensionSpec(String dimensionName) { FieldSpec fieldSpec = _fieldSpecMap.get(dimensionName); if (fieldSpec != null && fieldSpec.getFieldType() == FieldType.DIMENSION) { return (DimensionFieldSpec) fieldSpec; } return null; } @JsonIgnore public DateTimeFieldSpec getDateTimeSpec(String dateTimeName) { FieldSpec fieldSpec = _fieldSpecMap.get(dateTimeName); if (fieldSpec != null && fieldSpec.getFieldType() == FieldType.DATE_TIME) { return (DateTimeFieldSpec) fieldSpec; } return null; } @JsonIgnore public ComplexFieldSpec getComplexSpec(String complexName) { FieldSpec fieldSpec = _fieldSpecMap.get(complexName); if (fieldSpec != null && fieldSpec.getFieldType() == FieldType.COMPLEX) { return (ComplexFieldSpec) fieldSpec; } return null; } /** * Fetches the DateTimeFieldSpec for the given time column name. * If the columnName is a DATE_TIME column, returns the DateTimeFieldSpec * If the columnName is a TIME column, converts to DateTimeFieldSpec before returning */ @JsonIgnore @Nullable public DateTimeFieldSpec getSpecForTimeColumn(String timeColumnName) { FieldSpec fieldSpec = _fieldSpecMap.get(timeColumnName); if (fieldSpec != null) { if (fieldSpec.getFieldType() == FieldType.DATE_TIME) { return (DateTimeFieldSpec) fieldSpec; } if (fieldSpec.getFieldType() == FieldType.TIME) { return convertToDateTimeFieldSpec((TimeFieldSpec) fieldSpec); } } return null; } @JsonIgnore public List<String> getDimensionNames() { return _dimensionNames; } @JsonIgnore public List<String> getMetricNames() { return _metricNames; } @JsonIgnore public List<String> getDateTimeNames() { return _dateTimeNames; } @JsonIgnore public List<String> getComplexNames() { return _complexNames; } /** * Returns a json representation of the schema. */ public ObjectNode toJsonObject() { ObjectNode jsonObject = JsonUtils.newObjectNode(); jsonObject.put("schemaName", _schemaName); jsonObject.set("enableColumnBasedNullHandling", JsonUtils.objectToJsonNode(_enableColumnBasedNullHandling)); if (!_dimensionFieldSpecs.isEmpty()) { ArrayNode jsonArray = JsonUtils.newArrayNode(); for (DimensionFieldSpec dimensionFieldSpec : _dimensionFieldSpecs) { jsonArray.add(dimensionFieldSpec.toJsonObject()); } jsonObject.set("dimensionFieldSpecs", jsonArray); } if (!_metricFieldSpecs.isEmpty()) { ArrayNode jsonArray = JsonUtils.newArrayNode(); for (MetricFieldSpec metricFieldSpec : _metricFieldSpecs) { jsonArray.add(metricFieldSpec.toJsonObject()); } jsonObject.set("metricFieldSpecs", jsonArray); } if (_timeFieldSpec != null) { jsonObject.set("timeFieldSpec", _timeFieldSpec.toJsonObject()); } if (!_dateTimeFieldSpecs.isEmpty()) { ArrayNode jsonArray = JsonUtils.newArrayNode(); for (DateTimeFieldSpec dateTimeFieldSpec : _dateTimeFieldSpecs) { jsonArray.add(dateTimeFieldSpec.toJsonObject()); } jsonObject.set("dateTimeFieldSpecs", jsonArray); } if (!_complexFieldSpecs.isEmpty()) { ArrayNode jsonArray = JsonUtils.newArrayNode(); for (ComplexFieldSpec complexFieldSpec : _complexFieldSpecs) { jsonArray.add(complexFieldSpec.toJsonObject()); } jsonObject.set("complexFieldSpecs", jsonArray); } if (_primaryKeyColumns != null && !_primaryKeyColumns.isEmpty()) { ArrayNode jsonArray = JsonUtils.newArrayNode(); for (String column : _primaryKeyColumns) { jsonArray.add(column); } jsonObject.set("primaryKeyColumns", jsonArray); } return jsonObject; } /** * Returns a pretty json string representation of the schema. */ public String toPrettyJsonString() { try { return JsonUtils.objectToPrettyString(toJsonObject()); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } /** * Returns a single-line json string representation of the schema. */ public String toSingleLineJsonString() { return toJsonObject().toString(); } /** * Validates a pinot schema. * <p>The following validations are performed: * <ul> * <li>For dimension, time, date time fields, support {@link DataType}: INT, LONG, FLOAT, DOUBLE, BOOLEAN, * TIMESTAMP, STRING, BYTES</li> * <li>For metric fields, support {@link DataType}: INT, LONG, FLOAT, DOUBLE, BYTES</li> * </ul> */ public void validate() { for (FieldSpec fieldSpec : _fieldSpecMap.values()) { FieldType fieldType = fieldSpec.getFieldType(); DataType dataType = fieldSpec.getDataType(); String fieldName = fieldSpec.getName(); try { validate(fieldType, dataType); } catch (IllegalStateException e) { throw new IllegalStateException(e.getMessage() + ": " + fieldName); } } } public static class SchemaBuilder { private final Schema _schema; public SchemaBuilder() { _schema = new Schema(); } public SchemaBuilder setSchemaName(String schemaName) { _schema.setSchemaName(schemaName); return this; } public SchemaBuilder setEnableColumnBasedNullHandling(boolean enableColumnBasedNullHandling) { _schema.setEnableColumnBasedNullHandling(enableColumnBasedNullHandling); return this; } public SchemaBuilder addField(FieldSpec fieldSpec) { _schema.addField(fieldSpec); return this; } public SchemaBuilder addMetricField(String name, DataType dataType) { return addMetricField(name, dataType, ignore -> { }); } public SchemaBuilder addMetricField(String name, DataType dataType, Consumer<MetricFieldSpec> customizer) { MetricFieldSpec fieldSpec = new MetricFieldSpec(); return addField(fieldSpec, name, dataType, customizer); } public SchemaBuilder addDimensionField(String name, DataType dataType) { return addDimensionField(name, dataType, ignore -> { }); } public SchemaBuilder addDimensionField(String name, DataType dataType, Consumer<DimensionFieldSpec> customizer) { DimensionFieldSpec fieldSpec = new DimensionFieldSpec(); return addField(fieldSpec, name, dataType, customizer); } public SchemaBuilder addDateTimeField(String name, DataType dataType, String format, String granularity) { return addDateTimeField(name, dataType, format, granularity, ignore -> { }); } public SchemaBuilder addDateTimeField(String name, DataType dataType, String format, String granularity, Consumer<DateTimeFieldSpec> customizer) { DateTimeFieldSpec fieldSpec = new DateTimeFieldSpec(); fieldSpec.setFormat(format); fieldSpec.setGranularity(granularity); return addField(fieldSpec, name, dataType, customizer); } private <E extends FieldSpec> SchemaBuilder addField(E fieldSpec, String name, DataType dataType, Consumer<E> customizer) { fieldSpec.setName(name); fieldSpec.setDataType(dataType); customizer.accept(fieldSpec); _schema.addField(fieldSpec); return this; } /** * Add single value dimensionFieldSpec */ public SchemaBuilder addSingleValueDimension(String dimensionName, DataType dataType) { _schema.addField(new DimensionFieldSpec(dimensionName, dataType, true)); return this; } /** * Add single value dimensionFieldSpec with a defaultNullValue */ public SchemaBuilder addSingleValueDimension(String dimensionName, DataType dataType, Object defaultNullValue) { _schema.addField(new DimensionFieldSpec(dimensionName, dataType, true, defaultNullValue)); return this; } /** * Add single value dimensionFieldSpec with maxLength and a defaultNullValue */ public SchemaBuilder addSingleValueDimension(String dimensionName, DataType dataType, int maxLength, Object defaultNullValue) { Preconditions.checkArgument(dataType == DataType.STRING, "The maxLength field only applies to STRING field right now"); _schema.addField(new DimensionFieldSpec(dimensionName, dataType, true, maxLength, defaultNullValue)); return this; } /** * Add multi value dimensionFieldSpec */ public SchemaBuilder addMultiValueDimension(String dimensionName, DataType dataType) { _schema.addField(new DimensionFieldSpec(dimensionName, dataType, false)); return this; } /** * Add multi value dimensionFieldSpec with defaultNullValue */ public SchemaBuilder addMultiValueDimension(String dimensionName, DataType dataType, Object defaultNullValue) { _schema.addField(new DimensionFieldSpec(dimensionName, dataType, false, defaultNullValue)); return this; } /** * Add multi value dimensionFieldSpec with maxLength and a defaultNullValue */ public SchemaBuilder addMultiValueDimension(String dimensionName, DataType dataType, int maxLength, Object defaultNullValue) { Preconditions.checkArgument(dataType == DataType.STRING, "The maxLength field only applies to STRING field right now"); _schema.addField(new DimensionFieldSpec(dimensionName, dataType, false, maxLength, defaultNullValue)); return this; } /** * Add metricFieldSpec */ public SchemaBuilder addMetric(String metricName, DataType dataType) { _schema.addField(new MetricFieldSpec(metricName, dataType)); return this; } /** * Add metricFieldSpec with defaultNullValue */ public SchemaBuilder addMetric(String metricName, DataType dataType, Object defaultNullValue) { _schema.addField(new MetricFieldSpec(metricName, dataType, defaultNullValue)); return this; } /** * @deprecated in favor of {@link SchemaBuilder#addDateTime(String, DataType, String, String)} * Adds timeFieldSpec with incoming and outgoing granularity spec * This will continue to exist for a while in several tests, as it helps to test backward compatibility of * schemas containing * TimeFieldSpec */ @Deprecated public SchemaBuilder addTime(TimeGranularitySpec incomingTimeGranularitySpec, @Nullable TimeGranularitySpec outgoingTimeGranularitySpec) { if (outgoingTimeGranularitySpec != null) { _schema.addField(new TimeFieldSpec(incomingTimeGranularitySpec, outgoingTimeGranularitySpec)); } else { _schema.addField(new TimeFieldSpec(incomingTimeGranularitySpec)); } return this; } /** * Add dateTimeFieldSpec with basic fields */ public SchemaBuilder addDateTime(String name, DataType dataType, String format, String granularity) { _schema.addField(new DateTimeFieldSpec(name, dataType, format, granularity)); return this; } /** * Add dateTimeFieldSpec with basic fields plus defaultNullValue and transformFunction */ public SchemaBuilder addDateTime(String name, DataType dataType, String format, String granularity, @Nullable Object defaultNullValue, @Nullable String transformFunction) { DateTimeFieldSpec dateTimeFieldSpec = new DateTimeFieldSpec(name, dataType, format, granularity, defaultNullValue, transformFunction); _schema.addField(dateTimeFieldSpec); return this; } /** * Add complex field spec * @param name name of complex (nested) field * @param dataType root data type of complex field * @param childFieldSpecs map of child field specs */ public SchemaBuilder addComplex(String name, DataType dataType, Map<String, FieldSpec> childFieldSpecs) { _schema.addField(new ComplexFieldSpec(name, dataType, /* single value field */ true, childFieldSpecs)); return this; } public SchemaBuilder setPrimaryKeyColumns(List<String> primaryKeyColumns) { _schema.setPrimaryKeyColumns(primaryKeyColumns); return this; } public Schema build() { try { _schema.validate(); } catch (Exception e) { throw new RuntimeException("Invalid schema", e); } return _schema; } } @Override public String toString() { return toPrettyJsonString(); } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object o) { if (EqualityUtils.isSameReference(this, o)) { return true; } if (EqualityUtils.isNullOrNotSameClass(this, o)) { return false; } Schema that = (Schema) o; //@formatter:off return EqualityUtils.isEqual(_schemaName, that._schemaName) && EqualityUtils.isEqualIgnoreOrder(_dimensionFieldSpecs, that._dimensionFieldSpecs) && EqualityUtils.isEqualIgnoreOrder(_metricFieldSpecs, that._metricFieldSpecs) && EqualityUtils.isEqual(_timeFieldSpec, that._timeFieldSpec) && EqualityUtils.isEqualIgnoreOrder(_dateTimeFieldSpecs, that._dateTimeFieldSpecs) && EqualityUtils.isEqualIgnoreOrder(_complexFieldSpecs, that._complexFieldSpecs) && EqualityUtils.isEqual(_primaryKeyColumns, that._primaryKeyColumns) && EqualityUtils.isEqual(_enableColumnBasedNullHandling, that._enableColumnBasedNullHandling); //@formatter:on } /** * Updates fields with BOOLEAN data type to STRING if the data type in the old schema is STRING. * * BOOLEAN data type was stored as STRING within the schema before release 0.8.0. In release 0.8.0, we introduced * native BOOLEAN support and BOOLEAN data type is no longer replaced with STRING. * To keep the existing schema backward compatible, when the new field spec has BOOLEAN data type and the old field * spec has STRING data type, set the new field spec's data type to STRING. */ public void updateBooleanFieldsIfNeeded(Schema oldSchema) { for (Map.Entry<String, FieldSpec> entry : _fieldSpecMap.entrySet()) { FieldSpec fieldSpec = entry.getValue(); if (fieldSpec.getDataType() == DataType.BOOLEAN) { FieldSpec oldFieldSpec = oldSchema.getFieldSpecFor(entry.getKey()); if (oldFieldSpec != null && oldFieldSpec.getDataType() == DataType.STRING) { fieldSpec.setDataType(DataType.STRING); } } } } /** * Check whether the current schema is backward compatible with oldSchema. * * Backward compatibility requires * (1) all columns in oldSchema should be retained. * (2) all column fieldSpecs should be backward compatible with the old ones. * * @param oldSchema old schema */ public boolean isBackwardCompatibleWith(Schema oldSchema) { Set<String> columnNames = getColumnNames(); for (Map.Entry<String, FieldSpec> entry : oldSchema.getFieldSpecMap().entrySet()) { String oldSchemaColumnName = entry.getKey(); if (!columnNames.contains(oldSchemaColumnName)) { return false; } FieldSpec oldSchemaFieldSpec = entry.getValue(); FieldSpec fieldSpec = getFieldSpecFor(oldSchemaColumnName); if (!fieldSpec.isBackwardCompatibleWith(oldSchemaFieldSpec)) { return false; } } return true; } @Override public int hashCode() { int result = EqualityUtils.hashCodeOf(_schemaName); result = EqualityUtils.hashCodeOf(result, _dimensionFieldSpecs); result = EqualityUtils.hashCodeOf(result, _metricFieldSpecs); result = EqualityUtils.hashCodeOf(result, _timeFieldSpec); result = EqualityUtils.hashCodeOf(result, _dateTimeFieldSpecs); result = EqualityUtils.hashCodeOf(result, _complexFieldSpecs); result = EqualityUtils.hashCodeOf(result, _primaryKeyColumns); result = EqualityUtils.hashCodeOf(result, _enableColumnBasedNullHandling); return result; } /** * @deprecated this method is not correctly implemented. ie doesn't call super.clone and does not create a deep copy * of the fieldSpecs. */ @Deprecated @Override public Schema clone() { Schema cloned = new SchemaBuilder() .setSchemaName(getSchemaName()) .setPrimaryKeyColumns(getPrimaryKeyColumns()) .setEnableColumnBasedNullHandling(isEnableColumnBasedNullHandling()) .build(); getAllFieldSpecs().forEach(fieldSpec -> cloned.addField(fieldSpec)); return cloned; } /** * Helper method that converts a {@link TimeFieldSpec} to {@link DateTimeFieldSpec} * 1) If timeFieldSpec contains only incoming granularity spec, directly convert it to a dateTimeFieldSpec * 2) If timeFieldSpec contains incoming aas well as outgoing granularity spec, use the outgoing spec to construct * the dateTimeFieldSpec, * and configure a transform function for the conversion from incoming */ public static DateTimeFieldSpec convertToDateTimeFieldSpec(TimeFieldSpec timeFieldSpec) { DateTimeFieldSpec dateTimeFieldSpec = new DateTimeFieldSpec(); TimeGranularitySpec incomingGranularitySpec = timeFieldSpec.getIncomingGranularitySpec(); TimeGranularitySpec outgoingGranularitySpec = timeFieldSpec.getOutgoingGranularitySpec(); dateTimeFieldSpec.setName(outgoingGranularitySpec.getName()); dateTimeFieldSpec.setDataType(outgoingGranularitySpec.getDataType()); int outgoingTimeSize = outgoingGranularitySpec.getTimeUnitSize(); TimeUnit outgoingTimeUnit = outgoingGranularitySpec.getTimeType(); String outgoingTimeFormat = outgoingGranularitySpec.getTimeFormat(); String[] split = StringUtil.split(outgoingTimeFormat, ':', 2); String timeFormat; if (split[0].equals(DateTimeFieldSpec.TimeFormat.EPOCH.name())) { timeFormat = outgoingTimeSize + ":" + outgoingTimeUnit.name() + ":EPOCH"; } else { timeFormat = outgoingTimeSize + ":" + outgoingTimeUnit.name() + ":SIMPLE_DATE_FORMAT:" + split[1]; } // TODO: Switch to new format after releasing 0.11.0 // if (split[0].equals(DateTimeFieldSpec.TimeFormat.EPOCH.name())) { // timeFormat = "EPOCH|" + outgoingTimeUnit.name(); // if (outgoingTimeSize != 1) { // timeFormat += "|" + outgoingTimeSize; // } // timeFormat = outgoingTimeSize + ":" + outgoingTimeUnit.name() + ":EPOCH"; // } else { // timeFormat = "SIMPLE_DATE_FORMAT|" + split[1]; // } dateTimeFieldSpec.setFormat(timeFormat); DateTimeGranularitySpec granularitySpec = new DateTimeGranularitySpec(outgoingTimeSize, outgoingTimeUnit); dateTimeFieldSpec.setGranularity(outgoingTimeSize + ":" + outgoingTimeUnit.name()); if (timeFieldSpec.getTransformFunction() != null) { dateTimeFieldSpec.setTransformFunction(timeFieldSpec.getTransformFunction()); } else if (!incomingGranularitySpec.equals(outgoingGranularitySpec)) { String incomingName = incomingGranularitySpec.getName(); int incomingTimeSize = incomingGranularitySpec.getTimeUnitSize(); TimeUnit incomingTimeUnit = incomingGranularitySpec.getTimeType(); String incomingTimeFormat = incomingGranularitySpec.getTimeFormat(); Preconditions.checkState( (incomingTimeFormat.equals(DateTimeFieldSpec.TimeFormat.EPOCH.toString()) || incomingTimeFormat.equals( DateTimeFieldSpec.TimeFormat.TIMESTAMP.toString())) && outgoingTimeFormat.equals(incomingTimeFormat), "Conversion from incoming to outgoing is not supported for SIMPLE_DATE_FORMAT"); String transformFunction = constructTransformFunctionString(incomingName, incomingTimeSize, incomingTimeUnit, outgoingTimeSize, outgoingTimeUnit); dateTimeFieldSpec.setTransformFunction(transformFunction); } dateTimeFieldSpec.setMaxLength(timeFieldSpec.getMaxLength()); dateTimeFieldSpec.setDefaultNullValue(timeFieldSpec.getDefaultNullValue()); return dateTimeFieldSpec; } /** * Constructs a transformFunction string for the time column, based on incoming and outgoing timeGranularitySpec */ private static String constructTransformFunctionString(String incomingName, int incomingTimeSize, TimeUnit incomingTimeUnit, int outgoingTimeSize, TimeUnit outgoingTimeUnit) { String innerFunction = incomingName; switch (incomingTimeUnit) { case MILLISECONDS: // do nothing break; case SECONDS: if (incomingTimeSize > 1) { innerFunction = "fromEpochSecondsBucket(" + incomingName + ", " + incomingTimeSize + ")"; } else { innerFunction = "fromEpochSeconds(" + incomingName + ")"; } break; case MINUTES: if (incomingTimeSize > 1) { innerFunction = "fromEpochMinutesBucket(" + incomingName + ", " + incomingTimeSize + ")"; } else { innerFunction = "fromEpochMinutes(" + incomingName + ")"; } break; case HOURS: if (incomingTimeSize > 1) { innerFunction = "fromEpochHoursBucket(" + incomingName + ", " + incomingTimeSize + ")"; } else { innerFunction = "fromEpochHours(" + incomingName + ")"; } break; case DAYS: if (incomingTimeSize > 1) { innerFunction = "fromEpochDaysBucket(" + incomingName + ", " + incomingTimeSize + ")"; } else { innerFunction = "fromEpochDays(" + incomingName + ")"; } break; default: throw new IllegalStateException("Unsupported incomingTimeUnit - " + incomingTimeUnit); } String outerFunction = innerFunction; switch (outgoingTimeUnit) { case MILLISECONDS: break; case SECONDS: if (outgoingTimeSize > 1) { outerFunction = "toEpochSecondsBucket(" + innerFunction + ", " + outgoingTimeSize + ")"; } else { outerFunction = "toEpochSeconds(" + innerFunction + ")"; } break; case MINUTES: if (outgoingTimeSize > 1) { outerFunction = "toEpochMinutesBucket(" + innerFunction + ", " + outgoingTimeSize + ")"; } else { outerFunction = "toEpochMinutes(" + innerFunction + ")"; } break; case HOURS: if (outgoingTimeSize > 1) { outerFunction = "toEpochHoursBucket(" + innerFunction + ", " + outgoingTimeSize + ")"; } else { outerFunction = "toEpochHours(" + innerFunction + ")"; } break; case DAYS: if (outgoingTimeSize > 1) { outerFunction = "toEpochDaysBucket(" + innerFunction + ", " + outgoingTimeSize + ")"; } else { outerFunction = "toEpochDays(" + innerFunction + ")"; } break; default: throw new IllegalStateException("Unsupported outgoingTimeUnit - " + outgoingTimeUnit); } return outerFunction; } }
googleapis/google-cloud-java
36,940
java-publicca/proto-google-cloud-publicca-v1/src/main/java/com/google/cloud/security/publicca/v1/CreateExternalAccountKeyRequest.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/security/publicca/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.security.publicca.v1; /** * * * <pre> * Creates a new * [ExternalAccountKey][google.cloud.security.publicca.v1.ExternalAccountKey] in * a given project. * </pre> * * Protobuf type {@code google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest} */ public final class CreateExternalAccountKeyRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest) CreateExternalAccountKeyRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateExternalAccountKeyRequest.newBuilder() to construct. private CreateExternalAccountKeyRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateExternalAccountKeyRequest() { parent_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateExternalAccountKeyRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.security.publicca.v1.ServiceProto .internal_static_google_cloud_security_publicca_v1_CreateExternalAccountKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.security.publicca.v1.ServiceProto .internal_static_google_cloud_security_publicca_v1_CreateExternalAccountKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest.class, com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest.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 where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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 where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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 EXTERNAL_ACCOUNT_KEY_FIELD_NUMBER = 2; private com.google.cloud.security.publicca.v1.ExternalAccountKey externalAccountKey_; /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the externalAccountKey field is set. */ @java.lang.Override public boolean hasExternalAccountKey() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The externalAccountKey. */ @java.lang.Override public com.google.cloud.security.publicca.v1.ExternalAccountKey getExternalAccountKey() { return externalAccountKey_ == null ? com.google.cloud.security.publicca.v1.ExternalAccountKey.getDefaultInstance() : externalAccountKey_; } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.security.publicca.v1.ExternalAccountKeyOrBuilder getExternalAccountKeyOrBuilder() { return externalAccountKey_ == null ? com.google.cloud.security.publicca.v1.ExternalAccountKey.getDefaultInstance() : externalAccountKey_; } 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, getExternalAccountKey()); } 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, getExternalAccountKey()); } 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.security.publicca.v1.CreateExternalAccountKeyRequest)) { return super.equals(obj); } com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest other = (com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasExternalAccountKey() != other.hasExternalAccountKey()) return false; if (hasExternalAccountKey()) { if (!getExternalAccountKey().equals(other.getExternalAccountKey())) 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 (hasExternalAccountKey()) { hash = (37 * hash) + EXTERNAL_ACCOUNT_KEY_FIELD_NUMBER; hash = (53 * hash) + getExternalAccountKey().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest 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.security.publicca.v1.CreateExternalAccountKeyRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest 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.security.publicca.v1.CreateExternalAccountKeyRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest 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.security.publicca.v1.CreateExternalAccountKeyRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest 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.security.publicca.v1.CreateExternalAccountKeyRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest 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.security.publicca.v1.CreateExternalAccountKeyRequest 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> * Creates a new * [ExternalAccountKey][google.cloud.security.publicca.v1.ExternalAccountKey] in * a given project. * </pre> * * Protobuf type {@code google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest) com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.security.publicca.v1.ServiceProto .internal_static_google_cloud_security_publicca_v1_CreateExternalAccountKeyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.security.publicca.v1.ServiceProto .internal_static_google_cloud_security_publicca_v1_CreateExternalAccountKeyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest.class, com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest.Builder.class); } // Construct using // com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getExternalAccountKeyFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; externalAccountKey_ = null; if (externalAccountKeyBuilder_ != null) { externalAccountKeyBuilder_.dispose(); externalAccountKeyBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.security.publicca.v1.ServiceProto .internal_static_google_cloud_security_publicca_v1_CreateExternalAccountKeyRequest_descriptor; } @java.lang.Override public com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest getDefaultInstanceForType() { return com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest build() { com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest buildPartial() { com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest result = new com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.externalAccountKey_ = externalAccountKeyBuilder_ == null ? externalAccountKey_ : externalAccountKeyBuilder_.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.security.publicca.v1.CreateExternalAccountKeyRequest) { return mergeFrom( (com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest other) { if (other == com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasExternalAccountKey()) { mergeExternalAccountKey(other.getExternalAccountKey()); } 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( getExternalAccountKeyFieldBuilder().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 java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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 where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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 where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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 where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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 where this external_account_key will be * created. Format: projects/[project_id]/locations/[location]. At present * only the "global" location is supported. * </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.security.publicca.v1.ExternalAccountKey externalAccountKey_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.security.publicca.v1.ExternalAccountKey, com.google.cloud.security.publicca.v1.ExternalAccountKey.Builder, com.google.cloud.security.publicca.v1.ExternalAccountKeyOrBuilder> externalAccountKeyBuilder_; /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the externalAccountKey field is set. */ public boolean hasExternalAccountKey() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The externalAccountKey. */ public com.google.cloud.security.publicca.v1.ExternalAccountKey getExternalAccountKey() { if (externalAccountKeyBuilder_ == null) { return externalAccountKey_ == null ? com.google.cloud.security.publicca.v1.ExternalAccountKey.getDefaultInstance() : externalAccountKey_; } else { return externalAccountKeyBuilder_.getMessage(); } } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setExternalAccountKey( com.google.cloud.security.publicca.v1.ExternalAccountKey value) { if (externalAccountKeyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } externalAccountKey_ = value; } else { externalAccountKeyBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setExternalAccountKey( com.google.cloud.security.publicca.v1.ExternalAccountKey.Builder builderForValue) { if (externalAccountKeyBuilder_ == null) { externalAccountKey_ = builderForValue.build(); } else { externalAccountKeyBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeExternalAccountKey( com.google.cloud.security.publicca.v1.ExternalAccountKey value) { if (externalAccountKeyBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && externalAccountKey_ != null && externalAccountKey_ != com.google.cloud.security.publicca.v1.ExternalAccountKey.getDefaultInstance()) { getExternalAccountKeyBuilder().mergeFrom(value); } else { externalAccountKey_ = value; } } else { externalAccountKeyBuilder_.mergeFrom(value); } if (externalAccountKey_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearExternalAccountKey() { bitField0_ = (bitField0_ & ~0x00000002); externalAccountKey_ = null; if (externalAccountKeyBuilder_ != null) { externalAccountKeyBuilder_.dispose(); externalAccountKeyBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.security.publicca.v1.ExternalAccountKey.Builder getExternalAccountKeyBuilder() { bitField0_ |= 0x00000002; onChanged(); return getExternalAccountKeyFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.security.publicca.v1.ExternalAccountKeyOrBuilder getExternalAccountKeyOrBuilder() { if (externalAccountKeyBuilder_ != null) { return externalAccountKeyBuilder_.getMessageOrBuilder(); } else { return externalAccountKey_ == null ? com.google.cloud.security.publicca.v1.ExternalAccountKey.getDefaultInstance() : externalAccountKey_; } } /** * * * <pre> * Required. The external account key to create. This field only exists to * future-proof the API. At present, all fields in ExternalAccountKey are * output only and all values are ignored. For the purpose of the * CreateExternalAccountKeyRequest, set it to a default/empty value. * </pre> * * <code> * .google.cloud.security.publicca.v1.ExternalAccountKey external_account_key = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.security.publicca.v1.ExternalAccountKey, com.google.cloud.security.publicca.v1.ExternalAccountKey.Builder, com.google.cloud.security.publicca.v1.ExternalAccountKeyOrBuilder> getExternalAccountKeyFieldBuilder() { if (externalAccountKeyBuilder_ == null) { externalAccountKeyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.security.publicca.v1.ExternalAccountKey, com.google.cloud.security.publicca.v1.ExternalAccountKey.Builder, com.google.cloud.security.publicca.v1.ExternalAccountKeyOrBuilder>( getExternalAccountKey(), getParentForChildren(), isClean()); externalAccountKey_ = null; } return externalAccountKeyBuilder_; } @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.security.publicca.v1.CreateExternalAccountKeyRequest) } // @@protoc_insertion_point(class_scope:google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest) private static final com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest(); } public static com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateExternalAccountKeyRequest> PARSER = new com.google.protobuf.AbstractParser<CreateExternalAccountKeyRequest>() { @java.lang.Override public CreateExternalAccountKeyRequest 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<CreateExternalAccountKeyRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateExternalAccountKeyRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.security.publicca.v1.CreateExternalAccountKeyRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,768
java-document-ai/proto-google-cloud-document-ai-v1/src/main/java/com/google/cloud/documentai/v1/Barcode.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/documentai/v1/barcode.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.documentai.v1; /** * * * <pre> * Encodes the detailed information of a barcode. * </pre> * * Protobuf type {@code google.cloud.documentai.v1.Barcode} */ public final class Barcode extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.documentai.v1.Barcode) BarcodeOrBuilder { private static final long serialVersionUID = 0L; // Use Barcode.newBuilder() to construct. private Barcode(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Barcode() { format_ = ""; valueFormat_ = ""; rawValue_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Barcode(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.documentai.v1.BarcodeProto .internal_static_google_cloud_documentai_v1_Barcode_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.documentai.v1.BarcodeProto .internal_static_google_cloud_documentai_v1_Barcode_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.documentai.v1.Barcode.class, com.google.cloud.documentai.v1.Barcode.Builder.class); } public static final int FORMAT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object format_ = ""; /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @return The format. */ @java.lang.Override public java.lang.String getFormat() { java.lang.Object ref = format_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); format_ = s; return s; } } /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @return The bytes for format. */ @java.lang.Override public com.google.protobuf.ByteString getFormatBytes() { java.lang.Object ref = format_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); format_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALUE_FORMAT_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object valueFormat_ = ""; /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @return The valueFormat. */ @java.lang.Override public java.lang.String getValueFormat() { java.lang.Object ref = valueFormat_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); valueFormat_ = s; return s; } } /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @return The bytes for valueFormat. */ @java.lang.Override public com.google.protobuf.ByteString getValueFormatBytes() { java.lang.Object ref = valueFormat_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); valueFormat_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RAW_VALUE_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object rawValue_ = ""; /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @return The rawValue. */ @java.lang.Override public java.lang.String getRawValue() { java.lang.Object ref = rawValue_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawValue_ = s; return s; } } /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @return The bytes for rawValue. */ @java.lang.Override public com.google.protobuf.ByteString getRawValueBytes() { java.lang.Object ref = rawValue_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); rawValue_ = 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(format_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, format_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(valueFormat_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, valueFormat_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(rawValue_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, rawValue_); } 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(format_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, format_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(valueFormat_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, valueFormat_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(rawValue_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, rawValue_); } 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.documentai.v1.Barcode)) { return super.equals(obj); } com.google.cloud.documentai.v1.Barcode other = (com.google.cloud.documentai.v1.Barcode) obj; if (!getFormat().equals(other.getFormat())) return false; if (!getValueFormat().equals(other.getValueFormat())) return false; if (!getRawValue().equals(other.getRawValue())) 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) + FORMAT_FIELD_NUMBER; hash = (53 * hash) + getFormat().hashCode(); hash = (37 * hash) + VALUE_FORMAT_FIELD_NUMBER; hash = (53 * hash) + getValueFormat().hashCode(); hash = (37 * hash) + RAW_VALUE_FIELD_NUMBER; hash = (53 * hash) + getRawValue().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.documentai.v1.Barcode parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1.Barcode 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.documentai.v1.Barcode parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1.Barcode 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.documentai.v1.Barcode parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1.Barcode parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.documentai.v1.Barcode parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1.Barcode 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.documentai.v1.Barcode parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1.Barcode 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.documentai.v1.Barcode parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1.Barcode 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.documentai.v1.Barcode 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> * Encodes the detailed information of a barcode. * </pre> * * Protobuf type {@code google.cloud.documentai.v1.Barcode} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.documentai.v1.Barcode) com.google.cloud.documentai.v1.BarcodeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.documentai.v1.BarcodeProto .internal_static_google_cloud_documentai_v1_Barcode_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.documentai.v1.BarcodeProto .internal_static_google_cloud_documentai_v1_Barcode_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.documentai.v1.Barcode.class, com.google.cloud.documentai.v1.Barcode.Builder.class); } // Construct using com.google.cloud.documentai.v1.Barcode.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; format_ = ""; valueFormat_ = ""; rawValue_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.documentai.v1.BarcodeProto .internal_static_google_cloud_documentai_v1_Barcode_descriptor; } @java.lang.Override public com.google.cloud.documentai.v1.Barcode getDefaultInstanceForType() { return com.google.cloud.documentai.v1.Barcode.getDefaultInstance(); } @java.lang.Override public com.google.cloud.documentai.v1.Barcode build() { com.google.cloud.documentai.v1.Barcode result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.documentai.v1.Barcode buildPartial() { com.google.cloud.documentai.v1.Barcode result = new com.google.cloud.documentai.v1.Barcode(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.documentai.v1.Barcode result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.format_ = format_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.valueFormat_ = valueFormat_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.rawValue_ = rawValue_; } } @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.documentai.v1.Barcode) { return mergeFrom((com.google.cloud.documentai.v1.Barcode) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.documentai.v1.Barcode other) { if (other == com.google.cloud.documentai.v1.Barcode.getDefaultInstance()) return this; if (!other.getFormat().isEmpty()) { format_ = other.format_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getValueFormat().isEmpty()) { valueFormat_ = other.valueFormat_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getRawValue().isEmpty()) { rawValue_ = other.rawValue_; 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: { format_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { valueFormat_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { rawValue_ = 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 format_ = ""; /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @return The format. */ public java.lang.String getFormat() { java.lang.Object ref = format_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); format_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @return The bytes for format. */ public com.google.protobuf.ByteString getFormatBytes() { java.lang.Object ref = format_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); format_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @param value The format to set. * @return This builder for chaining. */ public Builder setFormat(java.lang.String value) { if (value == null) { throw new NullPointerException(); } format_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @return This builder for chaining. */ public Builder clearFormat() { format_ = getDefaultInstance().getFormat(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Format of a barcode. * The supported formats are: * * - `CODE_128`: Code 128 type. * - `CODE_39`: Code 39 type. * - `CODE_93`: Code 93 type. * - `CODABAR`: Codabar type. * - `DATA_MATRIX`: 2D Data Matrix type. * - `ITF`: ITF type. * - `EAN_13`: EAN-13 type. * - `EAN_8`: EAN-8 type. * - `QR_CODE`: 2D QR code type. * - `UPC_A`: UPC-A type. * - `UPC_E`: UPC-E type. * - `PDF417`: PDF417 type. * - `AZTEC`: 2D Aztec code type. * - `DATABAR`: GS1 DataBar code type. * </pre> * * <code>string format = 1;</code> * * @param value The bytes for format to set. * @return This builder for chaining. */ public Builder setFormatBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); format_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object valueFormat_ = ""; /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @return The valueFormat. */ public java.lang.String getValueFormat() { java.lang.Object ref = valueFormat_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); valueFormat_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @return The bytes for valueFormat. */ public com.google.protobuf.ByteString getValueFormatBytes() { java.lang.Object ref = valueFormat_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); valueFormat_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @param value The valueFormat to set. * @return This builder for chaining. */ public Builder setValueFormat(java.lang.String value) { if (value == null) { throw new NullPointerException(); } valueFormat_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @return This builder for chaining. */ public Builder clearValueFormat() { valueFormat_ = getDefaultInstance().getValueFormat(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Value format describes the format of the value that a barcode * encodes. * The supported formats are: * * - `CONTACT_INFO`: Contact information. * - `EMAIL`: Email address. * - `ISBN`: ISBN identifier. * - `PHONE`: Phone number. * - `PRODUCT`: Product. * - `SMS`: SMS message. * - `TEXT`: Text string. * - `URL`: URL address. * - `WIFI`: Wifi information. * - `GEO`: Geo-localization. * - `CALENDAR_EVENT`: Calendar event. * - `DRIVER_LICENSE`: Driver's license. * </pre> * * <code>string value_format = 2;</code> * * @param value The bytes for valueFormat to set. * @return This builder for chaining. */ public Builder setValueFormatBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); valueFormat_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object rawValue_ = ""; /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @return The rawValue. */ public java.lang.String getRawValue() { java.lang.Object ref = rawValue_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); rawValue_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @return The bytes for rawValue. */ public com.google.protobuf.ByteString getRawValueBytes() { java.lang.Object ref = rawValue_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); rawValue_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @param value The rawValue to set. * @return This builder for chaining. */ public Builder setRawValue(java.lang.String value) { if (value == null) { throw new NullPointerException(); } rawValue_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @return This builder for chaining. */ public Builder clearRawValue() { rawValue_ = getDefaultInstance().getRawValue(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Raw value encoded in the barcode. * For example: `'MEBKM:TITLE:Google;URL:https://www.google.com;;'`. * </pre> * * <code>string raw_value = 3;</code> * * @param value The bytes for rawValue to set. * @return This builder for chaining. */ public Builder setRawValueBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); rawValue_ = 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.documentai.v1.Barcode) } // @@protoc_insertion_point(class_scope:google.cloud.documentai.v1.Barcode) private static final com.google.cloud.documentai.v1.Barcode DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.documentai.v1.Barcode(); } public static com.google.cloud.documentai.v1.Barcode getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Barcode> PARSER = new com.google.protobuf.AbstractParser<Barcode>() { @java.lang.Override public Barcode 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<Barcode> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Barcode> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.documentai.v1.Barcode getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/commons-jcs
36,643
commons-jcs3-core/src/test/java/org/apache/commons/jcs3/auxiliary/disk/indexed/AbstractIndexDiskCacheUnitTest.java
package org.apache.commons.jcs3.auxiliary.disk.indexed; /* * 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. */ 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.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.jcs3.auxiliary.MockCacheEventLogger; import org.apache.commons.jcs3.auxiliary.disk.DiskTestObject; import org.apache.commons.jcs3.engine.CacheElement; import org.apache.commons.jcs3.engine.ElementAttributes; import org.apache.commons.jcs3.engine.behavior.ICacheElement; import org.apache.commons.jcs3.engine.behavior.IElementAttributes; import org.apache.commons.jcs3.engine.control.group.GroupAttrName; import org.apache.commons.jcs3.engine.control.group.GroupId; import org.apache.commons.jcs3.utils.timing.SleepUtil; import org.junit.jupiter.api.Test; /** * Tests for common functionality. */ public abstract class AbstractIndexDiskCacheUnitTest{ public abstract IndexedDiskCacheAttributes getCacheAttributes(); /** * Internal method used for group functionality. * <p> * * @param cacheName * @param group * @param name * @return GroupAttrName */ private GroupAttrName<String> getGroupAttrName(final String cacheName, final String group, final String name) { final GroupId gid = new GroupId(cacheName, group); return new GroupAttrName<>(gid, name); } public void oneLoadFromDisk() throws Exception { // initialize object to be stored String string = "IÒtÎrn‚tiÙn‡lizÊti¯n"; final StringBuilder sb = new StringBuilder(); sb.append(string); for (int i = 0; i < 4; i++) { sb.append(sb.toString()); // big string } string = sb.toString(); // initialize cache final String cacheName = "testLoadFromDisk"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); // DO WORK for (int i = 0; i < 50; i++) { diskCache.update(new CacheElement<>(cacheName, "x" + i, string)); } // Thread.sleep(1000); // VERIFY diskCache.dispose(); // Thread.sleep(1000); diskCache = new IndexedDiskCache<>(cattr); for (int i = 0; i < 50; i++) { final ICacheElement<String, String> afterElement = diskCache.get("x" + i); assertNotNull( afterElement, "Missing element from cache. Cache size: " + diskCache.getSize() + " element: x" + i ); assertEquals( string, afterElement.getVal(), "wrong string after retrieval" ); } } /** * Verify that we don't override the largest item. * <p> * * @throws IOException */ /** * Verify that the data size is as expected after a remove and after a put that should use the * spots. * <p> * * @throws IOException * @throws InterruptedException */ @Test public void testBytesFreeSize() throws IOException, InterruptedException { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testBytesFreeSize"); cattr.setDiskPath("target/test-sandbox/UnitTest"); final IndexedDiskCache<Integer, DiskTestObject> disk = new IndexedDiskCache<>(cattr); final int numberToInsert = 20; final int bytes = 24; final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); for (final ICacheElement<Integer, DiskTestObject> element : elements) { disk.processUpdate(element); } Thread.yield(); Thread.sleep(100); Thread.yield(); // remove half of those added final int numberToRemove = elements.length / 2; for (int i = 0; i < numberToRemove; i++) { disk.processRemove(elements[i].getKey()); } final long expectedSize = DiskTestObjectUtil.totalSize(elements, numberToRemove); final long resultSize = disk.getBytesFree(); // System.out.println( "testBytesFreeSize stats " + disk.getStats() ); assertEquals( expectedSize, resultSize, "Wrong bytes free size" + disk.getStats() ); // add half as many as we removed. These should all use spots in the recycle bin. final int numberToAdd = numberToRemove / 2; for (int i = 0; i < numberToAdd; i++) { disk.processUpdate(elements[i]); } final long expectedSize2 = DiskTestObjectUtil.totalSize(elements, numberToAdd); final long resultSize2 = disk.getBytesFree(); assertEquals( expectedSize2, resultSize2, "Wrong bytes free size" + disk.getStats() ); } /** * Verify that the overlap check returns true when there are no overlaps. */ @Test public void testCheckForDedOverlaps_noOverlap() { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testCheckForDedOverlaps_noOverlap"); cattr.setDiskPath("target/test-sandbox/UnitTest"); final IndexedDiskCache<String, String> disk = new IndexedDiskCache<>(cattr); final int numDescriptors = 5; int pos = 0; final List<IndexedDiskElementDescriptor> sortedDescriptors = new ArrayList<>(); for (int i = 0; i < numDescriptors; i++) { final IndexedDiskElementDescriptor descriptor = new IndexedDiskElementDescriptor(pos, i * 2); pos = pos + i * 2 + IndexedDisk.HEADER_SIZE_BYTES; sortedDescriptors.add(descriptor); } // DO WORK final boolean result = disk.checkForDedOverlaps(sortedDescriptors); // VERIFY assertTrue( result, "There should be no overlap. it should be ok" ); } /** * Verify that the overlap check returns false when there are overlaps. */ @Test public void testCheckForDedOverlaps_overlaps() { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testCheckForDedOverlaps_overlaps"); cattr.setDiskPath("target/test-sandbox/UnitTest"); final IndexedDiskCache<String, String> disk = new IndexedDiskCache<>(cattr); final int numDescriptors = 5; int pos = 0; final List<IndexedDiskElementDescriptor> sortedDescriptors = new ArrayList<>(); for (int i = 0; i < numDescriptors; i++) { final IndexedDiskElementDescriptor descriptor = new IndexedDiskElementDescriptor(pos, i * 2); // don't add the header + IndexedDisk.RECORD_HEADER; pos = pos + i * 2; sortedDescriptors.add(descriptor); } // DO WORK final boolean result = disk.checkForDedOverlaps(sortedDescriptors); // VERIFY assertFalse( result, "There should be overlaps. it should be not ok" ); } /** * Verify that the file size is as expected. * <p> * * @throws IOException * @throws InterruptedException */ @Test public void testFileSize() throws IOException, InterruptedException { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testFileSize"); cattr.setDiskPath("target/test-sandbox/UnitTest"); final IndexedDiskCache<Integer, DiskTestObject> disk = new IndexedDiskCache<>(cattr); final int numberToInsert = 20; final int bytes = 24; final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); for (final ICacheElement<Integer, DiskTestObject> element : elements) { disk.processUpdate(element); } Thread.yield(); Thread.sleep(100); Thread.yield(); final long expectedSize = DiskTestObjectUtil.totalSize(elements, numberToInsert); final long resultSize = disk.getDataFileSize(); // System.out.println( "testFileSize stats " + disk.getStats() ); assertEquals( expectedSize, resultSize, "Wrong file size" ); } /** * Verify event log calls. * <p> * * @throws Exception */ @Test public void testGet_EventLogging_simple() throws Exception { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testGet_EventLogging_simple"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTestCEL"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); diskCache.processRemoveAll(); final MockCacheEventLogger cacheEventLogger = new MockCacheEventLogger(); diskCache.setCacheEventLogger(cacheEventLogger); // DO WORK diskCache.get("key"); // VERIFY assertEquals( 1, cacheEventLogger.startICacheEventCalls, "Start should have been called." ); assertEquals( 1, cacheEventLogger.endICacheEventCalls, "End should have been called." ); } /** * Verify event log calls. * <p> * * @throws Exception */ @Test public void testGetMultiple_EventLogging_simple() throws Exception { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testGetMultiple_EventLogging_simple"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTestCEL"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); diskCache.processRemoveAll(); final MockCacheEventLogger cacheEventLogger = new MockCacheEventLogger(); diskCache.setCacheEventLogger(cacheEventLogger); final Set<String> keys = new HashSet<>(); keys.add("junk"); // DO WORK diskCache.getMultiple(keys); // VERIFY // 1 for get multiple and 1 for get. assertEquals( 2, cacheEventLogger.startICacheEventCalls, "Start should have been called." ); assertEquals( 2, cacheEventLogger.endICacheEventCalls, "End should have been called." ); } @Test public void testLoadFromDisk() throws Exception { for (int i = 0; i < 15; i++) { // usually after 2 time it fails oneLoadFromDisk(); } } /** * Verify that the old slot gets in the recycle bin. * <p> * * @throws IOException */ @Test public void testProcessUpdate_SameKeyBiggerSize() throws IOException { // SETUP final String cacheName = "testProcessUpdate_SameKeyBiggerSize"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); final String key = "myKey"; final String value = "myValue"; final String value2 = "myValue2"; final ICacheElement<String, String> ce1 = new CacheElement<>(cacheName, key, value); // DO WORK diskCache.processUpdate(ce1); final long fileSize1 = diskCache.getDataFileSize(); // DO WORK final ICacheElement<String, String> ce2 = new CacheElement<>(cacheName, key, value2); diskCache.processUpdate(ce2); final ICacheElement<String, String> result = diskCache.processGet(key); // VERIFY assertNotNull( result, "Should have a result" ); final long fileSize2 = diskCache.getDataFileSize(); assertTrue( fileSize1 < fileSize2, "File should be greater." ); final int binSize = diskCache.getRecyleBinSize(); assertEquals( 1, binSize, "Should be one in the bin." ); } /** * Verify the item makes it to disk. * <p> * * @throws IOException */ @Test public void testProcessUpdate_SameKeySameSize() throws IOException { // SETUP final String cacheName = "testProcessUpdate_SameKeySameSize"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); final String key = "myKey"; final String value = "myValue"; final ICacheElement<String, String> ce1 = new CacheElement<>(cacheName, key, value); // DO WORK diskCache.processUpdate(ce1); final long fileSize1 = diskCache.getDataFileSize(); // DO WORK final ICacheElement<String, String> ce2 = new CacheElement<>(cacheName, key, value); diskCache.processUpdate(ce2); final ICacheElement<String, String> result = diskCache.processGet(key); // VERIFY assertNotNull( result, "Should have a result" ); final long fileSize2 = diskCache.getDataFileSize(); assertEquals( fileSize1, fileSize2, "File should be the same" ); final int binSize = diskCache.getRecyleBinSize(); assertEquals( 0, binSize, "Should be nothing in the bin." ); } /** * Verify the item makes it to disk. * <p> * * @throws IOException */ @Test public void testProcessUpdate_SameKeySmallerSize() throws IOException { // SETUP final String cacheName = "testProcessUpdate_SameKeySmallerSize"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); final String key = "myKey"; final String value = "myValue"; final String value2 = "myValu"; final ICacheElement<String, String> ce1 = new CacheElement<>(cacheName, key, value); // DO WORK diskCache.processUpdate(ce1); final long fileSize1 = diskCache.getDataFileSize(); // DO WORK final ICacheElement<String, String> ce2 = new CacheElement<>(cacheName, key, value2); diskCache.processUpdate(ce2); final ICacheElement<String, String> result = diskCache.processGet(key); // VERIFY assertNotNull( result, "Should have a result" ); final long fileSize2 = diskCache.getDataFileSize(); assertEquals( fileSize1, fileSize2, "File should be the same" ); final int binSize = diskCache.getRecyleBinSize(); assertEquals( 0, binSize, "Should be nothing in the bin." ); } /** * Verify the item makes it to disk. * <p> * * @throws IOException */ @Test public void testProcessUpdate_Simple() throws IOException { // SETUP final String cacheName = "testProcessUpdate_Simple"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); final String key = "myKey"; final String value = "myValue"; final ICacheElement<String, String> ce = new CacheElement<>(cacheName, key, value); // DO WORK diskCache.processUpdate(ce); final ICacheElement<String, String> result = diskCache.processGet(key); // VERIFY assertNotNull( result, "Should have a result" ); final long fileSize = diskCache.getDataFileSize(); assertTrue( fileSize > 0, "File should be greater than 0" ); } /** * Test the basic get matching. With no wait this will all come from purgatory. * <p> * * @throws Exception */ @Test public void testPutGetMatching_NoWait() throws Exception { // SETUP final int items = 200; final String cacheName = "testPutGetMatching_NoWait"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); // DO WORK for (int i = 0; i < items; i++) { diskCache.update(new CacheElement<>(cacheName, i + ":key", cacheName + " data " + i)); } final Map<String, ICacheElement<String, String>> matchingResults = diskCache.getMatching("1.8.+"); // VERIFY assertEquals( 10, matchingResults.size(), "Wrong number returned" ); // System.out.println( "matchingResults.keySet() " + matchingResults.keySet() ); // System.out.println( "\nAFTER TEST \n" + diskCache.getStats() ); } /** * Test the basic get matching. * <p> * * @throws Exception */ @Test public void testPutGetMatching_SmallWait() throws Exception { // SETUP final int items = 200; final String cacheName = "testPutGetMatching_SmallWait"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); // DO WORK for (int i = 0; i < items; i++) { diskCache.update(new CacheElement<>(cacheName, i + ":key", cacheName + " data " + i)); } Thread.sleep(500); final Map<String, ICacheElement<String, String>> matchingResults = diskCache.getMatching("1.8.+"); // VERIFY assertEquals( 10, matchingResults.size(), "Wrong number returned" ); // System.out.println( "matchingResults.keySet() " + matchingResults.keySet() ); // System.out.println( "\nAFTER TEST \n" + diskCache.getStats() ); } /** * Verify that items are added to the recycle bin on removal. * <p> * * @throws IOException * @throws InterruptedException */ @Test public void testRecyleBinSize() throws IOException, InterruptedException { // SETUP final int numberToInsert = 20; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRecyleBinSize"); cattr.setDiskPath("target/test-sandbox/UnitTest"); cattr.setOptimizeAtRemoveCount(numberToInsert); cattr.setMaxKeySize(numberToInsert * 2); cattr.setMaxPurgatorySize(numberToInsert); final IndexedDiskCache<Integer, DiskTestObject> disk = new IndexedDiskCache<>(cattr); final int bytes = 1; final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); for (final ICacheElement<Integer, DiskTestObject> element : elements) { disk.processUpdate(element); } Thread.yield(); Thread.sleep(100); Thread.yield(); // remove half final int numberToRemove = elements.length / 2; for (int i = 0; i < numberToRemove; i++) { disk.processRemove(elements[i].getKey()); } // verify that the recycle bin has the correct amount. assertEquals( numberToRemove, disk.getRecyleBinSize(), "The recycle bin should have the number removed." ); } /** * Verify that items of the same size use recycle bin spots. Setup the recycle bin by removing * some items. Add some of the same size. Verify that the recycle count is the number added. * <p> * * @throws IOException * @throws InterruptedException */ @Test public void testRecyleBinUsage() throws IOException, InterruptedException { // SETUP final int numberToInsert = 20; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRecyleBinUsage"); cattr.setDiskPath("target/test-sandbox/UnitTest"); cattr.setOptimizeAtRemoveCount(numberToInsert); cattr.setMaxKeySize(numberToInsert * 2); cattr.setMaxPurgatorySize(numberToInsert); final IndexedDiskCache<Integer, DiskTestObject> disk = new IndexedDiskCache<>(cattr); // we will reuse these final int bytes = 1; final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); // Add some to the disk for (final ICacheElement<Integer, DiskTestObject> element : elements) { disk.processUpdate(element); } Thread.yield(); Thread.sleep(100); Thread.yield(); // remove half of those added final int numberToRemove = elements.length / 2; for (int i = 0; i < numberToRemove; i++) { disk.processRemove(elements[i].getKey()); } // verify that the recycle bin has the correct amount. assertEquals( numberToRemove, disk.getRecyleBinSize(), "The recycle bin should have the number removed." ); // add half as many as we removed. These should all use spots in the recycle bin. final int numberToAdd = numberToRemove / 2; for (int i = 0; i < numberToAdd; i++) { disk.processUpdate(elements[i]); } // verify that we used the correct number of spots assertEquals( numberToAdd, disk.getRecyleCount(), "The recycle bin should have the number removed." + disk.getStats() ); } /** * Verify event log calls. * <p> * * @throws Exception */ @Test public void testRemove_EventLogging_simple() throws Exception { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRemoveAll_EventLogging_simple"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTestCEL"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); diskCache.processRemoveAll(); final MockCacheEventLogger cacheEventLogger = new MockCacheEventLogger(); diskCache.setCacheEventLogger(cacheEventLogger); // DO WORK diskCache.remove("key"); // VERIFY assertEquals( 1, cacheEventLogger.startICacheEventCalls, "Start should have been called." ); assertEquals( 1, cacheEventLogger.endICacheEventCalls, "End should have been called." ); } /** * Verify that group members are removed if we call remove with a group. * * @throws IOException */ @Test public void testRemove_Group() throws IOException { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRemove_Group"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<GroupAttrName<String>, String> disk = new IndexedDiskCache<>(cattr); disk.processRemoveAll(); final String cacheName = "testRemove_Group_Region"; final String groupName = "testRemove_Group"; final int cnt = 25; for (int i = 0; i < cnt; i++) { final GroupAttrName<String> groupAttrName = getGroupAttrName(cacheName, groupName, i + ":key"); final CacheElement<GroupAttrName<String>, String> element = new CacheElement<>(cacheName, groupAttrName, "data:" + i); final IElementAttributes eAttr = new ElementAttributes(); eAttr.setIsSpool(true); element.setElementAttributes(eAttr); disk.processUpdate(element); } // verify each for (int i = 0; i < cnt; i++) { final GroupAttrName<String> groupAttrName = getGroupAttrName(cacheName, groupName, i + ":key"); final ICacheElement<GroupAttrName<String>, String> element = disk.processGet(groupAttrName); assertNotNull( element, "Should have received an element." ); } // DO WORK // remove the group disk.remove(getGroupAttrName(cacheName, groupName, null)); for (int i = 0; i < cnt; i++) { final GroupAttrName<String> groupAttrName = getGroupAttrName(cacheName, groupName, i + ":key"); final ICacheElement<GroupAttrName<String>, String> element = disk.processGet(groupAttrName); // VERIFY assertNull( element, "Should not have received an element." ); } } /** * Add some items to the disk cache and then remove them one by one. * <p> * * @throws IOException */ @Test public void testRemove_PartialKey() throws IOException { final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRemove_PartialKey"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> disk = new IndexedDiskCache<>(cattr); disk.processRemoveAll(); final int cnt = 25; for (int i = 0; i < cnt; i++) { final IElementAttributes eAttr = new ElementAttributes(); eAttr.setIsSpool(true); final ICacheElement<String, String> element = new CacheElement<>("testRemove_PartialKey", i + ":key", "data:" + i); element.setElementAttributes(eAttr); disk.processUpdate(element); } // verif each for (int i = 0; i < cnt; i++) { final ICacheElement<String, String> element = disk.processGet(i + ":key"); assertNotNull( element, "Shoulds have received an element." ); } // remove each for (int i = 0; i < cnt; i++) { disk.remove(i + ":"); final ICacheElement<String, String> element = disk.processGet(i + ":key"); assertNull( element, "Should not have received an element." ); } // https://issues.apache.org/jira/browse/JCS-67 assertEquals( cnt, disk.getRecyleBinSize(), "Recylenbin should not have more elements than we removed. Check for JCS-67" ); } /** * Verify event log calls. * <p> * * @throws Exception */ @Test public void testRemoveAll_EventLogging_simple() throws Exception { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRemoveAll_EventLogging_simple"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTestCEL"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); diskCache.processRemoveAll(); final MockCacheEventLogger cacheEventLogger = new MockCacheEventLogger(); diskCache.setCacheEventLogger(cacheEventLogger); // DO WORK diskCache.remove("key"); // VERIFY assertEquals( 1, cacheEventLogger.startICacheEventCalls, "Start should have been called." ); assertEquals( 1, cacheEventLogger.endICacheEventCalls, "End should have been called." ); } /** * Add some items to the disk cache and then remove them one by one. * * @throws IOException */ @Test public void testRemoveItems() throws IOException { final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testRemoveItems"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> disk = new IndexedDiskCache<>(cattr); disk.processRemoveAll(); final int cnt = 25; for (int i = 0; i < cnt; i++) { final IElementAttributes eAttr = new ElementAttributes(); eAttr.setIsSpool(true); final ICacheElement<String, String> element = new CacheElement<>("testRemoveItems", "key:" + i, "data:" + i); element.setElementAttributes(eAttr); disk.processUpdate(element); } // remove each for (int i = 0; i < cnt; i++) { disk.remove("key:" + i); final ICacheElement<String, String> element = disk.processGet("key:" + i); assertNull( element, "Should not have received an element." ); } } /** * Simply verify that we can put items in the disk cache and retrieve them. * * @throws IOException */ @Test public void testSimplePutAndGet() throws IOException { final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testSimplePutAndGet"); cattr.setMaxKeySize(1000); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> disk = new IndexedDiskCache<>(cattr); disk.processRemoveAll(); final int cnt = 999; for (int i = 0; i < cnt; i++) { final IElementAttributes eAttr = new ElementAttributes(); eAttr.setIsSpool(true); final ICacheElement<String, String> element = new CacheElement<>("testSimplePutAndGet", "key:" + i, "data:" + i); element.setElementAttributes(eAttr); disk.processUpdate(element); } for (int i = 0; i < cnt; i++) { final ICacheElement<String, String> element = disk.processGet("key:" + i); assertNotNull( element, "Should have received an element." ); assertEquals( "data:" + i, element.getVal(), "Element is wrong." ); } // Test that getMultiple returns all the expected values final Set<String> keys = new HashSet<>(); for (int i = 0; i < cnt; i++) { keys.add("key:" + i); } final Map<String, ICacheElement<String, String>> elements = disk.getMultiple(keys); for (int i = 0; i < cnt; i++) { final ICacheElement<String, String> element = elements.get("key:" + i); assertNotNull( element, "element " + i + ":key is missing" ); assertEquals( "data:" + i, element.getVal(), "value key:" + i ); } // System.out.println( disk.getStats() ); } /** * Verify event log calls. * <p> * * @throws Exception */ @Test public void testUpdate_EventLogging_simple() throws Exception { // SETUP final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName("testUpdate_EventLogging_simple"); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTestCEL"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); diskCache.processRemoveAll(); final MockCacheEventLogger cacheEventLogger = new MockCacheEventLogger(); diskCache.setCacheEventLogger(cacheEventLogger); final ICacheElement<String, String> item = new CacheElement<>("region", "key", "value"); // DO WORK diskCache.update(item); SleepUtil.sleepAtLeast(200); // VERIFY assertEquals( 1, cacheEventLogger.startICacheEventCalls, "Start should have been called." ); assertEquals( 1, cacheEventLogger.endICacheEventCalls, "End should have been called." ); } /** * Verify that the block disk cache can handle utf encoded strings. * <p> * * @throws Exception */ @Test public void testUTF8ByteArray() throws Exception { String string = "IÒtÎrn‚tiÙn‡lizÊti¯n"; final StringBuilder sb = new StringBuilder(); sb.append(string); for (int i = 0; i < 4; i++) { sb.append(sb.toString()); // big string } string = sb.toString(); // System.out.println( "The string contains " + string.length() + " characters" ); final byte[] bytes = string.getBytes(StandardCharsets.UTF_8); final String cacheName = "testUTF8ByteArray"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, byte[]> diskCache = new IndexedDiskCache<>(cattr); // DO WORK diskCache.update(new CacheElement<>(cacheName, "x", bytes)); // VERIFY assertNotNull(diskCache.get("x")); Thread.sleep(1000); final ICacheElement<String, byte[]> afterElement = diskCache.get("x"); assertNotNull(afterElement); // System.out.println( "afterElement = " + afterElement ); final byte[] after = afterElement.getVal(); assertNotNull(after); assertEquals( string, new String( after, StandardCharsets.UTF_8 ), "wrong bytes after retrieval" ); } /** * Verify that the block disk cache can handle utf encoded strings. * <p> * * @throws Exception */ @Test public void testUTF8String() throws Exception { String string = "IÒtÎrn‚tiÙn‡lizÊti¯n"; final StringBuilder sb = new StringBuilder(); sb.append(string); for (int i = 0; i < 4; i++) { sb.append(sb.toString()); // big string } string = sb.toString(); // System.out.println( "The string contains " + string.length() + " characters" ); final String cacheName = "testUTF8String"; final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName(cacheName); cattr.setMaxKeySize(100); cattr.setDiskPath("target/test-sandbox/IndexDiskCacheUnitTest"); final IndexedDiskCache<String, String> diskCache = new IndexedDiskCache<>(cattr); // DO WORK diskCache.update(new CacheElement<>(cacheName, "x", string)); // VERIFY assertNotNull(diskCache.get("x")); Thread.sleep(1000); final ICacheElement<String, String> afterElement = diskCache.get("x"); assertNotNull(afterElement); // System.out.println( "afterElement = " + afterElement ); final String after = afterElement.getVal(); assertNotNull(after); assertEquals( string, after, "wrong string after retrieval" ); } }
googleapis/google-cloud-java
37,048
java-shopping-merchant-accounts/google-shopping-merchant-accounts/src/main/java/com/google/shopping/merchant/accounts/v1beta/ProgramsServiceClient.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.shopping.merchant.accounts.v1beta; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.common.util.concurrent.MoreExecutors; import com.google.shopping.merchant.accounts.v1beta.stub.ProgramsServiceStub; import com.google.shopping.merchant.accounts.v1beta.stub.ProgramsServiceStubSettings; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service for program management. * * <p>Programs provide a mechanism for adding functionality to merchant accounts. A typical example * of this is the [Free product * listings](https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&amp;sjid=796648681813264022-EU) * program, which enables products from a merchant's store to be shown across Google for free. * * <p>This service exposes methods to retrieve a merchant's participation in all available programs, * in addition to methods for explicitly enabling or disabling participation in each program. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.getProgram(name); * } * }</pre> * * <p>Note: close() needs to be called on the ProgramsServiceClient object to clean up resources * such as threads. In the example above, try-with-resources is used, which automatically calls * close(). * * <table> * <caption>Methods</caption> * <tr> * <th>Method</th> * <th>Description</th> * <th>Method Variants</th> * </tr> * <tr> * <td><p> GetProgram</td> * <td><p> Retrieves the specified program for the account.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> getProgram(GetProgramRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> getProgram(ProgramName name) * <li><p> getProgram(String name) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getProgramCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ListPrograms</td> * <td><p> Retrieves all programs for the account.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> listPrograms(ListProgramsRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> listPrograms(AccountName parent) * <li><p> listPrograms(String parent) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> listProgramsPagedCallable() * <li><p> listProgramsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> EnableProgram</td> * <td><p> Enable participation in the specified program for the account. Executing this method requires admin access.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> enableProgram(EnableProgramRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> enableProgram(ProgramName name) * <li><p> enableProgram(String name) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> enableProgramCallable() * </ul> * </td> * </tr> * <tr> * <td><p> DisableProgram</td> * <td><p> Disable participation in the specified program for the account. Executing this method requires admin access.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> disableProgram(DisableProgramRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> disableProgram(ProgramName name) * <li><p> disableProgram(String name) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> disableProgramCallable() * </ul> * </td> * </tr> * </table> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of ProgramsServiceSettings to * create(). For example: * * <p>To customize credentials: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * ProgramsServiceSettings programsServiceSettings = * ProgramsServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * ProgramsServiceClient programsServiceClient = * ProgramsServiceClient.create(programsServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * ProgramsServiceSettings programsServiceSettings = * ProgramsServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * ProgramsServiceClient programsServiceClient = * ProgramsServiceClient.create(programsServiceSettings); * }</pre> * * <p>To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over * the wire: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * ProgramsServiceSettings programsServiceSettings = * ProgramsServiceSettings.newHttpJsonBuilder().build(); * ProgramsServiceClient programsServiceClient = * ProgramsServiceClient.create(programsServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class ProgramsServiceClient implements BackgroundResource { private final ProgramsServiceSettings settings; private final ProgramsServiceStub stub; /** Constructs an instance of ProgramsServiceClient with default settings. */ public static final ProgramsServiceClient create() throws IOException { return create(ProgramsServiceSettings.newBuilder().build()); } /** * Constructs an instance of ProgramsServiceClient, using the given settings. The channels are * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ProgramsServiceClient create(ProgramsServiceSettings settings) throws IOException { return new ProgramsServiceClient(settings); } /** * Constructs an instance of ProgramsServiceClient, using the given stub for making calls. This is * for advanced usage - prefer using create(ProgramsServiceSettings). */ public static final ProgramsServiceClient create(ProgramsServiceStub stub) { return new ProgramsServiceClient(stub); } /** * Constructs an instance of ProgramsServiceClient, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected ProgramsServiceClient(ProgramsServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((ProgramsServiceStubSettings) settings.getStubSettings()).createStub(); } protected ProgramsServiceClient(ProgramsServiceStub stub) { this.settings = null; this.stub = stub; } public final ProgramsServiceSettings getSettings() { return settings; } public ProgramsServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.getProgram(name); * } * }</pre> * * @param name Required. The name of the program to retrieve. Format: * `accounts/{account}/programs/{program}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program getProgram(ProgramName name) { GetProgramRequest request = GetProgramRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String name = ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString(); * Program response = programsServiceClient.getProgram(name); * } * }</pre> * * @param name Required. The name of the program to retrieve. Format: * `accounts/{account}/programs/{program}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program getProgram(String name) { GetProgramRequest request = GetProgramRequest.newBuilder().setName(name).build(); return getProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * GetProgramRequest request = * GetProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * Program response = programsServiceClient.getProgram(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program getProgram(GetProgramRequest request) { return getProgramCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * GetProgramRequest request = * GetProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * ApiFuture<Program> future = programsServiceClient.getProgramCallable().futureCall(request); * // Do something. * Program response = future.get(); * } * }</pre> */ public final UnaryCallable<GetProgramRequest, Program> getProgramCallable() { return stub.getProgramCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * AccountName parent = AccountName.of("[ACCOUNT]"); * for (Program element : programsServiceClient.listPrograms(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The name of the account for which to retrieve all programs. Format: * `accounts/{account}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListProgramsPagedResponse listPrograms(AccountName parent) { ListProgramsRequest request = ListProgramsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listPrograms(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String parent = AccountName.of("[ACCOUNT]").toString(); * for (Program element : programsServiceClient.listPrograms(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The name of the account for which to retrieve all programs. Format: * `accounts/{account}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListProgramsPagedResponse listPrograms(String parent) { ListProgramsRequest request = ListProgramsRequest.newBuilder().setParent(parent).build(); return listPrograms(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ListProgramsRequest request = * ListProgramsRequest.newBuilder() * .setParent(AccountName.of("[ACCOUNT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Program element : programsServiceClient.listPrograms(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListProgramsPagedResponse listPrograms(ListProgramsRequest request) { return listProgramsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ListProgramsRequest request = * ListProgramsRequest.newBuilder() * .setParent(AccountName.of("[ACCOUNT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Program> future = * programsServiceClient.listProgramsPagedCallable().futureCall(request); * // Do something. * for (Program element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListProgramsRequest, ListProgramsPagedResponse> listProgramsPagedCallable() { return stub.listProgramsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ListProgramsRequest request = * ListProgramsRequest.newBuilder() * .setParent(AccountName.of("[ACCOUNT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListProgramsResponse response = programsServiceClient.listProgramsCallable().call(request); * for (Program element : response.getProgramsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListProgramsRequest, ListProgramsResponse> listProgramsCallable() { return stub.listProgramsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.enableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to enable participation for the given * account. Format: `accounts/{account}/programs/{program}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program enableProgram(ProgramName name) { EnableProgramRequest request = EnableProgramRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return enableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String name = ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString(); * Program response = programsServiceClient.enableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to enable participation for the given * account. Format: `accounts/{account}/programs/{program}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program enableProgram(String name) { EnableProgramRequest request = EnableProgramRequest.newBuilder().setName(name).build(); return enableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * EnableProgramRequest request = * EnableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * Program response = programsServiceClient.enableProgram(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program enableProgram(EnableProgramRequest request) { return enableProgramCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * EnableProgramRequest request = * EnableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * ApiFuture<Program> future = programsServiceClient.enableProgramCallable().futureCall(request); * // Do something. * Program response = future.get(); * } * }</pre> */ public final UnaryCallable<EnableProgramRequest, Program> enableProgramCallable() { return stub.enableProgramCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.disableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to disable participation for the given * account. Format: `accounts/{account}/programs/{program}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program disableProgram(ProgramName name) { DisableProgramRequest request = DisableProgramRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return disableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String name = ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString(); * Program response = programsServiceClient.disableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to disable participation for the given * account. Format: `accounts/{account}/programs/{program}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program disableProgram(String name) { DisableProgramRequest request = DisableProgramRequest.newBuilder().setName(name).build(); return disableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * DisableProgramRequest request = * DisableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * Program response = programsServiceClient.disableProgram(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program disableProgram(DisableProgramRequest request) { return disableProgramCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. Executing this method requires * admin access. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * try (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * DisableProgramRequest request = * DisableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * ApiFuture<Program> future = * programsServiceClient.disableProgramCallable().futureCall(request); * // Do something. * Program response = future.get(); * } * }</pre> */ public final UnaryCallable<DisableProgramRequest, Program> disableProgramCallable() { return stub.disableProgramCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListProgramsPagedResponse extends AbstractPagedListResponse< ListProgramsRequest, ListProgramsResponse, Program, ListProgramsPage, ListProgramsFixedSizeCollection> { public static ApiFuture<ListProgramsPagedResponse> createAsync( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ApiFuture<ListProgramsResponse> futureResponse) { ApiFuture<ListProgramsPage> futurePage = ListProgramsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListProgramsPagedResponse(input), MoreExecutors.directExecutor()); } private ListProgramsPagedResponse(ListProgramsPage page) { super(page, ListProgramsFixedSizeCollection.createEmptyCollection()); } } public static class ListProgramsPage extends AbstractPage<ListProgramsRequest, ListProgramsResponse, Program, ListProgramsPage> { private ListProgramsPage( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ListProgramsResponse response) { super(context, response); } private static ListProgramsPage createEmptyPage() { return new ListProgramsPage(null, null); } @Override protected ListProgramsPage createPage( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ListProgramsResponse response) { return new ListProgramsPage(context, response); } @Override public ApiFuture<ListProgramsPage> createPageAsync( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ApiFuture<ListProgramsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListProgramsFixedSizeCollection extends AbstractFixedSizeCollection< ListProgramsRequest, ListProgramsResponse, Program, ListProgramsPage, ListProgramsFixedSizeCollection> { private ListProgramsFixedSizeCollection(List<ListProgramsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListProgramsFixedSizeCollection createEmptyCollection() { return new ListProgramsFixedSizeCollection(null, 0); } @Override protected ListProgramsFixedSizeCollection createCollection( List<ListProgramsPage> pages, int collectionSize) { return new ListProgramsFixedSizeCollection(pages, collectionSize); } } }
googleapis/google-cloud-java
36,831
java-servicedirectory/proto-google-cloud-servicedirectory-v1/src/main/java/com/google/cloud/servicedirectory/v1/ListNamespacesResponse.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/servicedirectory/v1/registration_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.servicedirectory.v1; /** * * * <pre> * The response message for * [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. * </pre> * * Protobuf type {@code google.cloud.servicedirectory.v1.ListNamespacesResponse} */ public final class ListNamespacesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.servicedirectory.v1.ListNamespacesResponse) ListNamespacesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListNamespacesResponse.newBuilder() to construct. private ListNamespacesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListNamespacesResponse() { namespaces_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListNamespacesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.servicedirectory.v1.RegistrationServiceProto .internal_static_google_cloud_servicedirectory_v1_ListNamespacesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.servicedirectory.v1.RegistrationServiceProto .internal_static_google_cloud_servicedirectory_v1_ListNamespacesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.servicedirectory.v1.ListNamespacesResponse.class, com.google.cloud.servicedirectory.v1.ListNamespacesResponse.Builder.class); } public static final int NAMESPACES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.servicedirectory.v1.Namespace> namespaces_; /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.servicedirectory.v1.Namespace> getNamespacesList() { return namespaces_; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.servicedirectory.v1.NamespaceOrBuilder> getNamespacesOrBuilderList() { return namespaces_; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ @java.lang.Override public int getNamespacesCount() { return namespaces_.size(); } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ @java.lang.Override public com.google.cloud.servicedirectory.v1.Namespace getNamespaces(int index) { return namespaces_.get(index); } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ @java.lang.Override public com.google.cloud.servicedirectory.v1.NamespaceOrBuilder getNamespacesOrBuilder(int index) { return namespaces_.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 < namespaces_.size(); i++) { output.writeMessage(1, namespaces_.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 < namespaces_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, namespaces_.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.servicedirectory.v1.ListNamespacesResponse)) { return super.equals(obj); } com.google.cloud.servicedirectory.v1.ListNamespacesResponse other = (com.google.cloud.servicedirectory.v1.ListNamespacesResponse) obj; if (!getNamespacesList().equals(other.getNamespacesList())) 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 (getNamespacesCount() > 0) { hash = (37 * hash) + NAMESPACES_FIELD_NUMBER; hash = (53 * hash) + getNamespacesList().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.servicedirectory.v1.ListNamespacesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse 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.servicedirectory.v1.ListNamespacesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse 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.servicedirectory.v1.ListNamespacesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse 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.servicedirectory.v1.ListNamespacesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse 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.servicedirectory.v1.ListNamespacesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse 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.servicedirectory.v1.ListNamespacesResponse 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 * [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. * </pre> * * Protobuf type {@code google.cloud.servicedirectory.v1.ListNamespacesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.servicedirectory.v1.ListNamespacesResponse) com.google.cloud.servicedirectory.v1.ListNamespacesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.servicedirectory.v1.RegistrationServiceProto .internal_static_google_cloud_servicedirectory_v1_ListNamespacesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.servicedirectory.v1.RegistrationServiceProto .internal_static_google_cloud_servicedirectory_v1_ListNamespacesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.servicedirectory.v1.ListNamespacesResponse.class, com.google.cloud.servicedirectory.v1.ListNamespacesResponse.Builder.class); } // Construct using com.google.cloud.servicedirectory.v1.ListNamespacesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (namespacesBuilder_ == null) { namespaces_ = java.util.Collections.emptyList(); } else { namespaces_ = null; namespacesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.servicedirectory.v1.RegistrationServiceProto .internal_static_google_cloud_servicedirectory_v1_ListNamespacesResponse_descriptor; } @java.lang.Override public com.google.cloud.servicedirectory.v1.ListNamespacesResponse getDefaultInstanceForType() { return com.google.cloud.servicedirectory.v1.ListNamespacesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.servicedirectory.v1.ListNamespacesResponse build() { com.google.cloud.servicedirectory.v1.ListNamespacesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.servicedirectory.v1.ListNamespacesResponse buildPartial() { com.google.cloud.servicedirectory.v1.ListNamespacesResponse result = new com.google.cloud.servicedirectory.v1.ListNamespacesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.servicedirectory.v1.ListNamespacesResponse result) { if (namespacesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { namespaces_ = java.util.Collections.unmodifiableList(namespaces_); bitField0_ = (bitField0_ & ~0x00000001); } result.namespaces_ = namespaces_; } else { result.namespaces_ = namespacesBuilder_.build(); } } private void buildPartial0(com.google.cloud.servicedirectory.v1.ListNamespacesResponse 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.servicedirectory.v1.ListNamespacesResponse) { return mergeFrom((com.google.cloud.servicedirectory.v1.ListNamespacesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.servicedirectory.v1.ListNamespacesResponse other) { if (other == com.google.cloud.servicedirectory.v1.ListNamespacesResponse.getDefaultInstance()) return this; if (namespacesBuilder_ == null) { if (!other.namespaces_.isEmpty()) { if (namespaces_.isEmpty()) { namespaces_ = other.namespaces_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureNamespacesIsMutable(); namespaces_.addAll(other.namespaces_); } onChanged(); } } else { if (!other.namespaces_.isEmpty()) { if (namespacesBuilder_.isEmpty()) { namespacesBuilder_.dispose(); namespacesBuilder_ = null; namespaces_ = other.namespaces_; bitField0_ = (bitField0_ & ~0x00000001); namespacesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getNamespacesFieldBuilder() : null; } else { namespacesBuilder_.addAllMessages(other.namespaces_); } } } 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.servicedirectory.v1.Namespace m = input.readMessage( com.google.cloud.servicedirectory.v1.Namespace.parser(), extensionRegistry); if (namespacesBuilder_ == null) { ensureNamespacesIsMutable(); namespaces_.add(m); } else { namespacesBuilder_.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.servicedirectory.v1.Namespace> namespaces_ = java.util.Collections.emptyList(); private void ensureNamespacesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { namespaces_ = new java.util.ArrayList<com.google.cloud.servicedirectory.v1.Namespace>(namespaces_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.servicedirectory.v1.Namespace, com.google.cloud.servicedirectory.v1.Namespace.Builder, com.google.cloud.servicedirectory.v1.NamespaceOrBuilder> namespacesBuilder_; /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public java.util.List<com.google.cloud.servicedirectory.v1.Namespace> getNamespacesList() { if (namespacesBuilder_ == null) { return java.util.Collections.unmodifiableList(namespaces_); } else { return namespacesBuilder_.getMessageList(); } } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public int getNamespacesCount() { if (namespacesBuilder_ == null) { return namespaces_.size(); } else { return namespacesBuilder_.getCount(); } } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public com.google.cloud.servicedirectory.v1.Namespace getNamespaces(int index) { if (namespacesBuilder_ == null) { return namespaces_.get(index); } else { return namespacesBuilder_.getMessage(index); } } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder setNamespaces(int index, com.google.cloud.servicedirectory.v1.Namespace value) { if (namespacesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNamespacesIsMutable(); namespaces_.set(index, value); onChanged(); } else { namespacesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder setNamespaces( int index, com.google.cloud.servicedirectory.v1.Namespace.Builder builderForValue) { if (namespacesBuilder_ == null) { ensureNamespacesIsMutable(); namespaces_.set(index, builderForValue.build()); onChanged(); } else { namespacesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder addNamespaces(com.google.cloud.servicedirectory.v1.Namespace value) { if (namespacesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNamespacesIsMutable(); namespaces_.add(value); onChanged(); } else { namespacesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder addNamespaces(int index, com.google.cloud.servicedirectory.v1.Namespace value) { if (namespacesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNamespacesIsMutable(); namespaces_.add(index, value); onChanged(); } else { namespacesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder addNamespaces( com.google.cloud.servicedirectory.v1.Namespace.Builder builderForValue) { if (namespacesBuilder_ == null) { ensureNamespacesIsMutable(); namespaces_.add(builderForValue.build()); onChanged(); } else { namespacesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder addNamespaces( int index, com.google.cloud.servicedirectory.v1.Namespace.Builder builderForValue) { if (namespacesBuilder_ == null) { ensureNamespacesIsMutable(); namespaces_.add(index, builderForValue.build()); onChanged(); } else { namespacesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder addAllNamespaces( java.lang.Iterable<? extends com.google.cloud.servicedirectory.v1.Namespace> values) { if (namespacesBuilder_ == null) { ensureNamespacesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, namespaces_); onChanged(); } else { namespacesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder clearNamespaces() { if (namespacesBuilder_ == null) { namespaces_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { namespacesBuilder_.clear(); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public Builder removeNamespaces(int index) { if (namespacesBuilder_ == null) { ensureNamespacesIsMutable(); namespaces_.remove(index); onChanged(); } else { namespacesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public com.google.cloud.servicedirectory.v1.Namespace.Builder getNamespacesBuilder(int index) { return getNamespacesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public com.google.cloud.servicedirectory.v1.NamespaceOrBuilder getNamespacesOrBuilder( int index) { if (namespacesBuilder_ == null) { return namespaces_.get(index); } else { return namespacesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public java.util.List<? extends com.google.cloud.servicedirectory.v1.NamespaceOrBuilder> getNamespacesOrBuilderList() { if (namespacesBuilder_ != null) { return namespacesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(namespaces_); } } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public com.google.cloud.servicedirectory.v1.Namespace.Builder addNamespacesBuilder() { return getNamespacesFieldBuilder() .addBuilder(com.google.cloud.servicedirectory.v1.Namespace.getDefaultInstance()); } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public com.google.cloud.servicedirectory.v1.Namespace.Builder addNamespacesBuilder(int index) { return getNamespacesFieldBuilder() .addBuilder(index, com.google.cloud.servicedirectory.v1.Namespace.getDefaultInstance()); } /** * * * <pre> * The list of namespaces. * </pre> * * <code>repeated .google.cloud.servicedirectory.v1.Namespace namespaces = 1;</code> */ public java.util.List<com.google.cloud.servicedirectory.v1.Namespace.Builder> getNamespacesBuilderList() { return getNamespacesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.servicedirectory.v1.Namespace, com.google.cloud.servicedirectory.v1.Namespace.Builder, com.google.cloud.servicedirectory.v1.NamespaceOrBuilder> getNamespacesFieldBuilder() { if (namespacesBuilder_ == null) { namespacesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.servicedirectory.v1.Namespace, com.google.cloud.servicedirectory.v1.Namespace.Builder, com.google.cloud.servicedirectory.v1.NamespaceOrBuilder>( namespaces_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); namespaces_ = null; } return namespacesBuilder_; } 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.servicedirectory.v1.ListNamespacesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.servicedirectory.v1.ListNamespacesResponse) private static final com.google.cloud.servicedirectory.v1.ListNamespacesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.servicedirectory.v1.ListNamespacesResponse(); } public static com.google.cloud.servicedirectory.v1.ListNamespacesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListNamespacesResponse> PARSER = new com.google.protobuf.AbstractParser<ListNamespacesResponse>() { @java.lang.Override public ListNamespacesResponse 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<ListNamespacesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListNamespacesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.servicedirectory.v1.ListNamespacesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/drill
37,074
exec/java-exec/src/main/java/org/apache/drill/exec/client/DrillClient.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.drill.exec.client; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.apache.drill.exec.proto.UserProtos.QueryResultsMode.STREAM_FULL; import static org.apache.drill.exec.proto.UserProtos.RunQuery.newBuilder; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.drill.common.DrillAutoCloseables; import org.apache.drill.common.Version; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.config.DrillProperties; import org.apache.drill.common.exceptions.DrillRuntimeException; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.common.util.JacksonUtils; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.coord.ClusterCoordinator; import org.apache.drill.exec.coord.zk.ZKClusterCoordinator; import org.apache.drill.exec.exception.OutOfMemoryException; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.memory.RootAllocatorFactory; import org.apache.drill.exec.proto.BitControl.PlanFragment; import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint; import org.apache.drill.exec.proto.GeneralRPCProtos; import org.apache.drill.exec.proto.GeneralRPCProtos.Ack; import org.apache.drill.exec.proto.UserBitShared; import org.apache.drill.exec.proto.UserBitShared.QueryId; import org.apache.drill.exec.proto.UserBitShared.QueryResult.QueryState; import org.apache.drill.exec.proto.UserBitShared.QueryType; import org.apache.drill.exec.proto.UserProtos; import org.apache.drill.exec.proto.UserProtos.CreatePreparedStatementReq; import org.apache.drill.exec.proto.UserProtos.CreatePreparedStatementResp; import org.apache.drill.exec.proto.UserProtos.GetCatalogsReq; import org.apache.drill.exec.proto.UserProtos.GetCatalogsResp; import org.apache.drill.exec.proto.UserProtos.GetColumnsReq; import org.apache.drill.exec.proto.UserProtos.GetColumnsResp; import org.apache.drill.exec.proto.UserProtos.GetQueryPlanFragments; import org.apache.drill.exec.proto.UserProtos.GetSchemasReq; import org.apache.drill.exec.proto.UserProtos.GetSchemasResp; import org.apache.drill.exec.proto.UserProtos.GetServerMetaReq; import org.apache.drill.exec.proto.UserProtos.GetServerMetaResp; import org.apache.drill.exec.proto.UserProtos.GetTablesReq; import org.apache.drill.exec.proto.UserProtos.GetTablesResp; import org.apache.drill.exec.proto.UserProtos.LikeFilter; import org.apache.drill.exec.proto.UserProtos.PreparedStatementHandle; import org.apache.drill.exec.proto.UserProtos.QueryPlanFragments; import org.apache.drill.exec.proto.UserProtos.RpcEndpointInfos; import org.apache.drill.exec.proto.UserProtos.RpcType; import org.apache.drill.exec.proto.UserProtos.RunQuery; import org.apache.drill.exec.proto.helper.QueryIdHelper; import org.apache.drill.exec.rpc.ChannelClosedException; import org.apache.drill.exec.rpc.ConnectionThrottle; import org.apache.drill.exec.rpc.DrillRpcFuture; import org.apache.drill.exec.rpc.NamedThreadFactory; import org.apache.drill.exec.rpc.NonTransientRpcException; import org.apache.drill.exec.rpc.RpcException; import org.apache.drill.exec.rpc.TransportCheck; import org.apache.drill.exec.rpc.user.QueryDataBatch; import org.apache.drill.exec.rpc.user.UserClient; import org.apache.drill.exec.rpc.user.UserResultsListener; import org.apache.drill.exec.rpc.user.UserRpcUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.util.concurrent.SettableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.EventLoopGroup; /** * Thin wrapper around a UserClient that handles connect/close and transforms * String into ByteBuf. */ public class DrillClient implements Closeable, ConnectionThrottle { private static Logger logger = LoggerFactory.getLogger(DrillClient.class); public static final String DEFAULT_CLIENT_NAME = "Apache Drill Java client"; private static final ObjectMapper objectMapper = JacksonUtils.createObjectMapper(); private final DrillConfig config; private UserClient client; private DrillProperties properties; private volatile ClusterCoordinator clusterCoordinator; private volatile boolean connected; private final BufferAllocator allocator; private final int reconnectTimes; private final int reconnectDelay; private boolean supportComplexTypes; private final boolean ownsZkConnection; private final boolean ownsAllocator; private final boolean isDirectConnection; // true if the connection bypasses zookeeper and connects directly to a drillbit private EventLoopGroup eventLoopGroup; private ExecutorService executor; private String clientName = DEFAULT_CLIENT_NAME; public DrillClient() throws OutOfMemoryException { this(DrillConfig.create(), false); } public DrillClient(boolean isDirect) throws OutOfMemoryException { this(DrillConfig.create(), isDirect); } public DrillClient(String fileName) throws OutOfMemoryException { this(DrillConfig.create(fileName), false); } public DrillClient(DrillConfig config) throws OutOfMemoryException { this(config, null, false); } public DrillClient(DrillConfig config, boolean isDirect) throws OutOfMemoryException { this(config, null, isDirect); } public DrillClient(DrillConfig config, ClusterCoordinator coordinator) throws OutOfMemoryException { this(config, coordinator, null, false); } public DrillClient(DrillConfig config, ClusterCoordinator coordinator, boolean isDirect) throws OutOfMemoryException { this(config, coordinator, null, isDirect); } public DrillClient(DrillConfig config, ClusterCoordinator coordinator, BufferAllocator allocator) throws OutOfMemoryException { this(config, coordinator, allocator, false); } public DrillClient(DrillConfig config, ClusterCoordinator coordinator, BufferAllocator allocator, boolean isDirect) { // if isDirect is true, the client will connect directly to the drillbit instead of // going thru the zookeeper this.isDirectConnection = isDirect; this.ownsZkConnection = coordinator == null && !isDirect; this.ownsAllocator = allocator == null; this.allocator = ownsAllocator ? RootAllocatorFactory.newRoot(config) : allocator; this.config = config; this.clusterCoordinator = coordinator; this.reconnectTimes = config.getInt(ExecConstants.BIT_RETRY_TIMES); this.reconnectDelay = config.getInt(ExecConstants.BIT_RETRY_DELAY); this.supportComplexTypes = config.getBoolean(ExecConstants.CLIENT_SUPPORT_COMPLEX_TYPES); } public DrillConfig getConfig() { return config; } @Override public void setAutoRead(boolean enableAutoRead) { client.setAutoRead(enableAutoRead); } /** * Sets the client name. * * If not set, default is {@code DrillClient#DEFAULT_CLIENT_NAME}. * * @param name the client name * * @throws IllegalStateException if called after a connection has been established. * @throws NullPointerException if client name is null */ public void setClientName(String name) { if (connected) { throw new IllegalStateException("Attempted to modify client connection property after connection has been established."); } this.clientName = checkNotNull(name, "client name should not be null"); } /** * Sets whether the application is willing to accept complex types (Map, * Arrays) in the returned result set. Default is {@code true}. If set to * {@code false}, the complex types are returned as JSON encoded VARCHAR type. * * @throws IllegalStateException * if called after a connection has been established. */ public void setSupportComplexTypes(boolean supportComplexTypes) { if (connected) { throw new IllegalStateException("Attempted to modify client connection property after connection has been established."); } this.supportComplexTypes = supportComplexTypes; } /** * Connects the client to a Drillbit server * * @throws RpcException */ public void connect() throws RpcException { connect(null, new Properties()); } /** * Start's a connection from client to server * @param props - not null {@link Properties} filled with connection url parameters * @throws RpcException */ public void connect(Properties props) throws RpcException { connect(null, props); } /** * Populates the endpointlist with drillbits information provided in the connection string by client. * For direct connection we can have connection string with drillbit property as below: * <dl> * <dt>drillbit=ip</dt> * <dd>use the ip specified as the Foreman ip with default port in config file</dd> * <dt>drillbit=ip:port</dt> * <dd>use the ip and port specified as the Foreman ip and port</dd> * <dt>drillbit=ip1:port1,ip2:port2,...</dt> * <dd>randomly select the ip and port pair from the specified list as the Foreman ip and port.</dd> * </dl> * * @param drillbits string with drillbit value provided in connection string * @param defaultUserPort string with default userport of drillbit specified in config file * @return list of drillbit endpoints parsed from connection string * @throws InvalidConnectionInfoException if the connection string has invalid or no drillbit information */ static List<DrillbitEndpoint> parseAndVerifyEndpoints(String drillbits, String defaultUserPort) throws InvalidConnectionInfoException { // If no drillbits is provided then throw exception drillbits = drillbits.trim(); if (drillbits.isEmpty()) { throw new InvalidConnectionInfoException("No drillbit information specified in the connection string"); } final List<DrillbitEndpoint> endpointList = new ArrayList<>(); final String[] connectInfo = drillbits.split(","); // Fetch ip address and port information for each drillbit and populate the list for (String drillbit : connectInfo) { // Trim all the empty spaces and check if the entry is empty string. // Ignore the empty ones. drillbit = drillbit.trim(); if (!drillbit.isEmpty()) { // Verify if we have only ":" or only ":port" pattern if (drillbit.charAt(0) == ':') { // Invalid drillbit information throw new InvalidConnectionInfoException("Malformed connection string with drillbit hostname or " + "hostaddress missing for an entry: " + drillbit); } // We are now sure that each ip:port entry will have both the values atleast once. // Split each drillbit connection string to get ip address and port value final String[] drillbitInfo = drillbit.split(":"); // Check if we have more than one port if (drillbitInfo.length > 2) { throw new InvalidConnectionInfoException("Malformed connection string with more than one port in a " + "drillbit entry: " + drillbit); } // At this point we are sure that drillbitInfo has atleast hostname or host address // trim all the empty spaces which might be present in front of hostname or // host address information final String ipAddress = drillbitInfo[0].trim(); String port = defaultUserPort; if (drillbitInfo.length == 2) { // We have a port value also given by user. trim all the empty spaces between : and port value before // validating the correctness of value. port = drillbitInfo[1].trim(); } try { final DrillbitEndpoint endpoint = DrillbitEndpoint.newBuilder() .setAddress(ipAddress) .setUserPort(Integer.parseInt(port)) .build(); endpointList.add(endpoint); } catch (NumberFormatException e) { throw new InvalidConnectionInfoException("Malformed port value in entry: " + ipAddress + ":" + port + " " + "passed in connection string"); } } } if (endpointList.size() == 0) { throw new InvalidConnectionInfoException("No valid drillbit information specified in the connection string"); } return endpointList; } /** * Start's a connection from client to server * @param connect - Zookeeper connection string provided at connection URL * @param props - not null {@link Properties} filled with connection url parameters * @throws RpcException */ public synchronized void connect(String connect, Properties props) throws RpcException { if (connected) { return; } properties = DrillProperties.createFromProperties(props); final List<DrillbitEndpoint> endpoints = new ArrayList<>(); if (isDirectConnection) { // Populate the endpoints list with all the drillbit information provided in the connection string endpoints.addAll(parseAndVerifyEndpoints(properties.getProperty(DrillProperties.DRILLBIT_CONNECTION), config.getString(ExecConstants.INITIAL_USER_PORT))); } else { if (ownsZkConnection) { try { this.clusterCoordinator = new ZKClusterCoordinator(this.config, connect); this.clusterCoordinator.start(10000); } catch (Exception e) { throw new RpcException("Failure setting up ZK for client.", e); } } // Gets the drillbit endpoints that are ONLINE and excludes the drillbits that are // in QUIESCENT state. This avoids the clients connecting to drillbits that are // shutting down thereby avoiding reducing the chances of query failures. endpoints.addAll(clusterCoordinator.getOnlineEndPoints()); // Make sure we have at least one endpoint in the list checkState(!endpoints.isEmpty(), "No active Drillbit endpoint found from ZooKeeper. Check connection parameters?"); } // shuffle the collection then get the first endpoint Collections.shuffle(endpoints); eventLoopGroup = createEventLoop(config.getInt(ExecConstants.CLIENT_RPC_THREADS), "Client-"); executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("drill-client-executor-")) { @Override protected void afterExecute(final Runnable r, final Throwable t) { if (t != null) { logger.error("{}.run() leaked an exception.", r.getClass().getName(), t); } super.afterExecute(r, t); } }; final String connectTriesConf = properties.getProperty(DrillProperties.TRIES, "5"); int connectTriesVal; try { connectTriesVal = Math.min(endpoints.size(), Integer.parseInt(connectTriesConf)); } catch (NumberFormatException e) { throw new InvalidConnectionInfoException("Invalid tries value: " + connectTriesConf + " specified in " + "connection string"); } // If the value provided in the connection string is <=0 then override with 1 since we want to try connecting // at least once connectTriesVal = Math.max(1, connectTriesVal); int triedEndpointIndex = 0; DrillbitEndpoint endpoint; while (triedEndpointIndex < connectTriesVal) { endpoint = endpoints.get(triedEndpointIndex); // Set in both props and properties since props is passed to UserClient // TODO: Logically here it's doing putIfAbsent, please change to use that api once JDK 8 is minimum required // version if (!properties.containsKey(DrillProperties.SERVICE_HOST)) { properties.setProperty(DrillProperties.SERVICE_HOST, endpoint.getAddress()); props.setProperty(DrillProperties.SERVICE_HOST, endpoint.getAddress()); } // Note: the properties member is a DrillProperties instance which lower cases names of // properties. That does not work too well with properties that are mixed case. // For user client severla properties are mixed case so we do not use the properties member // but instead pass the props parameter. client = new UserClient(clientName, config, props, supportComplexTypes, allocator, eventLoopGroup, executor, endpoint); logger.debug("Connecting to server {}:{}", endpoint.getAddress(), endpoint.getUserPort()); try { connect(endpoint); connected = true; logger.info("Successfully connected to server {}:{}", endpoint.getAddress(), endpoint.getUserPort()); break; } catch (NonTransientRpcException ex) { logger.error("Connection to {}:{} failed with error {}. Not retrying anymore", endpoint.getAddress(), endpoint.getUserPort(), ex.getMessage()); throw ex; } catch (RpcException ex) { ++triedEndpointIndex; logger.error("Attempt {}: Failed to connect to server {}:{}", triedEndpointIndex, endpoint.getAddress(), endpoint.getUserPort()); // Throw exception when we have exhausted all the tries without having a successful connection if (triedEndpointIndex == connectTriesVal) { throw ex; } // Close the connection here to avoid calling close twice in case when all tries are exhausted. // Since DrillClient.close is also calling client.close client.close(); } } } protected static EventLoopGroup createEventLoop(int size, String prefix) { return TransportCheck.createEventLoopGroup(size, prefix); } public synchronized boolean reconnect() { if (client.isActive()) { return true; } int retry = reconnectTimes; while (retry > 0) { retry--; try { Thread.sleep(this.reconnectDelay); // Gets the drillbit endpoints that are ONLINE and excludes the drillbits that are // in QUIESCENT state. This avoids the clients connecting to drillbits that are // shutting down thereby reducing the chances of query failures. final ArrayList<DrillbitEndpoint> endpoints = new ArrayList<>(clusterCoordinator.getOnlineEndPoints()); if (endpoints.isEmpty()) { continue; } client.close(); Collections.shuffle(endpoints); connect(endpoints.iterator().next()); return true; } catch (Exception e) { } } return false; } private void connect(DrillbitEndpoint endpoint) throws RpcException { client.connect(endpoint, properties, getUserCredentials()); logger.info("Foreman drillbit is {}", endpoint.getAddress()); } public BufferAllocator getAllocator() { return allocator; } /** * Closes this client's connection to the server */ @Override public void close() { if (client != null) { client.close(); } if (ownsAllocator && allocator != null) { DrillAutoCloseables.closeNoChecked(allocator); } if (ownsZkConnection) { if (clusterCoordinator != null) { try { clusterCoordinator.close(); clusterCoordinator = null; } catch (Exception e) { logger.warn("Error while closing Cluster Coordinator.", e); } } } if (eventLoopGroup != null) { eventLoopGroup.shutdownGracefully(); eventLoopGroup = null; } if (executor != null) { executor.shutdownNow(); executor = null; } connected = false; } /** * Return the server infos. Only available after connecting * * The result might be null if the server doesn't provide the informations. * * @return the server informations, or null if not connected or if the server * doesn't provide the information * @deprecated use {@code DrillClient#getServerVersion()} */ @Deprecated public RpcEndpointInfos getServerInfos() { return client != null ? client.getServerInfos() : null; } /** * Return the server name. Only available after connecting * * The result might be null if the server doesn't provide the name information. * * @return the server name, or null if not connected or if the server * doesn't provide the name * @return The server name. */ public String getServerName() { return (client != null && client.getServerInfos() != null) ? client.getServerInfos().getName() : null; } /** * Return the server version. Only available after connecting * * The result might be null if the server doesn't provide the version information. * * @return the server version, or null if not connected or if the server * doesn't provide the version * @return The server version. */ public Version getServerVersion() { return (client != null && client.getServerInfos() != null) ? UserRpcUtils.getVersion(client.getServerInfos()) : null; } /** * Get server meta information * * Get meta information about the server like the the available functions * or the identifier quoting string used by the current session * * @return a future to the server meta response */ public DrillRpcFuture<GetServerMetaResp> getServerMeta() { return client.send(RpcType.GET_SERVER_META, GetServerMetaReq.getDefaultInstance(), GetServerMetaResp.class); } /** * Returns the list of methods supported by the server based on its advertised information. * * @return an immutable set of capabilities */ public Set<ServerMethod> getSupportedMethods() { return client != null ? ServerMethod.getSupportedMethods(client.getSupportedMethods(), client.getServerInfos()) : null; } /** * Submits a string based query plan for execution and returns the result batches. Supported query types are: * <p><ul> * <li>{@link QueryType#LOGICAL} * <li>{@link QueryType#PHYSICAL} * <li>{@link QueryType#SQL} * </ul> * * @param type Query type * @param plan Query to execute * @return a handle for the query result * @throws RpcException */ public List<QueryDataBatch> runQuery(QueryType type, String plan) throws RpcException { checkArgument(type == QueryType.LOGICAL || type == QueryType.PHYSICAL || type == QueryType.SQL, String.format("Only query types %s, %s and %s are supported in this API", QueryType.LOGICAL, QueryType.PHYSICAL, QueryType.SQL)); final UserProtos.RunQuery query = newBuilder().setResultsMode(STREAM_FULL).setType(type).setPlan(plan).build(); final ListHoldingResultsListener listener = new ListHoldingResultsListener(query); client.submitQuery(listener, query); return listener.getResults(); } /** * API to just plan a query without execution * * @param type * @param query * @param isSplitPlan * option to tell whether to return single or split plans for a query * @return list of PlanFragments that can be used later on in * {@link #runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType, * java.util.List, org.apache.drill.exec.rpc.user.UserResultsListener)} * to run a query without additional planning */ public DrillRpcFuture<QueryPlanFragments> planQuery(QueryType type, String query, boolean isSplitPlan) { GetQueryPlanFragments runQuery = GetQueryPlanFragments.newBuilder().setQuery(query).setType(type).setSplitPlan(isSplitPlan).build(); return client.planQuery(runQuery); } /** * Run query based on list of fragments that were supposedly produced during query planning phase. Supported * query type is {@link QueryType#EXECUTION} * @param type * @param planFragments * @param resultsListener * @throws RpcException */ public void runQuery(QueryType type, List<PlanFragment> planFragments, UserResultsListener resultsListener) throws RpcException { // QueryType can be only executional checkArgument((QueryType.EXECUTION == type), "Only EXECUTION type query is supported with PlanFragments"); // setting Plan on RunQuery will be used for logging purposes and therefore can not be null // since there is no Plan string provided we will create a JsonArray out of individual fragment Plans ArrayNode jsonArray = objectMapper.createArrayNode(); for (PlanFragment fragment : planFragments) { try { jsonArray.add(objectMapper.readTree(fragment.getFragmentJson())); } catch (IOException e) { logger.error("Exception while trying to read PlanFragment JSON for {}", fragment.getHandle().getQueryId(), e); throw new RpcException(e); } } final String fragmentsToJsonString; try { fragmentsToJsonString = objectMapper.writeValueAsString(jsonArray); } catch (JsonProcessingException e) { logger.error("Exception while trying to get JSONString from Array of individual Fragments Json for %s", e); throw new RpcException(e); } final UserProtos.RunQuery query = newBuilder().setType(type).addAllFragments(planFragments) .setPlan(fragmentsToJsonString) .setResultsMode(STREAM_FULL).build(); client.submitQuery(resultsListener, query); } /** * Helper method to generate the UserCredentials message from the properties. */ private UserBitShared.UserCredentials getUserCredentials() { String userName = properties.getProperty(DrillProperties.USER); if (Strings.isNullOrEmpty(userName)) { userName = "anonymous"; // if username is not propagated as one of the properties } return UserBitShared.UserCredentials.newBuilder() .setUserName(userName) .build(); } public DrillRpcFuture<Ack> cancelQuery(QueryId id) { if(logger.isDebugEnabled()) { logger.debug("Cancelling query {}", QueryIdHelper.getQueryId(id)); } return client.send(RpcType.CANCEL_QUERY, id, Ack.class); } public DrillRpcFuture<Ack> resumeQuery(final QueryId queryId) { if(logger.isDebugEnabled()) { logger.debug("Resuming query {}", QueryIdHelper.getQueryId(queryId)); } return client.send(RpcType.RESUME_PAUSED_QUERY, queryId, Ack.class); } /** * Get the list of catalogs in {@code INFORMATION_SCHEMA.CATALOGS} table satisfying the given filters. * * @param catalogNameFilter Filter on {@code catalog name}. Pass null to apply no filter. * @return The list of catalogs in {@code INFORMATION_SCHEMA.CATALOGS} table satisfying the given filters. */ public DrillRpcFuture<GetCatalogsResp> getCatalogs(LikeFilter catalogNameFilter) { final GetCatalogsReq.Builder reqBuilder = GetCatalogsReq.newBuilder(); if (catalogNameFilter != null) { reqBuilder.setCatalogNameFilter(catalogNameFilter); } return client.send(RpcType.GET_CATALOGS, reqBuilder.build(), GetCatalogsResp.class); } /** * Get the list of schemas in {@code INFORMATION_SCHEMA.SCHEMATA} table satisfying the given filters. * * @param catalogNameFilter Filter on {@code catalog name}. Pass null to apply no filter. * @param schemaNameFilter Filter on {@code schema name}. Pass null to apply no filter. * @return The list of schemas in {@code INFORMATION_SCHEMA.SCHEMATA} table satisfying the given filters. */ public DrillRpcFuture<GetSchemasResp> getSchemas(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter) { final GetSchemasReq.Builder reqBuilder = GetSchemasReq.newBuilder(); if (catalogNameFilter != null) { reqBuilder.setCatalogNameFilter(catalogNameFilter); } if (schemaNameFilter != null) { reqBuilder.setSchemaNameFilter(schemaNameFilter); } return client.send(RpcType.GET_SCHEMAS, reqBuilder.build(), GetSchemasResp.class); } /** * Get the list of tables in {@code INFORMATION_SCHEMA.TABLES} table satisfying the given filters. * * @param catalogNameFilter Filter on {@code catalog name}. Pass null to apply no filter. * @param schemaNameFilter Filter on {@code schema name}. Pass null to apply no filter. * @param tableNameFilter Filter in {@code table name}. Pass null to apply no filter. * @param tableTypeFilter Filter in {@code table type}. Pass null to apply no filter * @return The list of tables in {@code INFORMATION_SCHEMA.TABLES} table satisfying the given filters. */ public DrillRpcFuture<GetTablesResp> getTables(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter, LikeFilter tableNameFilter, List<String> tableTypeFilter) { final GetTablesReq.Builder reqBuilder = GetTablesReq.newBuilder(); if (catalogNameFilter != null) { reqBuilder.setCatalogNameFilter(catalogNameFilter); } if (schemaNameFilter != null) { reqBuilder.setSchemaNameFilter(schemaNameFilter); } if (tableNameFilter != null) { reqBuilder.setTableNameFilter(tableNameFilter); } if (tableTypeFilter != null) { reqBuilder.addAllTableTypeFilter(tableTypeFilter); } return client.send(RpcType.GET_TABLES, reqBuilder.build(), GetTablesResp.class); } /** * Get the list of columns in {@code INFORMATION_SCHEMA.COLUMNS} table satisfying the given filters. * * @param catalogNameFilter Filter on {@code catalog name}. Pass null to apply no filter. * @param schemaNameFilter Filter on {@code schema name}. Pass null to apply no filter. * @param tableNameFilter Filter in {@code table name}. Pass null to apply no filter. * @param columnNameFilter Filter in {@code column name}. Pass null to apply no filter. * @return The list of columns in {@code INFORMATION_SCHEMA.COLUMNS} table satisfying the given filters. */ public DrillRpcFuture<GetColumnsResp> getColumns(LikeFilter catalogNameFilter, LikeFilter schemaNameFilter, LikeFilter tableNameFilter, LikeFilter columnNameFilter) { final GetColumnsReq.Builder reqBuilder = GetColumnsReq.newBuilder(); if (catalogNameFilter != null) { reqBuilder.setCatalogNameFilter(catalogNameFilter); } if (schemaNameFilter != null) { reqBuilder.setSchemaNameFilter(schemaNameFilter); } if (tableNameFilter != null) { reqBuilder.setTableNameFilter(tableNameFilter); } if (columnNameFilter != null) { reqBuilder.setColumnNameFilter(columnNameFilter); } return client.send(RpcType.GET_COLUMNS, reqBuilder.build(), GetColumnsResp.class); } /** * Create a prepared statement for given the {@code query}. * * @param query * @return The prepared statement for given the {@code query}. */ public DrillRpcFuture<CreatePreparedStatementResp> createPreparedStatement(final String query) { final CreatePreparedStatementReq req = CreatePreparedStatementReq.newBuilder() .setSqlQuery(query) .build(); return client.send(RpcType.CREATE_PREPARED_STATEMENT, req, CreatePreparedStatementResp.class); } /** * Execute the given prepared statement. * * @param preparedStatementHandle Prepared statement handle returned in response to * {@link #createPreparedStatement(String)}. * @param resultsListener {@link UserResultsListener} instance for listening for query results. */ public void executePreparedStatement(final PreparedStatementHandle preparedStatementHandle, final UserResultsListener resultsListener) { final RunQuery runQuery = newBuilder() .setResultsMode(STREAM_FULL) .setType(QueryType.PREPARED_STATEMENT) .setPreparedStatementHandle(preparedStatementHandle) .build(); client.submitQuery(resultsListener, runQuery); } /** * Execute the given prepared statement and return the results. * * @param preparedStatementHandle Prepared statement handle returned in response to * {@link #createPreparedStatement(String)}. * @return List of {@link QueryDataBatch}s. It is responsibility of the caller to release query data batches. * @throws RpcException */ @VisibleForTesting public List<QueryDataBatch> executePreparedStatement(final PreparedStatementHandle preparedStatementHandle) throws RpcException { final RunQuery runQuery = newBuilder() .setResultsMode(STREAM_FULL) .setType(QueryType.PREPARED_STATEMENT) .setPreparedStatementHandle(preparedStatementHandle) .build(); final ListHoldingResultsListener resultsListener = new ListHoldingResultsListener(runQuery); client.submitQuery(resultsListener, runQuery); return resultsListener.getResults(); } /** * Submits a Logical plan for direct execution (bypasses parsing) * * @param plan the plan to execute */ public void runQuery(QueryType type, String plan, UserResultsListener resultsListener) { client.submitQuery(resultsListener, newBuilder().setResultsMode(STREAM_FULL).setType(type).setPlan(plan).build()); } /** * @return true if client has connection and it is connected, false otherwise */ public boolean connectionIsActive() { return client.isActive(); } /** * Verify connection with request-answer. * * @param timeoutSec time in seconds to wait answer receiving. If 0 then won't wait. * @return true if {@link GeneralRPCProtos.RpcMode#PONG PONG} received until timeout, false otherwise */ public boolean hasPing(long timeoutSec) throws DrillRuntimeException { if (timeoutSec < 0) { timeoutSec = 0; } return client.hasPing(timeoutSec); } private class ListHoldingResultsListener implements UserResultsListener { private final Vector<QueryDataBatch> results = new Vector<>(); private final SettableFuture<List<QueryDataBatch>> future = SettableFuture.create(); private final UserProtos.RunQuery query; public ListHoldingResultsListener(UserProtos.RunQuery query) { logger.debug( "Listener created for query \"{}\"", query ); this.query = query; } @Override public void submissionFailed(UserException ex) { // or !client.isActive() if (ex.getCause() instanceof ChannelClosedException) { if (reconnect()) { try { client.submitQuery(this, query); } catch (Exception e) { fail(e); } } else { fail(ex); } } else { fail(ex); } } @Override public void queryCompleted(QueryState state) { future.set(results); } private void fail(Exception ex) { logger.debug("Submission failed.", ex); future.setException(ex); future.set(results); } @Override public void dataArrived(QueryDataBatch result, ConnectionThrottle throttle) { logger.debug("Result arrived: Row count: {}", result.getHeader().getRowCount()); logger.trace("Result batch: {}", result); results.add(result); } public List<QueryDataBatch> getResults() throws RpcException { try { return future.get(); } catch (Throwable t) { /* * Since we're not going to return the result to the caller * to clean up, we have to do it. */ for(final QueryDataBatch queryDataBatch : results) { queryDataBatch.release(); } throw RpcException.mapException(t); } } @Override public void queryIdArrived(QueryId queryId) { if (logger.isDebugEnabled()) { logger.debug("Query ID arrived: {}", QueryIdHelper.getQueryId(queryId)); } } } }
apache/samza
37,339
samza-core/src/main/java/org/apache/samza/clustermanager/ContainerManager.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.samza.clustermanager; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.time.Duration; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.samza.clustermanager.container.placement.ContainerPlacementMetadataStore; import org.apache.samza.clustermanager.container.placement.ContainerPlacementMetadata; import org.apache.samza.config.Config; import org.apache.samza.container.LocalityManager; import org.apache.samza.container.placement.ContainerPlacementMessage; import org.apache.samza.container.placement.ContainerPlacementRequestMessage; import org.apache.samza.container.placement.ContainerPlacementResponseMessage; import org.apache.samza.job.model.ProcessorLocality; import org.apache.samza.util.BoundedLinkedHashSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ContainerManager is a centralized entity that manages container actions like start, stop for both active and standby containers * ContainerManager acts as a brain for validating and issuing any actions on containers in the Job Coordinator. * * The requests to allocate resources resources made by {@link ContainerAllocator} can either expire or succeed. * When the requests succeeds the ContainerManager validates those requests before starting the container * When the requests expires the ContainerManager decides the next set of actions for the pending request. * * Callbacks issued from {@link ClusterResourceManager} aka {@link ContainerProcessManager} are intercepted * by ContainerManager to handle container failure and completions for both active and standby containers * * ContainerManager encapsulates logic and state related to container placement actions like move, restarts for active container * if issued externally. * */ public class ContainerManager { private static final Logger LOG = LoggerFactory.getLogger(ContainerManager.class); private static final String ANY_HOST = ResourceRequestState.ANY_HOST; private static final String LAST_SEEN = "LAST_SEEN"; private static final String FORCE_RESTART_LAST_SEEN = "FORCE_RESTART_LAST_SEEN"; private static final int UUID_CACHE_SIZE = 20000; /** * Container placement metadata store to write responses to control actions */ private final ContainerPlacementMetadataStore containerPlacementMetadataStore; /** * Resource-manager, used to stop containers */ private final ClusterResourceManager clusterResourceManager; private final SamzaApplicationState samzaApplicationState; private final boolean hostAffinityEnabled; /** * Map maintaining active container placement action meta data indexed by container's processorId eg 0, 1, 2 * Key is chosen to be processorId since at a time only one placement action can be in progress on a container. */ private final ConcurrentHashMap<String, ContainerPlacementMetadata> actions; /** * In-memory cache of placement requests UUIDs de-queued from the metadata store. Used to de-dup requests with the same * request UUID. Sized using max tolerable memory footprint and max likely duplicate-spacing. */ private final BoundedLinkedHashSet<UUID> placementRequestsCache; private final Optional<StandbyContainerManager> standbyContainerManager; private final LocalityManager localityManager; public ContainerManager(ContainerPlacementMetadataStore containerPlacementMetadataStore, SamzaApplicationState samzaApplicationState, ClusterResourceManager clusterResourceManager, boolean hostAffinityEnabled, boolean standByEnabled, LocalityManager localityManager, FaultDomainManager faultDomainManager, Config config) { Preconditions.checkNotNull(localityManager, "Locality manager cannot be null"); Preconditions.checkNotNull(faultDomainManager, "Fault domain manager cannot be null"); this.samzaApplicationState = samzaApplicationState; this.clusterResourceManager = clusterResourceManager; this.actions = new ConcurrentHashMap<>(); this.placementRequestsCache = new BoundedLinkedHashSet<UUID>(UUID_CACHE_SIZE); this.hostAffinityEnabled = hostAffinityEnabled; this.containerPlacementMetadataStore = containerPlacementMetadataStore; this.localityManager = localityManager; // Enable standby container manager if required if (standByEnabled) { this.standbyContainerManager = Optional.of(new StandbyContainerManager(samzaApplicationState, clusterResourceManager, localityManager, config, faultDomainManager)); } else { this.standbyContainerManager = Optional.empty(); } } /** * Handles the container start action for both active & standby containers. This method is invoked by the allocator thread * * Case 1. If the container launch request is due to an existing container placement action, issue a stop on active * container & wait for the active container to be stopped before issuing a start. * Case 2. If StandbyContainer is present refer to {@code StandbyContainerManager#checkStandbyConstraintsAndRunStreamProcessor} * Case 3. Otherwise just invoke a container start on the allocated resource for the pending request * * TODO: SAMZA-2399: Investigate & configure a timeout for container stop if needed * * @param request pending request for the preferred host * @param preferredHost preferred host to start the container * @param allocatedResource resource allocated from {@link ClusterResourceManager} * @param resourceRequestState state of request in {@link ContainerAllocator} * @param allocator to request resources from @{@link ClusterResourceManager} * * @return true if the container launch is complete, false if the container launch is in progress. A container launch * might be in progress when it is waiting for the previous container incarnation to stop in case of container * placement actions */ boolean handleContainerLaunch(SamzaResourceRequest request, String preferredHost, SamzaResource allocatedResource, ResourceRequestState resourceRequestState, ContainerAllocator allocator) { if (hasActiveContainerPlacementAction(request.getProcessorId())) { String processorId = request.getProcessorId(); ContainerPlacementMetadata actionMetaData = getPlacementActionMetadata(processorId).get(); ContainerPlacementMetadata.ContainerStatus actionStatus = actionMetaData.getContainerStatus(); if (samzaApplicationState.runningProcessors.containsKey(processorId) && actionStatus == ContainerPlacementMetadata.ContainerStatus.RUNNING) { LOG.debug("Requesting running container to shutdown due to existing ContainerPlacement action {}", actionMetaData); actionMetaData.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.STOP_IN_PROGRESS); updateContainerPlacementActionStatus(actionMetaData, ContainerPlacementMessage.StatusCode.IN_PROGRESS, "Active container stop in progress"); clusterResourceManager.stopStreamProcessor(samzaApplicationState.runningProcessors.get(processorId)); return false; } else if (actionStatus == ContainerPlacementMetadata.ContainerStatus.STOP_IN_PROGRESS) { LOG.info("Waiting for running container to shutdown due to existing ContainerPlacement action {}", actionMetaData); return false; } else if (actionStatus == ContainerPlacementMetadata.ContainerStatus.STOP_FAILED) { LOG.info("Shutdown on running container failed for action {}", actionMetaData); markContainerPlacementActionFailed(actionMetaData, String.format("failed to stop container on current host %s", actionMetaData.getSourceHost())); resourceRequestState.cancelResourceRequest(request); return true; } else if (actionStatus == ContainerPlacementMetadata.ContainerStatus.STOPPED) { // If the job has standby containers enabled, always check standby constraints before issuing a start on container // Note: Always check constraints against allocated resource, since preferred host can be ANY_HOST as well if (standbyContainerManager.isPresent() && !standbyContainerManager.get().checkStandbyConstraints(request.getProcessorId(), allocatedResource.getHost())) { LOG.info( "Starting container {} on host {} does not meet standby constraints, falling back to source host placement metadata: {}", request.getProcessorId(), preferredHost, actionMetaData); // Release unstartable container standbyContainerManager.get().releaseUnstartableContainer(request, allocatedResource, preferredHost, resourceRequestState); // Fallback to source host since the new allocated resource does not meet standby constraints allocator.requestResource(processorId, actionMetaData.getSourceHost()); markContainerPlacementActionFailed(actionMetaData, String.format("allocated resource %s does not meet standby constraints now, falling back to source host", allocatedResource)); } else { LOG.info("Status updated for ContainerPlacement action: ", actionMetaData); allocator.runStreamProcessor(request, preferredHost); } return true; } } if (this.standbyContainerManager.isPresent()) { standbyContainerManager.get() .checkStandbyConstraintsAndRunStreamProcessor(request, preferredHost, allocatedResource, allocator, resourceRequestState); } else { allocator.runStreamProcessor(request, preferredHost); } return true; } /** * Handles the action to be taken after the container has been stopped. If stop was issued due to existing control * action, mark the container as stopped, otherwise * * Case 1. When standby is enabled, refer to {@link StandbyContainerManager#handleContainerStop} to check constraints. * Case 2. When standby is disabled there are two cases according to host-affinity being enabled * Case 2.1. When host-affinity is enabled resources are requested on host where container was last seen * Case 2.2. When host-affinity is disabled resources are requested for ANY_HOST * * @param processorId logical id of the container eg 1,2,3 * @param containerId last known id of the container deployed * @param preferredHost host on which container was last deployed * @param exitStatus exit code returned by the container * @param preferredHostRetryDelay delay to be incurred before requesting resources * @param containerAllocator allocator for requesting resources */ void handleContainerStop(String processorId, String containerId, String preferredHost, int exitStatus, Duration preferredHostRetryDelay, ContainerAllocator containerAllocator) { if (hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(processorId).get(); LOG.info("Setting the container state with Processor ID: {} to be stopped because of existing ContainerPlacement action: {}", processorId, metadata); metadata.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.STOPPED); } else if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleContainerStop(processorId, containerId, preferredHost, exitStatus, containerAllocator, preferredHostRetryDelay); } else { // If StandbyTasks are not enabled, we simply make a request for the preferredHost containerAllocator.requestResourceWithDelay(processorId, preferredHost, preferredHostRetryDelay); } } /** * Handle the container launch failure for active containers and standby (if enabled). * * Case 1. If this launch was issued due to an existing container placement action update the metadata to report failure and issue * a request for source host where the container was last seen and mark the container placement failed * Case 2. When standby is enabled, refer to {@link StandbyContainerManager#handleContainerLaunchFail} to check behavior * Case 3. When standby is disabled the allocator issues a request for ANY_HOST resources * * @param processorId logical id of the container eg 1,2,3 * @param containerId last known id of the container deployed * @param preferredHost host on which container is requested to be deployed * @param containerAllocator allocator for requesting resources */ void handleContainerLaunchFail(String processorId, String containerId, String preferredHost, ContainerAllocator containerAllocator) { if (processorId != null && hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metaData = getPlacementActionMetadata(processorId).get(); // Issue a request to start the container on source host String sourceHost = hostAffinityEnabled ? metaData.getSourceHost() : ResourceRequestState.ANY_HOST; markContainerPlacementActionFailed(metaData, String.format("failed to start container on destination host %s, attempting to start on source host %s", preferredHost, sourceHost)); containerAllocator.requestResource(processorId, sourceHost); } else if (processorId != null && standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerLaunchFail(processorId, containerId, containerAllocator); } else if (processorId != null) { LOG.info("Falling back to ANY_HOST for Processor ID: {} since launch failed for Container ID: {} on host: {}", processorId, containerId, preferredHost); containerAllocator.requestResource(processorId, ResourceRequestState.ANY_HOST); } else { LOG.warn("Did not find a pending Processor ID for Container ID: {} on host: {}. " + "Ignoring invalid/redundant notification.", containerId, preferredHost); } } /** * Handle the container stop failure for active containers and standby (if enabled). * @param processorId logical id of the container eg 1,2,3 * @param containerId last known id of the container deployed * @param containerHost host on which container is requested to be deployed * @param containerAllocator allocator for requesting resources * TODO: SAMZA-2512 Add integ test for handleContainerStopFail */ void handleContainerStopFail(String processorId, String containerId, String containerHost, ContainerAllocator containerAllocator) { if (processorId != null && hasActiveContainerPlacementAction(processorId)) { // Assuming resource acquired on destination host will be relinquished by the containerAllocator, // We mark the placement action as failed, and return. ContainerPlacementMetadata metaData = getPlacementActionMetadata(processorId).get(); metaData.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.STOP_FAILED); } else if (processorId != null && standbyContainerManager.isPresent()) { standbyContainerManager.get().handleContainerStopFail(processorId, containerId, containerAllocator); } else { LOG.warn("Did not find a running Processor ID for Container ID: {} on host: {}. " + "Ignoring invalid/redundant notification.", containerId, containerHost); } } /** * Handles the state update on successful launch of a container, if this launch is due to a container placement action updates the * related metadata to report success * * @param processorId logical processor id of container 0,1,2 */ void handleContainerLaunchSuccess(String processorId, String containerHost) { if (hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(processorId).get(); // Mark the active container running again and dispatch a response metadata.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.RUNNING); updateContainerPlacementActionStatus(metadata, ContainerPlacementMessage.StatusCode.SUCCEEDED, "Successfully completed the container placement action started container on host " + containerHost); } } /** * Handles an expired resource request for both active and standby containers. * * Case 1. If this expired request is due to a container placement action mark the request as failed and return * Case 2: Otherwise for a normal resource request following cases are possible * Case 2.1 If StandbyContainer is present refer to {@code StandbyContainerManager#handleExpiredResourceRequest} * Case 2.2: host-affinity is enabled, allocator thread looks for allocated resources on ANY_HOST and issues a * container start if available, otherwise issue an ANY_HOST request * Case 2.2: host-affinity is disabled, allocator thread does not handle expired requests, it waits for cluster * manager to return resources on ANY_HOST * * @param processorId logical id of the container * @param preferredHost host on which container is requested to be deployed * @param request pending request for the preferred host * @param allocator allocator for requesting resources * @param resourceRequestState state of request in {@link ContainerAllocator} */ @VisibleForTesting void handleExpiredRequest(String processorId, String preferredHost, SamzaResourceRequest request, ContainerAllocator allocator, ResourceRequestState resourceRequestState) { boolean resourceAvailableOnAnyHost = allocator.hasAllocatedResource(ResourceRequestState.ANY_HOST); // Case 1. Container placement actions can be taken in either cases of host affinity being set, in both cases // mark the container placement action failed if (hasActiveContainerPlacementAction(processorId)) { resourceRequestState.cancelResourceRequest(request); markContainerPlacementActionFailed(getPlacementActionMetadata(processorId).get(), "failed the ContainerPlacement action because request for resources to ClusterManager expired"); return; } // Case 2. When host affinity is disabled wait for cluster resource manager return resources // TODO: SAMZA-2330: Handle expired request for host affinity disabled case by retying request for getting ANY_HOST if (!hostAffinityEnabled) { return; } // Case 2. When host affinity is enabled handle the expired requests if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleExpiredResourceRequest(processorId, request, Optional.ofNullable(allocator.peekAllocatedResource(ResourceRequestState.ANY_HOST)), allocator, resourceRequestState); } else if (resourceAvailableOnAnyHost) { LOG.info("Request for Processor ID: {} on host: {} has expired. Running on ANY_HOST", processorId, preferredHost); allocator.runStreamProcessor(request, ResourceRequestState.ANY_HOST); } else { LOG.info("Request for Processor ID: {} on host: {} has expired. Requesting additional resources on ANY_HOST.", processorId, preferredHost); resourceRequestState.cancelResourceRequest(request); allocator.requestResource(processorId, ResourceRequestState.ANY_HOST); } } /** * Handles expired allocated resource by requesting the same resource again and release the expired allocated resource * * @param request pending request for the preferred host * @param resource resource allocated from {@link ClusterResourceManager} which has expired * @param preferredHost host on which container is requested to be deployed * @param resourceRequestState state of request in {@link ContainerAllocator} * @param allocator allocator for requesting resources */ void handleExpiredResource(SamzaResourceRequest request, SamzaResource resource, String preferredHost, ResourceRequestState resourceRequestState, ContainerAllocator allocator) { LOG.info("Allocated resource {} has expired for Processor ID: {} request: {}. Re-requesting resource again", resource, request.getProcessorId(), request); resourceRequestState.releaseUnstartableContainer(resource, preferredHost); resourceRequestState.cancelResourceRequest(request); SamzaResourceRequest newResourceRequest = allocator.getResourceRequest(request.getProcessorId(), request.getPreferredHost()); if (hasActiveContainerPlacementAction(newResourceRequest.getProcessorId())) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(request.getProcessorId()).get(); metadata.recordResourceRequest(newResourceRequest); } allocator.issueResourceRequest(newResourceRequest); } /** * Registers a container placement action to move the running container to destination host, if destination host is same as the * host on which container is running, container placement action is treated as a restart. * * When host affinity is disabled a move / restart is only allowed on ANY_HOST * When host affinity is enabled move / restart is allowed on specific or ANY_HOST * * Container placement requests are tied to deploymentId which is currently {@link org.apache.samza.config.ApplicationConfig#APP_RUN_ID} * On job restarts container placement requests queued for the previous deployment are deleted using this * * All kinds of container placement request except for when destination host is "FORCE_RESTART_LAST_SEEN" work with * a RESERVE - STOP - START policy, which means resources are accrued first before issuing a container stop, failure to * do so will leave the running container untouched. Requests with destination host "FORCE_RESTART_LAST_SEEN" works with * STOP - RESERVE - START policy, which means running container is stopped first then resource request are issued, this case * is equivalent to doing a kill -9 on a container * * @param requestMessage request containing logical processor id 0,1,2 and host where container is desired to be moved, * acceptable values of this param are * - valid hostname * - "ANY_HOST" in this case the request is sent to resource manager for any host * - "LAST_SEEN" in this case request is sent to resource manager for last seen host * - "FORCE_RESTART_LAST_SEEN" in this case request is sent to resource manager for last seen host * @param containerAllocator to request physical resources */ public void registerContainerPlacementAction(ContainerPlacementRequestMessage requestMessage, ContainerAllocator containerAllocator) { String processorId = requestMessage.getProcessorId(); String destinationHost = requestMessage.getDestinationHost(); // Is the action ready to be de-queued and taken or it needs to wait to be executed in future if (!deQueueAction(requestMessage)) { return; } LOG.info("ContainerPlacement action is de-queued metadata: {}", requestMessage); Pair<ContainerPlacementMessage.StatusCode, String> actionStatus = validatePlacementAction(requestMessage); // Action is de-queued upon so we record it in the cache placementRequestsCache.put(requestMessage.getUuid()); // Remove the request message from metastore since this message is already acted upon containerPlacementMetadataStore.deleteContainerPlacementRequestMessage(requestMessage.getUuid()); // Request is bad just update the response on message & return if (actionStatus.getKey() == ContainerPlacementMessage.StatusCode.BAD_REQUEST) { LOG.info("Status updated for ContainerPlacement action request: {} response: {}", requestMessage, actionStatus.getValue()); writeContainerPlacementResponseMessage(requestMessage, actionStatus.getKey(), actionStatus.getValue()); return; } /* * When destination host is {@code FORCE_RESTART_LAST_SEEN} its treated as eqvivalent to kill -9 operation for the container * In this scenario container is stopped first and we fallback to normal restart path so the policy here is * stop - reserve - move */ if (destinationHost.equals(FORCE_RESTART_LAST_SEEN)) { LOG.info("Issuing a force restart for Processor ID: {} for ContainerPlacement action request {}", processorId, requestMessage); clusterResourceManager.stopStreamProcessor(samzaApplicationState.runningProcessors.get(processorId)); writeContainerPlacementResponseMessage(requestMessage, ContainerPlacementMessage.StatusCode.SUCCEEDED, "Successfully issued a stop container request falling back to normal restart path"); return; } /** * When destination host is {@code LAST_SEEN} its treated as a restart request on the host where container is running * on or has been seen last, but in this policy would be reserve - stop - move, which means reserve resources first * only if resources are accrued stop the active container and issue a start on it on resource acquired */ if (destinationHost.equals(LAST_SEEN)) { String lastSeenHost = getSourceHostForContainer(requestMessage); LOG.info("Changing the requested host for placement action to {} because requested host is LAST_SEEN", lastSeenHost); destinationHost = lastSeenHost; } // TODO: SAMZA-2457: Allow host affinity disabled jobs to move containers to specific host if (!hostAffinityEnabled) { LOG.info("Changing the requested host for placement action to {} because host affinity is disabled", ResourceRequestState.ANY_HOST); destinationHost = ANY_HOST; } // Register metadata ContainerPlacementMetadata actionMetaData = new ContainerPlacementMetadata(requestMessage, getSourceHostForContainer(requestMessage)); actions.put(processorId, actionMetaData); // If the job is running in a degraded state then the container is already stopped if (samzaApplicationState.failedProcessors.containsKey(requestMessage.getProcessorId())) { actionMetaData.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.STOPPED); } SamzaResourceRequest resourceRequest = containerAllocator.getResourceRequest(processorId, destinationHost); // Record the resource request for monitoring actionMetaData.recordResourceRequest(resourceRequest); actions.put(processorId, actionMetaData); updateContainerPlacementActionStatus(actionMetaData, ContainerPlacementMessage.StatusCode.IN_PROGRESS, "Preferred Resources requested"); containerAllocator.issueResourceRequest(resourceRequest); } /** * This method is only used for Testing the Container Placement actions to get a hold of {@link ContainerPlacementMetadata} * for assertions. Not intended to be used in src */ @VisibleForTesting ContainerPlacementMetadata registerContainerPlacementActionForTest(ContainerPlacementRequestMessage requestMessage, ContainerAllocator containerAllocator) { registerContainerPlacementAction(requestMessage, containerAllocator); if (hasActiveContainerPlacementAction(requestMessage.getProcessorId())) { return getPlacementActionMetadata(requestMessage.getProcessorId()).get(); } return null; } public Optional<Duration> getActionExpiryTimeout(SamzaResourceRequest resourceRequest) { for (ContainerPlacementMetadata actionMetadata : actions.values()) { if (actionMetadata.containsResourceRequest(resourceRequest) && actionMetadata.getActionStatus() == ContainerPlacementMessage.StatusCode.IN_PROGRESS) { return actionMetadata.getRequestActionExpiryTimeout(); } } return Optional.empty(); } private void markContainerPlacementActionFailed(ContainerPlacementMetadata metaData, String failureMessage) { samzaApplicationState.failedContainerPlacementActions.incrementAndGet(); updateContainerPlacementActionStatus(metaData, ContainerPlacementMessage.StatusCode.FAILED, failureMessage); } /** * A ContainerPlacementAction is only active if it is either CREATED, ACCEPTED or IN_PROGRESS */ private boolean hasActiveContainerPlacementAction(String processorId) { Optional<ContainerPlacementMetadata> metadata = getPlacementActionMetadata(processorId); if (metadata.isPresent()) { switch (metadata.get().getActionStatus()) { case ACCEPTED: case IN_PROGRESS: return true; default: return false; } } return false; } /** * Check if a activeContainerResource has control-action-metadata associated with it */ private Optional<ContainerPlacementMetadata> getPlacementActionMetadata(String processorId) { return Optional.ofNullable(this.actions.get(processorId)); } private void updateContainerPlacementActionStatus(ContainerPlacementMetadata metadata, ContainerPlacementMessage.StatusCode statusCode, String responseMessage) { metadata.setActionStatus(statusCode, responseMessage); writeContainerPlacementResponseMessage(metadata.getRequestMessage(), statusCode, responseMessage); LOG.info("Status updated for ContainerPlacement action: {}", metadata); } private void writeContainerPlacementResponseMessage(ContainerPlacementRequestMessage requestMessage, ContainerPlacementMessage.StatusCode statusCode, String responseMessage) { containerPlacementMetadataStore.writeContainerPlacementResponseMessage( ContainerPlacementResponseMessage.fromContainerPlacementRequestMessage(requestMessage, statusCode, responseMessage, System.currentTimeMillis())); } /** * Gets the hostname on which container is either currently running or was last seen on if it is not running * TODO SAMZA-2480: Move logic related to onResourcesCompleted from ContainerProcessManager to ContainerManager */ private String getSourceHostForContainer(ContainerPlacementRequestMessage requestMessage) { String sourceHost = null; String processorId = requestMessage.getProcessorId(); if (samzaApplicationState.runningProcessors.containsKey(processorId)) { SamzaResource currentResource = samzaApplicationState.runningProcessors.get(processorId); LOG.info("Processor ID: {} matched a running container with containerId ID: {} is running on host: {} for ContainerPlacement action: {}", processorId, currentResource.getContainerId(), currentResource.getHost(), requestMessage); sourceHost = currentResource.getHost(); } else { sourceHost = Optional.ofNullable(localityManager.readLocality().getProcessorLocality(processorId)) .map(ProcessorLocality::host) .orElse(null); LOG.info("Processor ID: {} is not running and was last seen on host: {} for ContainerPlacement action: {}", processorId, sourceHost, requestMessage); } return sourceHost; } /** * These are specific scenarios in which a placement action should wait for existing action to complete before it is executed * 1. If there is an placement request in progress on active container * 2. If there is an placement request is progress on any of its standby container * 3. If the container itself is pending a start * * @param requestMessage container placement request message * @return true if action should be taken right now, false if it needs to wait to be taken in future */ private boolean deQueueAction(ContainerPlacementRequestMessage requestMessage) { // Do not dequeue action wait for the in-flight action to complete if (checkIfActiveOrStandbyContainerHasActivePlacementAction(requestMessage)) { return false; } if (samzaApplicationState.failedProcessors.containsKey(requestMessage.getProcessorId())) { LOG.info("ContainerPlacement request: {} is de-queued, container with Processor ID: {} has exhausted all retries and is in failed state", requestMessage, requestMessage.getProcessorId()); return true; } // Do not dequeue the action wait for the container to come to a running state if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) || samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId())) { LOG.info("ContainerPlacement request: {} is en-queued because container is pending start", requestMessage); return false; } return true; } /** * A valid container placement action needs a valid processor id. Duplicate actions are handled by de-duping on uuid. * If standby containers are enabled destination host requested must meet standby constraints * * @param requestMessage container placement request message * @return Pair<ContainerPlacementMessage.StatusCode, String> which is status code & response suggesting if the request is valid */ private Pair<ContainerPlacementMessage.StatusCode, String> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { String errorMessagePrefix = ContainerPlacementMessage.StatusCode.BAD_REQUEST + " reason: %s"; Boolean invalidAction = false; String errorMessage = null; boolean isRunning = samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()); boolean isPending = samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId()); boolean isFailed = samzaApplicationState.failedProcessors.containsKey(requestMessage.getProcessorId()); if (!isRunning && !isPending && !isFailed) { errorMessage = String.format(errorMessagePrefix, "invalid processor id neither in running, pending or failed processors"); invalidAction = true; } else if (placementRequestsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format(errorMessagePrefix, "duplicate UUID of the request, please retry"); invalidAction = true; } else if (standbyContainerManager.isPresent() && !standbyContainerManager.get() .checkStandbyConstraints(requestMessage.getProcessorId(), requestMessage.getDestinationHost())) { errorMessage = String.format(errorMessagePrefix, "destination host does not meet standby constraints"); invalidAction = true; } if (invalidAction) { return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage); } return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted"); } /** * Checks if there are any active container placement action on container itself or on any of its standby containers * (if enabled) */ private boolean checkIfActiveOrStandbyContainerHasActivePlacementAction(ContainerPlacementRequestMessage request) { String processorId = request.getProcessorId(); // Container itself has active container placement actions if (hasActiveContainerPlacementAction(processorId)) { LOG.info("ContainerPlacement request: {} is en-queued because container has an in-progress placement action", request); return true; } if (standbyContainerManager.isPresent()) { // If requested placement action is on a standby container and its active container has a placement request, // this request shall not be de-queued until in-flight action on active container is complete if (StandbyTaskUtil.isStandbyContainer(processorId) && hasActiveContainerPlacementAction( StandbyTaskUtil.getActiveContainerId(processorId))) { LOG.info("ContainerPlacement request: {} is en-queued because its active container has an in-progress placement action", request); return true; } // If requested placement action is on a standby container and its active container has a placement request, // this request shall not be de-queued until in-flight action on active container is complete if (!StandbyTaskUtil.isStandbyContainer(processorId)) { for (String standby : standbyContainerManager.get().getStandbyList(processorId)) { if (hasActiveContainerPlacementAction(standby)) { LOG.info("ContainerPlacement request: {} is en-queued because one of its standby replica has an in-progress placement action", request); return true; } } } } return false; } }
apache/fory
36,946
java/fory-core/src/main/java/org/apache/fory/meta/ClassDef.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.fory.meta; import static org.apache.fory.meta.ClassDefEncoder.buildFields; import static org.apache.fory.type.TypeUtils.COLLECTION_TYPE; import static org.apache.fory.type.TypeUtils.MAP_TYPE; import static org.apache.fory.type.TypeUtils.collectionOf; import static org.apache.fory.type.TypeUtils.mapOf; import java.io.ObjectStreamClass; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.SortedMap; import java.util.stream.Collectors; import org.apache.fory.Fory; import org.apache.fory.builder.MetaSharedCodecBuilder; import org.apache.fory.collection.Tuple2; import org.apache.fory.config.CompatibleMode; import org.apache.fory.config.ForyBuilder; import org.apache.fory.logging.Logger; import org.apache.fory.logging.LoggerFactory; import org.apache.fory.memory.MemoryBuffer; import org.apache.fory.memory.Platform; import org.apache.fory.reflect.ReflectionUtils; import org.apache.fory.reflect.TypeRef; import org.apache.fory.resolver.ClassInfo; import org.apache.fory.resolver.ClassResolver; import org.apache.fory.resolver.TypeResolver; import org.apache.fory.resolver.XtypeResolver; import org.apache.fory.serializer.CompatibleSerializer; import org.apache.fory.serializer.NonexistentClass; import org.apache.fory.serializer.converter.FieldConverter; import org.apache.fory.serializer.converter.FieldConverters; import org.apache.fory.type.Descriptor; import org.apache.fory.type.FinalObjectTypeStub; import org.apache.fory.type.GenericType; import org.apache.fory.type.TypeUtils; import org.apache.fory.type.Types; import org.apache.fory.util.Preconditions; /** * Serializable class definition to be sent to other process. So if sender peer and receiver peer * has different class definition for same class, such as add/remove fields, we can use this * definition to create different serializer to support back/forward compatibility. * * <p>Note that: * <li>If a class is already registered, this definition will contain class id only. * <li>Sending class definition is not cheap, should be sent with some kind of meta share mechanism. * <li>{@link ObjectStreamClass} doesn't contain any non-primitive field type info, which is not * enough to create serializer in receiver. * * @see MetaSharedCodecBuilder * @see CompatibleMode#COMPATIBLE * @see CompatibleSerializer * @see ForyBuilder#withMetaShare * @see ReflectionUtils#getFieldOffset */ public class ClassDef implements Serializable { static final int COMPRESS_META_FLAG = 0b1 << 13; static final int HAS_FIELDS_META_FLAG = 0b1 << 12; // low 12 bits static final int META_SIZE_MASKS = 0xfff; static final int NUM_HASH_BITS = 50; private static final Logger LOG = LoggerFactory.getLogger(ClassDef.class); // TODO use field offset to sort field, which will hit l1-cache more. Since // `objectFieldOffset` is not part of jvm-specification, it may change between different jdk // vendor. But the deserialization peer use the class definition to create deserializer, it's OK // even field offset or fields order change between jvm process. public static final Comparator<Field> FIELD_COMPARATOR = (f1, f2) -> { long offset1 = Platform.objectFieldOffset(f1); long offset2 = Platform.objectFieldOffset(f2); long diff = offset1 - offset2; if (diff != 0) { return (int) diff; } else { if (!f1.equals(f2)) { LOG.warn( "Field {} has same offset with {}, please an issue with jdk info to fory", f1, f2); } int compare = f1.getDeclaringClass().getName().compareTo(f2.getName()); if (compare != 0) { return compare; } return f1.getName().compareTo(f2.getName()); } }; private final ClassSpec classSpec; private final List<FieldInfo> fieldsInfo; private final boolean hasFieldsMeta; // Unique id for class def. If class def are same between processes, then the id will // be same too. private final long id; private final byte[] encoded; private transient List<Descriptor> descriptors; ClassDef( ClassSpec classSpec, List<FieldInfo> fieldsInfo, boolean hasFieldsMeta, long id, byte[] encoded) { this.classSpec = classSpec; this.fieldsInfo = fieldsInfo; this.hasFieldsMeta = hasFieldsMeta; this.id = id; this.encoded = encoded; } public static void skipClassDef(MemoryBuffer buffer, long id) { int size = (int) (id & META_SIZE_MASKS); if (size == META_SIZE_MASKS) { size += buffer.readVarUint32Small14(); } buffer.increaseReaderIndex(size); } /** * Returns class name. * * @see Class#getName() */ public String getClassName() { return classSpec.entireClassName; } public ClassSpec getClassSpec() { return classSpec; } /** Contain all fields info including all parent classes. */ public List<FieldInfo> getFieldsInfo() { return fieldsInfo; } /** Returns ext meta for the class. */ public boolean hasFieldsMeta() { return hasFieldsMeta; } /** * Returns an unique id for class def. If class def are same between processes, then the id will * be same too. */ public long getId() { return id; } public byte[] getEncoded() { return encoded; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } ClassDef classDef = (ClassDef) o; return hasFieldsMeta == classDef.hasFieldsMeta && id == classDef.id && Objects.equals(classSpec, classDef.classSpec) && Objects.equals(fieldsInfo, classDef.fieldsInfo); } @Override public int hashCode() { return Objects.hash(classSpec.entireClassName, fieldsInfo, id); } @Override public String toString() { return "ClassDef{" + "className='" + classSpec.entireClassName + '\'' + ", fieldsInfo=" + fieldsInfo + ", hasFieldsMeta=" + hasFieldsMeta + ", id=" + id + '}'; } /** Write class definition to buffer. */ public void writeClassDef(MemoryBuffer buffer) { buffer.writeBytes(encoded, 0, encoded.length); } /** Read class definition from buffer. */ public static ClassDef readClassDef(Fory fory, MemoryBuffer buffer) { if (fory.isCrossLanguage()) { return TypeDefDecoder.decodeClassDef(fory.getXtypeResolver(), buffer, buffer.readInt64()); } return ClassDefDecoder.decodeClassDef(fory.getClassResolver(), buffer, buffer.readInt64()); } /** Read class definition from buffer. */ public static ClassDef readClassDef(Fory fory, MemoryBuffer buffer, long header) { if (fory.isCrossLanguage()) { return TypeDefDecoder.decodeClassDef(fory.getXtypeResolver(), buffer, header); } return ClassDefDecoder.decodeClassDef(fory.getClassResolver(), buffer, header); } /** * Consolidate fields of <code>classDef</code> with <code>cls</code>. If some field exists in * <code>cls</code> but not in <code>classDef</code>, it won't be returned in final collection. If * some field exists in <code>classDef</code> but not in <code> cls</code>, it will be added to * final collection. * * @param cls class load in current process. */ public List<Descriptor> getDescriptors(TypeResolver resolver, Class<?> cls) { if (descriptors == null) { SortedMap<Member, Descriptor> allDescriptorsMap = resolver.getFory().getClassResolver().getAllDescriptorsMap(cls, true); Map<String, Descriptor> descriptorsMap = new HashMap<>(); for (Map.Entry<Member, Descriptor> e : allDescriptorsMap.entrySet()) { if (descriptorsMap.put( e.getKey().getDeclaringClass().getName() + "." + e.getKey().getName(), e.getValue()) != null) { throw new IllegalStateException("Duplicate key"); } } descriptors = new ArrayList<>(fieldsInfo.size()); for (FieldInfo fieldInfo : fieldsInfo) { Descriptor descriptor = descriptorsMap.get(fieldInfo.getDefinedClass() + "." + fieldInfo.getFieldName()); Descriptor newDesc = fieldInfo.toDescriptor(resolver, descriptor); Class<?> rawType = newDesc.getRawType(); FieldType fieldType = fieldInfo.getFieldType(); if (fieldType instanceof RegisteredFieldType) { String typeAlias = String.valueOf(((RegisteredFieldType) fieldType).getClassId()); if (!typeAlias.equals(newDesc.getTypeName())) { newDesc = newDesc.copyWithTypeName(typeAlias); } } if (descriptor != null) { // Make DescriptorGrouper have consistent order whether field exist or not // fory builtin types skip if (useFieldType(rawType, descriptor)) { descriptor = descriptor.copyWithTypeName(newDesc.getTypeName()); descriptors.add(descriptor); } else { FieldConverter<?> converter = FieldConverters.getConverter(rawType, descriptor.getField()); if (converter != null) { newDesc.setFieldConverter(converter); } descriptors.add(newDesc); } } else { descriptors.add(newDesc); } } } return descriptors; } /** Returns true if can use current field type. */ private static boolean useFieldType(Class<?> parsedType, Descriptor descriptor) { if (parsedType.isEnum() || parsedType.isAssignableFrom(descriptor.getRawType()) || parsedType == FinalObjectTypeStub.class) { return true; } if (parsedType.isArray()) { Tuple2<Class<?>, Integer> info = TypeUtils.getArrayComponentInfo(parsedType); Field field = descriptor.getField(); if (!field.getType().isArray() || TypeUtils.getArrayDimensions(field.getType()) != info.f1) { return false; } return info.f0 == FinalObjectTypeStub.class || info.f0.isEnum(); } return false; } /** * FieldInfo contains all necessary info of a field to execute serialization/deserialization * logic. */ public static class FieldInfo implements Serializable { /** where are current field defined. */ private final String definedClass; /** Name of a field. */ private final String fieldName; private final FieldType fieldType; FieldInfo(String definedClass, String fieldName, FieldType fieldType) { this.definedClass = definedClass; this.fieldName = fieldName; this.fieldType = fieldType; } /** Returns classname of current field defined. */ public String getDefinedClass() { return definedClass; } /** Returns name of current field. */ public String getFieldName() { return fieldName; } /** Returns whether field is annotated by an unsigned int id. */ public boolean hasTag() { return false; } /** Returns annotated tag id for the field. */ public short getTag() { return -1; } /** Returns type of current field. */ public FieldType getFieldType() { return fieldType; } /** * Convert this field into a {@link Descriptor}, the corresponding {@link Field} field will be * null. Don't invoke this method if class does have <code>fieldName</code> field. In such case, * reflection should be used to get the descriptor. */ Descriptor toDescriptor(TypeResolver resolver, Descriptor descriptor) { TypeRef<?> declared = descriptor != null ? descriptor.getTypeRef() : null; TypeRef<?> typeRef = fieldType.toTypeToken(resolver, declared); if (descriptor != null) { if (typeRef.equals(declared)) { return descriptor; } else { descriptor.copyWithTypeName(typeRef.getType().getTypeName()); } } // This field doesn't exist in peer class, so any legal modifier will be OK. int stubModifiers = ReflectionUtils.getField(getClass(), "fieldName").getModifiers(); return new Descriptor(typeRef, fieldName, stubModifiers, definedClass); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FieldInfo fieldInfo = (FieldInfo) o; return Objects.equals(definedClass, fieldInfo.definedClass) && Objects.equals(fieldName, fieldInfo.fieldName) && Objects.equals(fieldType, fieldInfo.fieldType); } @Override public int hashCode() { return Objects.hash(definedClass, fieldName, fieldType); } @Override public String toString() { return "FieldInfo{" + "definedClass='" + definedClass + '\'' + ", fieldName='" + fieldName + '\'' + ", fieldType=" + fieldType + '}'; } } public abstract static class FieldType implements Serializable { protected final int xtypeId; protected final boolean isMonomorphic; protected final boolean nullable; protected final boolean trackingRef; public FieldType(int xtypeId, boolean isMonomorphic, boolean nullable, boolean trackingRef) { this.isMonomorphic = isMonomorphic; this.trackingRef = trackingRef; this.nullable = nullable; this.xtypeId = xtypeId & 0xff; } public boolean isMonomorphic() { return isMonomorphic; } public boolean trackingRef() { return trackingRef; } public boolean nullable() { return nullable; } /** * Convert a serializable field type to type token. If field type is a generic type with * generics, the generics will be built up recursively. The final leaf object type will be built * from class id or class stub. * * @see FinalObjectTypeStub */ public abstract TypeRef<?> toTypeToken(TypeResolver classResolver, TypeRef<?> declared); @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } FieldType fieldType = (FieldType) o; return isMonomorphic == fieldType.isMonomorphic && trackingRef == fieldType.trackingRef; } @Override public int hashCode() { return Objects.hash(isMonomorphic, trackingRef); } /** Write field type info. */ public void write(MemoryBuffer buffer, boolean writeHeader) { byte header = (byte) ((isMonomorphic ? 1 : 0) << 1); // header of nested generic fields in collection/map will be written independently header |= (byte) (trackingRef ? 1 : 0); if (this instanceof RegisteredFieldType) { short classId = ((RegisteredFieldType) this).getClassId(); buffer.writeVarUint32Small7(writeHeader ? ((5 + classId) << 2) | header : 5 + classId); } else if (this instanceof EnumFieldType) { buffer.writeVarUint32Small7(writeHeader ? ((4) << 2) | header : 4); } else if (this instanceof ArrayFieldType) { ArrayFieldType arrayFieldType = (ArrayFieldType) this; buffer.writeVarUint32Small7(writeHeader ? ((3) << 2) | header : 3); buffer.writeVarUint32Small7(arrayFieldType.getDimensions()); (arrayFieldType).getComponentType().write(buffer); } else if (this instanceof CollectionFieldType) { buffer.writeVarUint32Small7(writeHeader ? ((2) << 2) | header : 2); // TODO remove it when new collection deserialization jit finished. ((CollectionFieldType) this).getElementType().write(buffer); } else if (this instanceof MapFieldType) { buffer.writeVarUint32Small7(writeHeader ? ((1) << 2) | header : 1); // TODO remove it when new map deserialization jit finished. MapFieldType mapFieldType = (MapFieldType) this; mapFieldType.getKeyType().write(buffer); mapFieldType.getValueType().write(buffer); } else { Preconditions.checkArgument(this instanceof ObjectFieldType); buffer.writeVarUint32Small7(writeHeader ? header : 0); } } public void write(MemoryBuffer buffer) { write(buffer, true); } public static FieldType read(MemoryBuffer buffer, TypeResolver resolver) { int header = buffer.readVarUint32Small7(); boolean isMonomorphic = (header & 0b10) != 0; boolean trackingRef = (header & 0b1) != 0; return read(buffer, resolver, isMonomorphic, trackingRef, header >>> 2); } /** Read field type info. */ public static FieldType read( MemoryBuffer buffer, TypeResolver resolver, boolean isFinal, boolean trackingRef, int typeId) { if (typeId == 0) { return new ObjectFieldType(-1, isFinal, true, trackingRef); } else if (typeId == 1) { return new MapFieldType( -1, isFinal, true, trackingRef, read(buffer, resolver), read(buffer, resolver)); } else if (typeId == 2) { return new CollectionFieldType(-1, isFinal, true, trackingRef, read(buffer, resolver)); } else if (typeId == 3) { int dims = buffer.readVarUint32Small7(); return new ArrayFieldType(isFinal, trackingRef, read(buffer, resolver), dims); } else if (typeId == 4) { return new EnumFieldType(true, -1); } else { boolean nullable = ((ClassResolver) resolver).isPrimitive((short) typeId); return new RegisteredFieldType(isFinal, nullable, trackingRef, (typeId - 5)); } } public final void xwrite(MemoryBuffer buffer, boolean writeFlags) { int xtypeId = this.xtypeId; if (writeFlags) { xtypeId = (xtypeId << 2); if (nullable) { xtypeId |= 0b10; } if (trackingRef) { xtypeId |= 0b1; } } buffer.writeVarUint32Small7(xtypeId); switch (xtypeId) { case Types.LIST: ((CollectionFieldType) this).getElementType().xwrite(buffer, true); break; case Types.MAP: MapFieldType mapFieldType = (MapFieldType) this; mapFieldType.getKeyType().xwrite(buffer, true); mapFieldType.getValueType().xwrite(buffer, true); break; default: { } } } public static FieldType xread(MemoryBuffer buffer, XtypeResolver resolver) { int xtypeId = buffer.readVarUint32Small7(); boolean trackingRef = (xtypeId & 0b1) != 0; boolean nullable = (xtypeId & 0b10) != 0; xtypeId = xtypeId >>> 2; return xread(buffer, resolver, xtypeId, nullable, trackingRef); } public static FieldType xread( MemoryBuffer buffer, XtypeResolver resolver, int xtypeId, boolean nullable, boolean trackingRef) { assert xtypeId <= 0xff; switch (xtypeId) { case Types.LIST: case Types.SET: return new CollectionFieldType( xtypeId, true, nullable, trackingRef, xread(buffer, resolver)); case Types.MAP: return new MapFieldType( xtypeId, true, nullable, trackingRef, xread(buffer, resolver), xread(buffer, resolver)); case Types.ENUM: case Types.NAMED_ENUM: return new EnumFieldType(nullable, xtypeId); case Types.UNKNOWN: return new ObjectFieldType(xtypeId, false, nullable, trackingRef); default: { if (!Types.isUserDefinedType((byte) xtypeId)) { ClassInfo classInfo = resolver.getXtypeInfo(xtypeId); Preconditions.checkNotNull(classInfo); Class<?> cls = classInfo.getCls(); return new RegisteredFieldType( resolver.isMonomorphic(cls), nullable, trackingRef, xtypeId); } else { return new ObjectFieldType(xtypeId, false, nullable, trackingRef); } } } } } /** Class for field type which is registered. */ public static class RegisteredFieldType extends FieldType { private final short classId; public RegisteredFieldType( boolean isFinal, boolean nullable, boolean trackingRef, int classId) { super(classId, isFinal, nullable, trackingRef); this.classId = (short) classId; } public short getClassId() { return classId; } @Override public TypeRef<?> toTypeToken(TypeResolver resolver, TypeRef<?> declared) { Class<?> cls; if (resolver instanceof XtypeResolver) { cls = ((XtypeResolver) resolver).getXtypeInfo(classId).getCls(); if (Types.isPrimitiveType(classId)) { // For primitive types, ensure we use the correct primitive/boxed form // based on the nullable flag, not the declared type if (!nullable) { // nullable=false means the source was primitive, use primitive type cls = TypeUtils.unwrap(cls); } else { // nullable=true means the source was boxed, use boxed type cls = TypeUtils.wrap(cls); } } } else { cls = ((ClassResolver) resolver).getRegisteredClass(classId); } if (cls == null) { LOG.warn("Class {} not registered, take it as Struct type for deserialization.", classId); cls = NonexistentClass.NonexistentMetaShared.class; } return TypeRef.of(cls, new TypeExtMeta(nullable, trackingRef)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } RegisteredFieldType that = (RegisteredFieldType) o; return classId == that.classId; } @Override public int hashCode() { return Objects.hash(super.hashCode(), classId); } @Override public String toString() { return "RegisteredFieldType{" + "isMonomorphic=" + isMonomorphic() + ", trackingRef=" + trackingRef() + ", classId=" + classId + '}'; } } /** * Class for collection field type, which store collection element type information. Nested * collection/map generics example: * * <pre>{@code * new TypeToken<Collection<Map<String, String>>>() {} * }</pre> */ public static class CollectionFieldType extends FieldType { private final FieldType elementType; public CollectionFieldType( int xtypeId, boolean isFinal, boolean nullable, boolean trackingRef, FieldType elementType) { super(xtypeId, isFinal, nullable, trackingRef); this.elementType = elementType; } public FieldType getElementType() { return elementType; } @Override public TypeRef<?> toTypeToken(TypeResolver classResolver, TypeRef<?> declared) { // TODO support preserve element TypeExtMeta TypeRef<? extends Collection<?>> collectionTypeRef = collectionOf( elementType.toTypeToken(classResolver, declared), new TypeExtMeta(nullable, trackingRef)); if (declared == null) { return collectionTypeRef; } Class<?> declaredClass = declared.getRawType(); if (!declaredClass.isArray()) { return collectionTypeRef; } Tuple2<Class<?>, Integer> info = TypeUtils.getArrayComponentInfo(declaredClass); List<TypeRef<?>> typeRefs = new ArrayList<>(info.f1 + 1); typeRefs.add(collectionTypeRef); for (int i = 0; i < info.f1; i++) { typeRefs.add(TypeUtils.getElementType(typeRefs.get(i))); } Collections.reverse(typeRefs); for (int i = 1; i < typeRefs.size(); i++) { TypeRef<?> arrayType = typeRefs.get(i - 1); TypeRef<?> typeRef = TypeRef.of( Array.newInstance(arrayType.getRawType(), 1).getClass(), typeRefs.get(i).getExtInfo()); typeRefs.set(i, typeRef); } return typeRefs.get(typeRefs.size() - 1); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } CollectionFieldType that = (CollectionFieldType) o; return Objects.equals(elementType, that.elementType); } @Override public int hashCode() { return Objects.hash(super.hashCode(), elementType); } @Override public String toString() { return "CollectionFieldType{" + "elementType=" + elementType + ", isFinal=" + isMonomorphic() + ", trackingRef=" + trackingRef() + '}'; } } /** * Class for map field type, which store map key/value type information. Nested map generics * example: * * <pre>{@code * new TypeToken<Map<List<String>>, String>() {} * }</pre> */ public static class MapFieldType extends FieldType { private final FieldType keyType; private final FieldType valueType; public MapFieldType( int xtypeId, boolean isFinal, boolean nullable, boolean trackingRef, FieldType keyType, FieldType valueType) { super(xtypeId, isFinal, nullable, trackingRef); this.keyType = keyType; this.valueType = valueType; } public FieldType getKeyType() { return keyType; } public FieldType getValueType() { return valueType; } @Override public TypeRef<?> toTypeToken(TypeResolver classResolver, TypeRef<?> declared) { // TODO support preserve element TypeExtMeta, it will be lost when building other TypeRef return mapOf( keyType.toTypeToken(classResolver, declared), valueType.toTypeToken(classResolver, declared), new TypeExtMeta(nullable, trackingRef)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } MapFieldType that = (MapFieldType) o; return Objects.equals(keyType, that.keyType) && Objects.equals(valueType, that.valueType); } @Override public int hashCode() { return Objects.hash(super.hashCode(), keyType, valueType); } @Override public String toString() { return "MapFieldType{" + "keyType=" + keyType + ", valueType=" + valueType + ", isFinal=" + isMonomorphic() + ", trackingRef=" + trackingRef() + '}'; } } public static class EnumFieldType extends FieldType { private EnumFieldType(boolean nullable, int xtypeId) { super(xtypeId, true, nullable, false); } @Override public TypeRef<?> toTypeToken(TypeResolver classResolver, TypeRef<?> declared) { return TypeRef.of(NonexistentClass.NonexistentEnum.class); } } public static class ArrayFieldType extends FieldType { private final FieldType componentType; private final int dimensions; public ArrayFieldType( boolean isMonomorphic, boolean trackingRef, FieldType componentType, int dimensions) { this(-1, isMonomorphic, true, trackingRef, componentType, dimensions); } public ArrayFieldType( int xtypeId, boolean isMonomorphic, boolean nullable, boolean trackingRef, FieldType componentType, int dimensions) { super(xtypeId, isMonomorphic, nullable, trackingRef); this.componentType = componentType; this.dimensions = dimensions; } @Override public TypeRef<?> toTypeToken(TypeResolver classResolver, TypeRef<?> declared) { while (declared != null && declared.isArray()) { declared = declared.getComponentType(); } TypeRef<?> componentTypeRef = componentType.toTypeToken(classResolver, declared); Class<?> componentRawType = componentTypeRef.getRawType(); if (NonexistentClass.class.isAssignableFrom(componentRawType)) { return TypeRef.of( // We embed `isMonomorphic` flag in ObjectArraySerializer, so this flag can be ignored // here. NonexistentClass.getNonexistentClass( componentType instanceof EnumFieldType, dimensions, true), new TypeExtMeta(nullable, trackingRef)); } else { return TypeRef.of( Array.newInstance(componentRawType, new int[dimensions]).getClass(), new TypeExtMeta(nullable, trackingRef)); } } public int getDimensions() { return dimensions; } public FieldType getComponentType() { return componentType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ArrayFieldType that = (ArrayFieldType) o; return dimensions == that.dimensions && Objects.equals(componentType, that.componentType); } @Override public int hashCode() { return Objects.hash(super.hashCode(), componentType, dimensions); } @Override public String toString() { return "ArrayFieldType{" + "componentType=" + componentType + ", dimensions=" + dimensions + ", isMonomorphic=" + isMonomorphic + ", trackingRef=" + trackingRef + '}'; } } /** Class for field type which isn't registered and not collection/map type too. */ public static class ObjectFieldType extends FieldType { public ObjectFieldType(int xtypeId, boolean isFinal, boolean nullable, boolean trackingRef) { super(xtypeId, isFinal, nullable, trackingRef); } @Override public TypeRef<?> toTypeToken(TypeResolver classResolver, TypeRef<?> declared) { return isMonomorphic() ? TypeRef.of(FinalObjectTypeStub.class, new TypeExtMeta(nullable, trackingRef)) : TypeRef.of(Object.class, new TypeExtMeta(nullable, trackingRef)); } @Override public boolean equals(Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } } /** Build field type from generics, nested generics will be extracted too. */ static FieldType buildFieldType(TypeResolver resolver, Field field) { Preconditions.checkNotNull(field); GenericType genericType = resolver.buildGenericType(field.getGenericType()); return buildFieldType(resolver, genericType); } /** Build field type from generics, nested generics will be extracted too. */ private static FieldType buildFieldType(TypeResolver resolver, GenericType genericType) { Preconditions.checkNotNull(genericType); Class<?> rawType = genericType.getCls(); boolean isXlang = resolver.getFory().isCrossLanguage(); int xtypeId = -1; if (isXlang) { ClassInfo info = resolver.getClassInfo(genericType.getCls(), false); if (info != null) { xtypeId = info.getXtypeId(); } else { xtypeId = Types.UNKNOWN; } } boolean isMonomorphic = genericType.isMonomorphic(); boolean trackingRef = genericType.trackingRef(resolver); // TODO support @Nullable/ForyField annotation boolean nullable = !genericType.getCls().isPrimitive(); if (COLLECTION_TYPE.isSupertypeOf(genericType.getTypeRef())) { return new CollectionFieldType( xtypeId, isMonomorphic, nullable, trackingRef, buildFieldType( resolver, genericType.getTypeParameter0() == null ? GenericType.build(Object.class) : genericType.getTypeParameter0())); } else if (MAP_TYPE.isSupertypeOf(genericType.getTypeRef())) { return new MapFieldType( xtypeId, isMonomorphic, nullable, trackingRef, buildFieldType( resolver, genericType.getTypeParameter0() == null ? GenericType.build(Object.class) : genericType.getTypeParameter0()), buildFieldType( resolver, genericType.getTypeParameter1() == null ? GenericType.build(Object.class) : genericType.getTypeParameter1())); } else { if (isXlang && !Types.isUserDefinedType((byte) xtypeId) && resolver.isRegisteredById(rawType)) { return new RegisteredFieldType(isMonomorphic, nullable, trackingRef, xtypeId); } else if (!isXlang && resolver.isRegisteredById(rawType)) { Short classId = ((ClassResolver) resolver).getRegisteredClassId(rawType); return new RegisteredFieldType(isMonomorphic, nullable, trackingRef, classId); } else { if (rawType.isEnum()) { return new EnumFieldType(nullable, xtypeId); } if (rawType.isArray()) { Class<?> elemType = rawType.getComponentType(); while (elemType.isArray()) { elemType = elemType.getComponentType(); } if (isXlang && !elemType.isPrimitive()) { return new CollectionFieldType( xtypeId, isMonomorphic, nullable, trackingRef, buildFieldType(resolver, GenericType.build(elemType))); } Tuple2<Class<?>, Integer> info = TypeUtils.getArrayComponentInfo(rawType); return new ArrayFieldType( xtypeId, isMonomorphic, nullable, trackingRef, buildFieldType(resolver, GenericType.build(info.f0)), info.f1); } return new ObjectFieldType(xtypeId, isMonomorphic, nullable, trackingRef); } } } public static ClassDef buildClassDef(Fory fory, Class<?> cls) { return buildClassDef(fory, cls, true); } public static ClassDef buildClassDef(Fory fory, Class<?> cls, boolean resolveParent) { if (fory.isCrossLanguage()) { return TypeDefEncoder.buildTypeDef(fory, cls); } return ClassDefEncoder.buildClassDef( fory.getClassResolver(), cls, buildFields(fory, cls, resolveParent), true); } /** Build class definition from fields of class. */ static ClassDef buildClassDef(ClassResolver classResolver, Class<?> type, List<Field> fields) { return buildClassDef(classResolver, type, fields, true); } public static ClassDef buildClassDef( ClassResolver classResolver, Class<?> type, List<Field> fields, boolean hasFieldsMeta) { return ClassDefEncoder.buildClassDef(classResolver, type, fields, hasFieldsMeta); } public ClassDef replaceRootClassTo(ClassResolver classResolver, Class<?> targetCls) { String name = targetCls.getName(); List<FieldInfo> fieldInfos = fieldsInfo.stream() .map( fieldInfo -> { if (fieldInfo.definedClass.equals(classSpec.entireClassName)) { return new FieldInfo(name, fieldInfo.fieldName, fieldInfo.fieldType); } else { return fieldInfo; } }) .collect(Collectors.toList()); return ClassDefEncoder.buildClassDefWithFieldInfos( classResolver, targetCls, fieldInfos, hasFieldsMeta); } }
apache/kafka
37,213
connect/mirror/src/main/java/org/apache/kafka/connect/mirror/MirrorSourceConnector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.mirror; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.admin.AlterConfigOp; import org.apache.kafka.clients.admin.Config; import org.apache.kafka.clients.admin.ConfigEntry; import org.apache.kafka.clients.admin.CreateTopicsOptions; import org.apache.kafka.clients.admin.NewPartitions; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.admin.TopicDescription; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.IsolationLevel; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.acl.AccessControlEntry; import org.apache.kafka.common.acl.AccessControlEntryFilter; import org.apache.kafka.common.acl.AclBinding; import org.apache.kafka.common.acl.AclBindingFilter; import org.apache.kafka.common.acl.AclOperation; import org.apache.kafka.common.acl.AclPermissionType; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigResource; import org.apache.kafka.common.config.ConfigValue; import org.apache.kafka.common.errors.InvalidPartitionsException; import org.apache.kafka.common.errors.SecurityDisabledException; import org.apache.kafka.common.errors.UnsupportedVersionException; import org.apache.kafka.common.resource.PatternType; import org.apache.kafka.common.resource.ResourcePattern; import org.apache.kafka.common.resource.ResourcePatternFilter; import org.apache.kafka.common.resource.ResourceType; import org.apache.kafka.common.utils.AppInfoParser; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.connector.Task; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.source.ExactlyOnceSupport; import org.apache.kafka.connect.source.SourceConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static org.apache.kafka.connect.mirror.MirrorConnectorConfig.OFFSET_SYNCS_CLIENT_ROLE_PREFIX; import static org.apache.kafka.connect.mirror.MirrorConnectorConfig.OFFSET_SYNCS_TOPIC_CONFIG_PREFIX; import static org.apache.kafka.connect.mirror.MirrorSourceConfig.SYNC_TOPIC_ACLS_ENABLED; import static org.apache.kafka.connect.mirror.MirrorUtils.SOURCE_CLUSTER_KEY; import static org.apache.kafka.connect.mirror.MirrorUtils.TOPIC_KEY; import static org.apache.kafka.connect.mirror.MirrorUtils.adminCall; /** Replicate data, configuration, and ACLs between clusters. * * @see MirrorSourceConfig for supported config properties. */ public class MirrorSourceConnector extends SourceConnector { private static final Logger log = LoggerFactory.getLogger(MirrorSourceConnector.class); private static final ResourcePatternFilter ANY_TOPIC = new ResourcePatternFilter(ResourceType.TOPIC, null, PatternType.ANY); private static final AclBindingFilter ANY_TOPIC_ACL = new AclBindingFilter(ANY_TOPIC, AccessControlEntryFilter.ANY); private static final String READ_COMMITTED = IsolationLevel.READ_COMMITTED.toString(); private static final String EXACTLY_ONCE_SUPPORT_CONFIG = "exactly.once.support"; private final AtomicBoolean noAclAuthorizer = new AtomicBoolean(false); private Scheduler scheduler; private MirrorSourceConfig config; private SourceAndTarget sourceAndTarget; private String connectorName; private TopicFilter topicFilter; private ConfigPropertyFilter configPropertyFilter; private List<TopicPartition> knownSourceTopicPartitions = List.of(); private List<TopicPartition> knownTargetTopicPartitions = List.of(); private ReplicationPolicy replicationPolicy; private int replicationFactor; private Admin sourceAdminClient; private Admin targetAdminClient; private boolean heartbeatsReplicationEnabled; public MirrorSourceConnector() { // nop } // visible for testing MirrorSourceConnector(List<TopicPartition> knownSourceTopicPartitions, MirrorSourceConfig config) { this.knownSourceTopicPartitions = knownSourceTopicPartitions; this.config = config; } // visible for testing MirrorSourceConnector(SourceAndTarget sourceAndTarget, ReplicationPolicy replicationPolicy, TopicFilter topicFilter, ConfigPropertyFilter configPropertyFilter) { this(sourceAndTarget, replicationPolicy, topicFilter, configPropertyFilter, true); } // visible for testing MirrorSourceConnector(SourceAndTarget sourceAndTarget, ReplicationPolicy replicationPolicy, TopicFilter topicFilter, ConfigPropertyFilter configPropertyFilter, boolean heartbeatsReplicationEnabled) { this.sourceAndTarget = sourceAndTarget; this.replicationPolicy = replicationPolicy; this.topicFilter = topicFilter; this.configPropertyFilter = configPropertyFilter; this.heartbeatsReplicationEnabled = heartbeatsReplicationEnabled; } // visible for testing MirrorSourceConnector(Admin sourceAdminClient, Admin targetAdminClient, MirrorSourceConfig config) { this.sourceAdminClient = sourceAdminClient; this.targetAdminClient = targetAdminClient; this.config = config; } @Override public void start(Map<String, String> props) { long start = System.currentTimeMillis(); config = new MirrorSourceConfig(props); if (!config.enabled()) { return; } connectorName = config.connectorName(); sourceAndTarget = new SourceAndTarget(config.sourceClusterAlias(), config.targetClusterAlias()); topicFilter = config.topicFilter(); configPropertyFilter = config.configPropertyFilter(); replicationPolicy = config.replicationPolicy(); replicationFactor = config.replicationFactor(); sourceAdminClient = config.forwardingAdmin(config.sourceAdminConfig("replication-source-admin")); targetAdminClient = config.forwardingAdmin(config.targetAdminConfig("replication-target-admin")); heartbeatsReplicationEnabled = config.heartbeatsReplicationEnabled(); scheduler = new Scheduler(getClass(), config.entityLabel(), config.adminTimeout()); scheduler.execute(this::createOffsetSyncsTopic, "creating upstream offset-syncs topic"); scheduler.execute(this::loadTopicPartitions, "loading initial set of topic-partitions"); scheduler.execute(this::computeAndCreateTopicPartitions, "creating downstream topic-partitions"); scheduler.execute(this::refreshKnownTargetTopics, "refreshing known target topics"); scheduler.scheduleRepeating(this::syncTopicAcls, config.syncTopicAclsInterval(), "syncing topic ACLs"); scheduler.scheduleRepeating(this::syncTopicConfigs, config.syncTopicConfigsInterval(), "syncing topic configs"); scheduler.scheduleRepeatingDelayed(this::refreshTopicPartitions, config.refreshTopicsInterval(), "refreshing topics"); log.info("Started {} with {} topic-partitions.", connectorName, knownSourceTopicPartitions.size()); log.info("Starting {} took {} ms.", connectorName, System.currentTimeMillis() - start); } @Override public void stop() { long start = System.currentTimeMillis(); if (!config.enabled()) { return; } Utils.closeQuietly(scheduler, "scheduler"); Utils.closeQuietly(topicFilter, "topic filter"); Utils.closeQuietly(configPropertyFilter, "config property filter"); Utils.closeQuietly(sourceAdminClient, "source admin client"); Utils.closeQuietly(targetAdminClient, "target admin client"); log.info("Stopping {} took {} ms.", connectorName, System.currentTimeMillis() - start); } @Override public Class<? extends Task> taskClass() { return MirrorSourceTask.class; } // divide topic-partitions among tasks // since each mirrored topic has different traffic and number of partitions, to balance the load // across all mirrormaker instances (workers), 'roundrobin' helps to evenly assign all // topic-partition to the tasks, then the tasks are further distributed to workers. // For example, 3 tasks to mirror 3 topics with 8, 2 and 2 partitions respectively. // 't1' denotes 'task 1', 't0p5' denotes 'topic 0, partition 5' // t1 -> [t0p0, t0p3, t0p6, t1p1] // t2 -> [t0p1, t0p4, t0p7, t2p0] // t3 -> [t0p2, t0p5, t1p0, t2p1] @Override public List<Map<String, String>> taskConfigs(int maxTasks) { if (!config.enabled() || knownSourceTopicPartitions.isEmpty()) { return List.of(); } int numTasks = Math.min(maxTasks, knownSourceTopicPartitions.size()); List<List<TopicPartition>> roundRobinByTask = new ArrayList<>(numTasks); for (int i = 0; i < numTasks; i++) { roundRobinByTask.add(new ArrayList<>()); } int count = 0; for (TopicPartition partition : knownSourceTopicPartitions) { int index = count % numTasks; roundRobinByTask.get(index).add(partition); count++; } return IntStream.range(0, numTasks) .mapToObj(i -> config.taskConfigForTopicPartitions(roundRobinByTask.get(i), i)) .collect(Collectors.toList()); } @Override public ConfigDef config() { return MirrorSourceConfig.CONNECTOR_CONFIG_DEF; } @Override public org.apache.kafka.common.config.Config validate(Map<String, String> props) { List<ConfigValue> configValues = super.validate(props).configValues(); validateExactlyOnceConfigs(props, configValues); validateEmitOffsetSyncConfigs(props, configValues); return new org.apache.kafka.common.config.Config(configValues); } private static void validateEmitOffsetSyncConfigs(Map<String, String> props, List<ConfigValue> configValues) { boolean offsetSyncsConfigured = props.keySet().stream() .anyMatch(conf -> conf.startsWith(OFFSET_SYNCS_CLIENT_ROLE_PREFIX) || conf.startsWith(OFFSET_SYNCS_TOPIC_CONFIG_PREFIX)); if ("false".equals(props.get(MirrorConnectorConfig.EMIT_OFFSET_SYNCS_ENABLED)) && offsetSyncsConfigured) { ConfigValue emitOffsetSyncs = configValues.stream().filter(prop -> MirrorConnectorConfig.EMIT_OFFSET_SYNCS_ENABLED.equals(prop.name())) .findAny() .orElseGet(() -> { ConfigValue result = new ConfigValue(MirrorConnectorConfig.EMIT_OFFSET_SYNCS_ENABLED); configValues.add(result); return result; }); emitOffsetSyncs.addErrorMessage("MirrorSourceConnector can't setup offset-syncs feature while " + MirrorConnectorConfig.EMIT_OFFSET_SYNCS_ENABLED + " set to false"); } } private void validateExactlyOnceConfigs(Map<String, String> props, List<ConfigValue> configValues) { if ("required".equals(props.get(EXACTLY_ONCE_SUPPORT_CONFIG))) { if (!consumerUsesReadCommitted(props)) { ConfigValue exactlyOnceSupport = configValues.stream() .filter(cv -> EXACTLY_ONCE_SUPPORT_CONFIG.equals(cv.name())) .findAny() .orElseGet(() -> { ConfigValue result = new ConfigValue(EXACTLY_ONCE_SUPPORT_CONFIG); configValues.add(result); return result; }); // The Connect framework will already generate an error for this property if we return ExactlyOnceSupport.UNSUPPORTED // from our exactlyOnceSupport method, but it will be fairly generic // We add a second error message here to give users more insight into why this specific connector can't support exactly-once // guarantees with the given configuration exactlyOnceSupport.addErrorMessage( "MirrorSourceConnector can only provide exactly-once guarantees when its source consumer is configured with " + ConsumerConfig.ISOLATION_LEVEL_CONFIG + " set to '" + READ_COMMITTED + "'; " + "otherwise, records from aborted and uncommitted transactions will be replicated from the " + "source cluster to the target cluster." ); } } } @Override public String version() { return AppInfoParser.getVersion(); } @Override public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) { return consumerUsesReadCommitted(props) ? ExactlyOnceSupport.SUPPORTED : ExactlyOnceSupport.UNSUPPORTED; } @Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null) { // We allow tombstones for anything; if there's garbage in the offsets for the connector, we don't // want to prevent users from being able to clean it up using the REST API continue; } Map<String, ?> sourcePartition = offsetEntry.getKey(); if (sourcePartition == null) { throw new ConnectException("Source partitions may not be null"); } MirrorUtils.validateSourcePartitionString(sourcePartition, SOURCE_CLUSTER_KEY); MirrorUtils.validateSourcePartitionString(sourcePartition, TOPIC_KEY); MirrorUtils.validateSourcePartitionPartition(sourcePartition); MirrorUtils.validateSourceOffset(sourcePartition, sourceOffset, false); } // We never commit offsets with our source consumer, so no additional effort is required beyond just validating // the format of the user-supplied offsets return true; } private boolean consumerUsesReadCommitted(Map<String, String> props) { Object consumerIsolationLevel = MirrorSourceConfig.sourceConsumerConfig(props) .get(ConsumerConfig.ISOLATION_LEVEL_CONFIG); return Objects.equals(READ_COMMITTED, consumerIsolationLevel); } // visible for testing List<TopicPartition> findSourceTopicPartitions() throws InterruptedException, ExecutionException { Set<String> topics = listTopics(sourceAdminClient).stream() .filter(this::shouldReplicateTopic) .collect(Collectors.toSet()); return describeTopics(sourceAdminClient, topics).stream() .flatMap(MirrorSourceConnector::expandTopicDescription) .collect(Collectors.toList()); } // visible for testing List<TopicPartition> findTargetTopicPartitions() throws InterruptedException, ExecutionException { Set<String> topics = listTopics(targetAdminClient).stream() .filter(t -> sourceAndTarget.source().equals(replicationPolicy.topicSource(t))) .filter(t -> !t.equals(config.checkpointsTopic())) .collect(Collectors.toSet()); return describeTopics(targetAdminClient, topics).stream() .flatMap(MirrorSourceConnector::expandTopicDescription) .collect(Collectors.toList()); } // visible for testing void refreshTopicPartitions() throws InterruptedException, ExecutionException { List<TopicPartition> sourceTopicPartitions = findSourceTopicPartitions(); List<TopicPartition> targetTopicPartitions = findTargetTopicPartitions(); Set<TopicPartition> sourceTopicPartitionsSet = new HashSet<>(sourceTopicPartitions); Set<TopicPartition> knownSourceTopicPartitionsSet = new HashSet<>(knownSourceTopicPartitions); Set<TopicPartition> upstreamTargetTopicPartitions = targetTopicPartitions.stream() .map(x -> new TopicPartition(replicationPolicy.upstreamTopic(x.topic()), x.partition())) .collect(Collectors.toSet()); Set<TopicPartition> missingInTarget = new HashSet<>(sourceTopicPartitions); missingInTarget.removeAll(upstreamTargetTopicPartitions); knownTargetTopicPartitions = targetTopicPartitions; // Detect if topic-partitions were added or deleted from the source cluster // or if topic-partitions are missing from the target cluster if (!knownSourceTopicPartitionsSet.equals(sourceTopicPartitionsSet) || !missingInTarget.isEmpty()) { Set<TopicPartition> newTopicPartitions = new HashSet<>(sourceTopicPartitions); newTopicPartitions.removeAll(knownSourceTopicPartitionsSet); Set<TopicPartition> deletedTopicPartitions = knownSourceTopicPartitionsSet; deletedTopicPartitions.removeAll(sourceTopicPartitionsSet); log.info("Found {} new topic-partitions on {}. " + "Found {} deleted topic-partitions on {}. " + "Found {} topic-partitions missing on {}.", newTopicPartitions.size(), sourceAndTarget.source(), deletedTopicPartitions.size(), sourceAndTarget.source(), missingInTarget.size(), sourceAndTarget.target()); log.trace("Found new topic-partitions on {}: {}", sourceAndTarget.source(), newTopicPartitions); log.trace("Found deleted topic-partitions on {}: {}", sourceAndTarget.source(), deletedTopicPartitions); log.trace("Found missing topic-partitions on {}: {}", sourceAndTarget.target(), missingInTarget); knownSourceTopicPartitions = sourceTopicPartitions; computeAndCreateTopicPartitions(); context.requestTaskReconfiguration(); } } private void loadTopicPartitions() throws InterruptedException, ExecutionException { knownSourceTopicPartitions = findSourceTopicPartitions(); knownTargetTopicPartitions = findTargetTopicPartitions(); } private void refreshKnownTargetTopics() throws InterruptedException, ExecutionException { knownTargetTopicPartitions = findTargetTopicPartitions(); } private Set<String> topicsBeingReplicated() { Set<String> knownTargetTopics = toTopics(knownTargetTopicPartitions); return knownSourceTopicPartitions.stream() .map(TopicPartition::topic) .distinct() .filter(x -> knownTargetTopics.contains(formatRemoteTopic(x))) .collect(Collectors.toSet()); } private Set<String> toTopics(Collection<TopicPartition> tps) { return tps.stream() .map(TopicPartition::topic) .collect(Collectors.toSet()); } // Visible for testing void syncTopicAcls() throws InterruptedException, ExecutionException { Optional<Collection<AclBinding>> rawBindings = listTopicAclBindings(); if (rawBindings.isEmpty()) return; List<AclBinding> filteredBindings = rawBindings.get().stream() .filter(x -> x.pattern().resourceType() == ResourceType.TOPIC) .filter(x -> x.pattern().patternType() == PatternType.LITERAL) .filter(this::shouldReplicateAcl) .filter(x -> shouldReplicateTopic(x.pattern().name())) .map(this::targetAclBinding) .collect(Collectors.toList()); updateTopicAcls(filteredBindings); } // visible for testing void syncTopicConfigs() throws InterruptedException, ExecutionException { Map<String, Config> sourceConfigs = describeTopicConfigs(topicsBeingReplicated()); Map<String, Config> targetConfigs = sourceConfigs.entrySet().stream() .collect(Collectors.toMap(x -> formatRemoteTopic(x.getKey()), x -> targetConfig(x.getValue(), true))); incrementalAlterConfigs(targetConfigs); } private void createOffsetSyncsTopic() { if (config.emitOffsetSyncsEnabled()) { try (Admin offsetSyncsAdminClient = config.forwardingAdmin(config.offsetSyncsTopicAdminConfig())) { MirrorUtils.createSinglePartitionCompactedTopic( config.offsetSyncsTopic(), config.offsetSyncsTopicReplicationFactor(), offsetSyncsAdminClient ); } } } void computeAndCreateTopicPartitions() throws ExecutionException, InterruptedException { // get source and target topics with respective partition counts Map<String, Long> sourceTopicToPartitionCounts = knownSourceTopicPartitions.stream() .collect(Collectors.groupingBy(TopicPartition::topic, Collectors.counting())).entrySet().stream() .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); Map<String, Long> targetTopicToPartitionCounts = knownTargetTopicPartitions.stream() .collect(Collectors.groupingBy(TopicPartition::topic, Collectors.counting())).entrySet().stream() .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); Set<String> knownSourceTopics = sourceTopicToPartitionCounts.keySet(); Set<String> knownTargetTopics = targetTopicToPartitionCounts.keySet(); Map<String, String> sourceToRemoteTopics = knownSourceTopics.stream() .collect(Collectors.toMap(Function.identity(), this::formatRemoteTopic)); // compute existing and new source topics Map<Boolean, Set<String>> partitionedSourceTopics = knownSourceTopics.stream() .collect(Collectors.partitioningBy(sourceTopic -> knownTargetTopics.contains(sourceToRemoteTopics.get(sourceTopic)), Collectors.toSet())); Set<String> existingSourceTopics = partitionedSourceTopics.get(true); Set<String> newSourceTopics = partitionedSourceTopics.get(false); // create new topics if (!newSourceTopics.isEmpty()) createNewTopics(newSourceTopics, sourceTopicToPartitionCounts); // compute topics with new partitions Map<String, Long> sourceTopicsWithNewPartitions = existingSourceTopics.stream() .filter(sourceTopic -> { String targetTopic = sourceToRemoteTopics.get(sourceTopic); return sourceTopicToPartitionCounts.get(sourceTopic) > targetTopicToPartitionCounts.get(targetTopic); }) .collect(Collectors.toMap(Function.identity(), sourceTopicToPartitionCounts::get)); // create new partitions if (!sourceTopicsWithNewPartitions.isEmpty()) { Map<String, NewPartitions> newTargetPartitions = sourceTopicsWithNewPartitions.entrySet().stream() .collect(Collectors.toMap(sourceTopicAndPartitionCount -> sourceToRemoteTopics.get(sourceTopicAndPartitionCount.getKey()), sourceTopicAndPartitionCount -> NewPartitions.increaseTo(sourceTopicAndPartitionCount.getValue().intValue()))); createNewPartitions(newTargetPartitions); } } // visible for testing void createNewTopics(Set<String> newSourceTopics, Map<String, Long> sourceTopicToPartitionCounts) throws ExecutionException, InterruptedException { Map<String, Config> sourceTopicToConfig = describeTopicConfigs(newSourceTopics); Map<String, NewTopic> newTopics = newSourceTopics.stream() .map(sourceTopic -> { String remoteTopic = formatRemoteTopic(sourceTopic); int partitionCount = sourceTopicToPartitionCounts.get(sourceTopic).intValue(); Map<String, String> configs = configToMap(targetConfig(sourceTopicToConfig.get(sourceTopic), false)); return new NewTopic(remoteTopic, partitionCount, (short) replicationFactor) .configs(configs); }) .collect(Collectors.toMap(NewTopic::name, Function.identity())); createNewTopics(newTopics); } // visible for testing void createNewTopics(Map<String, NewTopic> newTopics) throws ExecutionException, InterruptedException { adminCall( () -> { targetAdminClient.createTopics(newTopics.values(), new CreateTopicsOptions()).values() .forEach((k, v) -> v.whenComplete((x, e) -> { if (e != null) { log.warn("Could not create topic {}.", k, e); } else { log.info("Created remote topic {} with {} partitions.", k, newTopics.get(k).numPartitions()); } })); return null; }, () -> String.format("create topics %s on %s cluster", newTopics, config.targetClusterAlias()) ); } void createNewPartitions(Map<String, NewPartitions> newPartitions) throws ExecutionException, InterruptedException { adminCall( () -> { targetAdminClient.createPartitions(newPartitions).values().forEach((k, v) -> v.whenComplete((x, e) -> { if (e instanceof InvalidPartitionsException) { // swallow, this is normal } else if (e != null) { log.warn("Could not create topic-partitions for {}.", k, e); } else { log.info("Increased size of {} to {} partitions.", k, newPartitions.get(k).totalCount()); } })); return null; }, () -> String.format("create partitions %s on %s cluster", newPartitions, config.targetClusterAlias()) ); } private Set<String> listTopics(Admin adminClient) throws InterruptedException, ExecutionException { return adminCall( () -> adminClient.listTopics().names().get(), () -> "list topics on " + actualClusterAlias(adminClient) + " cluster" ); } private Optional<Collection<AclBinding>> listTopicAclBindings() throws InterruptedException, ExecutionException { return adminCall( () -> { Collection<AclBinding> bindings; try { bindings = sourceAdminClient.describeAcls(ANY_TOPIC_ACL).values().get(); } catch (ExecutionException e) { if (e.getCause() instanceof SecurityDisabledException) { if (noAclAuthorizer.compareAndSet(false, true)) { log.info( "No ACL authorizer is configured on the source Kafka cluster, so no topic ACL syncing will take place. " + "Consider disabling topic ACL syncing by setting " + SYNC_TOPIC_ACLS_ENABLED + " to 'false'." ); } else { log.debug("Source-side ACL authorizer still not found; skipping topic ACL sync"); } return Optional.empty(); } else { throw e; } } return Optional.of(bindings); }, () -> "describe ACLs on " + config.sourceClusterAlias() + " cluster" ); } private Collection<TopicDescription> describeTopics(Admin adminClient, Collection<String> topics) throws InterruptedException, ExecutionException { return adminCall( () -> adminClient.describeTopics(topics).allTopicNames().get().values(), () -> String.format("describe topics %s on %s cluster", topics, actualClusterAlias(adminClient)) ); } static Map<String, String> configToMap(Config config) { return config.entries().stream() .collect(Collectors.toMap(ConfigEntry::name, ConfigEntry::value)); } // visible for testing void incrementalAlterConfigs(Map<String, Config> topicConfigs) throws ExecutionException, InterruptedException { Map<ConfigResource, Collection<AlterConfigOp>> configOps = new HashMap<>(); for (Map.Entry<String, Config> topicConfig : topicConfigs.entrySet()) { Collection<AlterConfigOp> ops = new ArrayList<>(); ConfigResource configResource = new ConfigResource(ConfigResource.Type.TOPIC, topicConfig.getKey()); for (ConfigEntry config : topicConfig.getValue().entries()) { if (config.isDefault() && !shouldReplicateSourceDefault(config.name())) { ops.add(new AlterConfigOp(config, AlterConfigOp.OpType.DELETE)); } else { ops.add(new AlterConfigOp(config, AlterConfigOp.OpType.SET)); } } configOps.put(configResource, ops); } log.trace("Syncing configs for {} topics.", configOps.size()); adminCall(() -> { targetAdminClient.incrementalAlterConfigs(configOps).values() .forEach((k, v) -> v.whenComplete((x, e) -> { if (e instanceof UnsupportedVersionException) { log.error("Failed to sync configs for topic {} on cluster {} with " + "IncrementalAlterConfigs API", k.name(), sourceAndTarget.target(), e); context.raiseError(new ConnectException("the target cluster '" + sourceAndTarget.target() + "' is not compatible with " + "IncrementalAlterConfigs " + "API", e)); } else { log.warn("Could not alter configuration of topic {}.", k.name(), e); } })); return null; }, () -> String.format("incremental alter topic configs %s on %s cluster", topicConfigs, config.targetClusterAlias())); } private void updateTopicAcls(List<AclBinding> bindings) throws ExecutionException, InterruptedException { log.trace("Syncing {} topic ACL bindings.", bindings.size()); adminCall( () -> { targetAdminClient.createAcls(bindings).values().forEach((k, v) -> v.whenComplete((x, e) -> { if (e != null) { log.warn("Could not sync ACL of topic {}.", k.pattern().name(), e); } })); return null; }, () -> String.format("create ACLs %s on %s cluster", bindings, config.targetClusterAlias()) ); } private static Stream<TopicPartition> expandTopicDescription(TopicDescription description) { String topic = description.name(); return description.partitions().stream() .map(x -> new TopicPartition(topic, x.partition())); } Map<String, Config> describeTopicConfigs(Set<String> topics) throws InterruptedException, ExecutionException { Set<ConfigResource> resources = topics.stream() .map(x -> new ConfigResource(ConfigResource.Type.TOPIC, x)) .collect(Collectors.toSet()); return adminCall( () -> sourceAdminClient.describeConfigs(resources).all().get().entrySet().stream() .collect(Collectors.toMap(x -> x.getKey().name(), Entry::getValue)), () -> String.format("describe configs for topics %s on %s cluster", topics, config.sourceClusterAlias()) ); } Config targetConfig(Config sourceConfig, boolean incremental) { // If using incrementalAlterConfigs API, sync the default property with either SET or DELETE action determined by ConfigPropertyFilter::shouldReplicateSourceDefault later. // If not using incrementalAlterConfigs API, sync the default property only if ConfigPropertyFilter::shouldReplicateSourceDefault returns true. // If ConfigPropertyFilter::shouldReplicateConfigProperty returns false, do not sync the property at all. List<ConfigEntry> entries = sourceConfig.entries().stream() .filter(x -> incremental || (x.isDefault() && shouldReplicateSourceDefault(x.name())) || !x.isDefault()) .filter(x -> !x.isReadOnly() && !x.isSensitive()) .filter(x -> x.source() != ConfigEntry.ConfigSource.STATIC_BROKER_CONFIG) .filter(x -> shouldReplicateTopicConfigurationProperty(x.name())) .collect(Collectors.toList()); return new Config(entries); } private static AccessControlEntry downgradeAllowAllACL(AccessControlEntry entry) { return new AccessControlEntry(entry.principal(), entry.host(), AclOperation.READ, entry.permissionType()); } AclBinding targetAclBinding(AclBinding sourceAclBinding) { String targetTopic = formatRemoteTopic(sourceAclBinding.pattern().name()); final AccessControlEntry entry; if (sourceAclBinding.entry().permissionType() == AclPermissionType.ALLOW && sourceAclBinding.entry().operation() == AclOperation.ALL) { entry = downgradeAllowAllACL(sourceAclBinding.entry()); } else { entry = sourceAclBinding.entry(); } return new AclBinding(new ResourcePattern(ResourceType.TOPIC, targetTopic, PatternType.LITERAL), entry); } boolean shouldReplicateTopic(String topic) { return (topicFilter.shouldReplicateTopic(topic) || (heartbeatsReplicationEnabled && replicationPolicy.isHeartbeatsTopic(topic))) && !replicationPolicy.isInternalTopic(topic) && !isCycle(topic); } boolean shouldReplicateAcl(AclBinding aclBinding) { return !(aclBinding.entry().permissionType() == AclPermissionType.ALLOW && aclBinding.entry().operation() == AclOperation.WRITE); } boolean shouldReplicateTopicConfigurationProperty(String property) { return configPropertyFilter.shouldReplicateConfigProperty(property); } boolean shouldReplicateSourceDefault(String property) { return configPropertyFilter.shouldReplicateSourceDefault(property); } // Recurse upstream to detect cycles, i.e. whether this topic is already on the target cluster boolean isCycle(String topic) { String source = replicationPolicy.topicSource(topic); if (source == null) { return false; } else if (source.equals(sourceAndTarget.target())) { return true; } else { String upstreamTopic = replicationPolicy.upstreamTopic(topic); if (upstreamTopic == null || upstreamTopic.equals(topic)) { // Extra check for IdentityReplicationPolicy and similar impls that don't prevent cycles. return false; } return isCycle(upstreamTopic); } } String formatRemoteTopic(String topic) { return replicationPolicy.formatRemoteTopic(sourceAndTarget.source(), topic); } private String actualClusterAlias(Admin adminClient) { return adminClient.equals(sourceAdminClient) ? config.sourceClusterAlias() : config.targetClusterAlias(); } }
googleapis/google-cloud-java
36,901
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/UpdateDatasetVersionRequest.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/dataset_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Request message for * [DatasetService.UpdateDatasetVersion][google.cloud.aiplatform.v1beta1.DatasetService.UpdateDatasetVersion]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest} */ public final class UpdateDatasetVersionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) UpdateDatasetVersionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateDatasetVersionRequest.newBuilder() to construct. private UpdateDatasetVersionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateDatasetVersionRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateDatasetVersionRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1beta1_UpdateDatasetVersionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1beta1_UpdateDatasetVersionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.class, com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.Builder.class); } private int bitField0_; public static final int DATASET_VERSION_FIELD_NUMBER = 1; private com.google.cloud.aiplatform.v1beta1.DatasetVersion datasetVersion_; /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the datasetVersion field is set. */ @java.lang.Override public boolean hasDatasetVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The datasetVersion. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.DatasetVersion getDatasetVersion() { return datasetVersion_ == null ? com.google.cloud.aiplatform.v1beta1.DatasetVersion.getDefaultInstance() : datasetVersion_; } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.DatasetVersionOrBuilder getDatasetVersionOrBuilder() { return datasetVersion_ == null ? com.google.cloud.aiplatform.v1beta1.DatasetVersion.getDefaultInstance() : datasetVersion_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getDatasetVersion()); } 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, getDatasetVersion()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest other = (com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) obj; if (hasDatasetVersion() != other.hasDatasetVersion()) return false; if (hasDatasetVersion()) { if (!getDatasetVersion().equals(other.getDatasetVersion())) 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 (hasDatasetVersion()) { hash = (37 * hash) + DATASET_VERSION_FIELD_NUMBER; hash = (53 * hash) + getDatasetVersion().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest 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.UpdateDatasetVersionRequest 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 * [DatasetService.UpdateDatasetVersion][google.cloud.aiplatform.v1beta1.DatasetService.UpdateDatasetVersion]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1beta1_UpdateDatasetVersionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1beta1_UpdateDatasetVersionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.class, com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getDatasetVersionFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; datasetVersion_ = null; if (datasetVersionBuilder_ != null) { datasetVersionBuilder_.dispose(); datasetVersionBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1beta1_UpdateDatasetVersionRequest_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest build() { com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest buildPartial() { com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest result = new com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.datasetVersion_ = datasetVersionBuilder_ == null ? datasetVersion_ : datasetVersionBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest other) { if (other == com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest.getDefaultInstance()) return this; if (other.hasDatasetVersion()) { mergeDatasetVersion(other.getDatasetVersion()); } 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(getDatasetVersionFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.aiplatform.v1beta1.DatasetVersion datasetVersion_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.DatasetVersion, com.google.cloud.aiplatform.v1beta1.DatasetVersion.Builder, com.google.cloud.aiplatform.v1beta1.DatasetVersionOrBuilder> datasetVersionBuilder_; /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the datasetVersion field is set. */ public boolean hasDatasetVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The datasetVersion. */ public com.google.cloud.aiplatform.v1beta1.DatasetVersion getDatasetVersion() { if (datasetVersionBuilder_ == null) { return datasetVersion_ == null ? com.google.cloud.aiplatform.v1beta1.DatasetVersion.getDefaultInstance() : datasetVersion_; } else { return datasetVersionBuilder_.getMessage(); } } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDatasetVersion(com.google.cloud.aiplatform.v1beta1.DatasetVersion value) { if (datasetVersionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } datasetVersion_ = value; } else { datasetVersionBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDatasetVersion( com.google.cloud.aiplatform.v1beta1.DatasetVersion.Builder builderForValue) { if (datasetVersionBuilder_ == null) { datasetVersion_ = builderForValue.build(); } else { datasetVersionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeDatasetVersion(com.google.cloud.aiplatform.v1beta1.DatasetVersion value) { if (datasetVersionBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && datasetVersion_ != null && datasetVersion_ != com.google.cloud.aiplatform.v1beta1.DatasetVersion.getDefaultInstance()) { getDatasetVersionBuilder().mergeFrom(value); } else { datasetVersion_ = value; } } else { datasetVersionBuilder_.mergeFrom(value); } if (datasetVersion_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearDatasetVersion() { bitField0_ = (bitField0_ & ~0x00000001); datasetVersion_ = null; if (datasetVersionBuilder_ != null) { datasetVersionBuilder_.dispose(); datasetVersionBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.DatasetVersion.Builder getDatasetVersionBuilder() { bitField0_ |= 0x00000001; onChanged(); return getDatasetVersionFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.DatasetVersionOrBuilder getDatasetVersionOrBuilder() { if (datasetVersionBuilder_ != null) { return datasetVersionBuilder_.getMessageOrBuilder(); } else { return datasetVersion_ == null ? com.google.cloud.aiplatform.v1beta1.DatasetVersion.getDefaultInstance() : datasetVersion_; } } /** * * * <pre> * Required. The DatasetVersion which replaces the resource on the server. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.DatasetVersion dataset_version = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.DatasetVersion, com.google.cloud.aiplatform.v1beta1.DatasetVersion.Builder, com.google.cloud.aiplatform.v1beta1.DatasetVersionOrBuilder> getDatasetVersionFieldBuilder() { if (datasetVersionBuilder_ == null) { datasetVersionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.DatasetVersion, com.google.cloud.aiplatform.v1beta1.DatasetVersion.Builder, com.google.cloud.aiplatform.v1beta1.DatasetVersionOrBuilder>( getDatasetVersion(), getParentForChildren(), isClean()); datasetVersion_ = null; } return datasetVersionBuilder_; } 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 * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. The update mask applies to the resource. * For the `FieldMask` definition, see * [google.protobuf.FieldMask][google.protobuf.FieldMask]. Updatable fields: * * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest) private static final com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest(); } public static com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateDatasetVersionRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateDatasetVersionRequest>() { @java.lang.Override public UpdateDatasetVersionRequest 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<UpdateDatasetVersionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateDatasetVersionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.UpdateDatasetVersionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,918
java-confidentialcomputing/proto-google-cloud-confidentialcomputing-v1/src/main/java/com/google/cloud/confidentialcomputing/v1/ServiceProto.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/confidentialcomputing/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.confidentialcomputing.v1; public final class ServiceProto { private ServiceProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_Challenge_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_Challenge_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_CreateChallengeRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_CreateChallengeRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_TdxCcelAttestation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_TdxCcelAttestation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_SevSnpAttestation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_SevSnpAttestation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_GcpCredentials_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_GcpCredentials_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_TokenOptions_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_TokenOptions_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_ContainerImageSignatures_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_ContainerImageSignatures_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_PcrValuesEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_PcrValuesEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_ContainerImageSignature_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_ContainerImageSignature_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_GceShieldedIdentity_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_GceShieldedIdentity_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n" + "3google/cloud/confidentialcomputing/v1/service.proto\022%google.cloud.confidential" + "computing.v1\032\034google/api/annotations.pro" + "to\032\027google/api/client.proto\032\037google/api/" + "field_behavior.proto\032\031google/api/resourc" + "e.proto\032\037google/protobuf/timestamp.proto\032\027google/rpc/status.proto\"\245\002\n" + "\tChallenge\022\021\n" + "\004name\030\001 \001(\tB\003\340A\003\0224\n" + "\013create_time\030\002 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\0224\n" + "\013expire_time\030\003" + " \001(\0132\032.google.protobuf.TimestampB\003\340A\003\022\021\n" + "\004used\030\004 \001(\010B\003\340A\003\022\026\n" + "\ttpm_nonce\030\006 \001(\tB\003\340A\003:n\352Ak\n" + ".confidentialcomputing.googleapis.com/Challenge\0229projects/{projec" + "t}/locations/{location}/challenges/{uuid}\"\235\001\n" + "\026CreateChallengeRequest\0229\n" + "\006parent\030\001 \001(\tB)\340A\002\372A#\n" + "!locations.googleapis.com/Location\022H\n" + "\tchallenge\030\002 \001(\01320.google.clou" + "d.confidentialcomputing.v1.ChallengeB\003\340A\002\"\237\005\n" + "\030VerifyAttestationRequest\022Q\n" + "\007td_ccel\030\006" + " \001(\01329.google.cloud.confidentialcomputing.v1.TdxCcelAttestationB\003\340A\001H\000\022\\\n" + "\023sev_snp_attestation\030\007 \001(\01328.google.cloud.co" + "nfidentialcomputing.v1.SevSnpAttestationB\003\340A\001H\000\022I\n" + "\tchallenge\030\001 \001(\tB6\340A\002\372A0\n" + ".confidentialcomputing.googleapis.com/Challenge\022S\n" + "\017gcp_credentials\030\002 \001(\01325.google.clo" + "ud.confidentialcomputing.v1.GcpCredentialsB\003\340A\001\022S\n" + "\017tpm_attestation\030\003 \001(\01325.googl" + "e.cloud.confidentialcomputing.v1.TpmAttestationB\003\340A\002\022b\n" + "\027confidential_space_info\030\004" + " \001(\0132<.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfoB\003\340A\001\022O\n\r" + "token_options\030\005" + " \001(\01323.google.cloud.confidentialcomputing.v1.TokenOptionsB\003\340A\001\022\025\n" + "\010attester\030\010 \001(\tB\003\340A\001B\021\n" + "\017tee_attestation\"\203\001\n" + "\022TdxCcelAttestation\022\034\n" + "\017ccel_acpi_table\030\001 \001(\014B\003\340A\001\022\026\n" + "\tccel_data\030\002 \001(\014B\003\340A\001\022 \n" + "\023canonical_event_log\030\003 \001(\014B\003\340A\001\022\025\n" + "\010td_quote\030\004 \001(\014B\003\340A\001\"?\n" + "\021SevSnpAttestation\022\023\n" + "\006report\030\001 \001(\014B\003\340A\001\022\025\n" + "\010aux_blob\030\002 \001(\014B\003\340A\001\"l\n" + "\031VerifyAttestationResponse\022\036\n" + "\021oidc_claims_token\030\002 \001(\tB\003\340A\003\022/\n" + "\016partial_errors\030\003 \003(\0132\022.google.rpc.StatusB\003\340A\003\"3\n" + "\016GcpCredentials\022!\n" + "\031service_account_id_tokens\030\002 \003(\t\"\205\002\n" + "\014TokenOptions\022i\n" + "\032aws_principal_tags_options\030\004 \001(\0132>.google.cloud.confidentialco" + "mputing.v1.AwsPrincipalTagsOptionsB\003\340A\001H\000\022\025\n" + "\010audience\030\001 \001(\tB\003\340A\001\022\022\n" + "\005nonce\030\002 \003(\tB\003\340A\001\022I\n\n" + "token_type\030\003 \001(\01620.google.cloud." + "confidentialcomputing.v1.TokenTypeB\003\340A\001B\024\n" + "\022token_type_options\"\366\002\n" + "\027AwsPrincipalTagsOptions\022x\n" + "\026allowed_principal_tags\030\001 \001(\0132S.google.cloud.confidentialcomputing.v" + "1.AwsPrincipalTagsOptions.AllowedPrincipalTagsB\003\340A\001\032\340\001\n" + "\024AllowedPrincipalTags\022\225\001\n" + "\032container_image_signatures\030\001 \001(\0132l.goog" + "le.cloud.confidentialcomputing.v1.AwsPri" + "ncipalTagsOptions.AllowedPrincipalTags.ContainerImageSignaturesB\003\340A\001\0320\n" + "\030ContainerImageSignatures\022\024\n" + "\007key_ids\030\001 \003(\tB\003\340A\001\"\217\003\n" + "\016TpmAttestation\022K\n" + "\006quotes\030\001 \003(\0132;.goog" + "le.cloud.confidentialcomputing.v1.TpmAttestation.Quote\022\025\n\r" + "tcg_event_log\030\002 \001(\014\022\033\n" + "\023canonical_event_log\030\003 \001(\014\022\017\n" + "\007ak_cert\030\004 \001(\014\022\022\n\n" + "cert_chain\030\005 \003(\014\032\326\001\n" + "\005Quote\022\021\n" + "\thash_algo\030\001 \001(\005\022^\n\n" + "pcr_values\030\002 \003(\0132J.googl" + "e.cloud.confidentialcomputing.v1.TpmAttestation.Quote.PcrValuesEntry\022\021\n" + "\traw_quote\030\003 \001(\014\022\025\n\r" + "raw_signature\030\004 \001(\014\0320\n" + "\016PcrValuesEntry\022\013\n" + "\003key\030\001 \001(\005\022\r\n" + "\005value\030\002 \001(\014:\0028\001\"j\n" + "\025ConfidentialSpaceInfo\022Q\n" + "\017signed_entities\030\001" + " \003(\01323.google.cloud.confidentialcomputing.v1.SignedEntityB\003\340A\001\"w\n" + "\014SignedEntity\022g\n" + "\032container_image_signatures\030\001 \003(\013" + "2>.google.cloud.confidentialcomputing.v1.ContainerImageSignatureB\003\340A\001\"\257\001\n" + "\027ContainerImageSignature\022\024\n" + "\007payload\030\001 \001(\014B\003\340A\001\022\026\n" + "\tsignature\030\002 \001(\014B\003\340A\001\022\027\n\n" + "public_key\030\003 \001(\014B\003\340A\001\022M\n" + "\007sig_alg\030\004 \001(\01627.google.cloud" + ".confidentialcomputing.v1.SigningAlgorithmB\003\340A\001\"\226\010\n" + "\036VerifyConfidentialSpaceRequest\022Q\n" + "\007td_ccel\030\003 \001(\01329.google.cloud.confi" + "dentialcomputing.v1.TdxCcelAttestationB\003\340A\004H\000\022U\n" + "\017tpm_attestation\030\004 \001(\01325.google." + "cloud.confidentialcomputing.v1.TpmAttestationB\003\340A\004H\000\022I\n" + "\tchallenge\030\001 \001(\tB6\340A\002\372A0\n" + ".confidentialcomputing.googleapis.com/Challenge\022S\n" + "\017gcp_credentials\030\002 \001(\01325.googl" + "e.cloud.confidentialcomputing.v1.GcpCredentialsB\003\340A\001\022Q\n" + "\017signed_entities\030\005 \003(\01323." + "google.cloud.confidentialcomputing.v1.SignedEntityB\003\340A\001\022^\n" + "\025gce_shielded_identity\030\006" + " \001(\0132:.google.cloud.confidentialcomputing.v1.GceShieldedIdentityB\003\340A\001\022t\n" + "\007options\030\007 \001(\0132^.google.cloud.confidentialcomp" + "uting.v1.VerifyConfidentialSpaceRequest.ConfidentialSpaceOptionsB\003\340A\001\032\355\002\n" + "\030ConfidentialSpaceOptions\022i\n" + "\032aws_principal_tags_options\030\005 \001(\0132>.google.cloud.confidenti" + "alcomputing.v1.AwsPrincipalTagsOptionsB\003\340A\001H\000\022\025\n" + "\010audience\030\001 \001(\tB\003\340A\001\022O\n\r" + "token_profile\030\002" + " \001(\01623.google.cloud.confidentialcomputing.v1.TokenProfileB\003\340A\001\022\022\n" + "\005nonce\030\003 \003(\tB\003\340A\001\022Q\n" + "\016signature_type\030\004 \001(\01624.goog" + "le.cloud.confidentialcomputing.v1.SignatureTypeB\003\340A\001B\027\n" + "\025token_profile_optionsB\021\n" + "\017tee_attestation\"G\n" + "\023GceShieldedIdentity\022\024\n" + "\007ak_cert\030\001 \001(\014B\003\340A\001\022\032\n\r" + "ak_cert_chain\030\002 \003(\014B\003\340A\001\"r\n" + "\037VerifyConfidentialSpaceResponse\022\036\n" + "\021attestation_token\030\001 \001(\tB\003\340A\003\022/\n" + "\016partial_errors\030\002 \003(\0132\022.google.rpc.StatusB\003\340A\003\"\316\001\n" + "\034VerifyConfidentialGkeRequest\022P\n" + "\017tpm_attestation\030\002 \001(\01325.google.cloud.c" + "onfidentialcomputing.v1.TpmAttestationH\000\022I\n" + "\tchallenge\030\001 \001(\tB6\340A\002\372A0\n" + ".confidentialcomputing.googleapis.com/ChallengeB\021\n" + "\017tee_attestation\"?\n" + "\035VerifyConfidentialGkeResponse\022\036\n" + "\021attestation_token\030\001 \001(\tB\003\340A\003*\177\n" + "\020SigningAlgorithm\022!\n" + "\035SIGNING_ALGORITHM_UNSPECIFIED\020\000\022\025\n" + "\021RSASSA_PSS_SHA256\020\001\022\032\n" + "\026RSASSA_PKCS1V15_SHA256\020\002\022\025\n" + "\021ECDSA_P256_SHA256\020\003*\216\001\n" + "\tTokenType\022\032\n" + "\026TOKEN_TYPE_UNSPECIFIED\020\000\022\023\n" + "\017TOKEN_TYPE_OIDC\020\001\022\022\n" + "\016TOKEN_TYPE_PKI\020\002\022\032\n" + "\026TOKEN_TYPE_LIMITED_AWS\020\003\022 \n" + "\034TOKEN_TYPE_AWS_PRINCIPALTAGS\020\004*`\n\r" + "SignatureType\022\036\n" + "\032SIGNATURE_TYPE_UNSPECIFIED\020\000\022\027\n" + "\023SIGNATURE_TYPE_OIDC\020\001\022\026\n" + "\022SIGNATURE_TYPE_PKI\020\002*c\n" + "\014TokenProfile\022\035\n" + "\031TOKEN_PROFILE_UNSPECIFIED\020\000\022\035\n" + "\031TOKEN_PROFILE_DEFAULT_EAT\020\001\022\025\n" + "\021TOKEN_PROFILE_AWS\020\0022\265\010\n" + "\025ConfidentialComputing\022\330\001\n" + "\017CreateChallenge\022=.google.cloud.confidentialcomputing.v1.C" + "reateChallengeRequest\0320.google.cloud.con" + "fidentialcomputing.v1.Challenge\"T\332A\020pare" + "nt,challenge\202\323\344\223\002;\"./v1/{parent=projects/*/locations/*}/challenges:" + "\tchallenge\022\350\001\n" + "\021VerifyAttestation\022?.google.cloud.confidentialcomputing.v1.VerifyAttestationReq" + "uest\032@.google.cloud.confidentialcomputin" + "g.v1.VerifyAttestationResponse\"P\202\323\344\223\002J\"E" + "/v1/{challenge=projects/*/locations/*/challenges/*}:verifyAttestation:\001*\022\200\002\n" + "\027VerifyConfidentialSpace\022E.google.cloud.conf" + "identialcomputing.v1.VerifyConfidentialSpaceRequest\032F.google.cloud.confidentialc" + "omputing.v1.VerifyConfidentialSpaceRespo" + "nse\"V\202\323\344\223\002P\"K/v1/{challenge=projects/*/l" + "ocations/*/challenges/*}:verifyConfidentialSpace:\001*\022\370\001\n" + "\025VerifyConfidentialGke\022C.google.cloud.confidentialcomputing.v1.Ve" + "rifyConfidentialGkeRequest\032D.google.cloud.confidentialcomputing.v1.VerifyConfide" + "ntialGkeResponse\"T\202\323\344\223\002N\"I/v1/{challenge" + "=projects/*/locations/*/challenges/*}:ve" + "rifyConfidentialGke:\001*\032X\312A$confidentialc" + "omputing.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platformB\227\002\n" + ")com.google.cloud.confidentialcomputing.v1B\014" + "ServiceProtoP\001Z_cloud.google.com/go/confidentialcomputing/apiv1/confidentialcomp" + "utingpb;confidentialcomputingpb\252\002%Google" + ".Cloud.ConfidentialComputing.V1\312\002%Google" + "\\Cloud\\ConfidentialComputing\\V1\352\002(Google" + "::Cloud::ConfidentialComputing::V1b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.protobuf.TimestampProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), }); internal_static_google_cloud_confidentialcomputing_v1_Challenge_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_confidentialcomputing_v1_Challenge_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_Challenge_descriptor, new java.lang.String[] { "Name", "CreateTime", "ExpireTime", "Used", "TpmNonce", }); internal_static_google_cloud_confidentialcomputing_v1_CreateChallengeRequest_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_confidentialcomputing_v1_CreateChallengeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_CreateChallengeRequest_descriptor, new java.lang.String[] { "Parent", "Challenge", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationRequest_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationRequest_descriptor, new java.lang.String[] { "TdCcel", "SevSnpAttestation", "Challenge", "GcpCredentials", "TpmAttestation", "ConfidentialSpaceInfo", "TokenOptions", "Attester", "TeeAttestation", }); internal_static_google_cloud_confidentialcomputing_v1_TdxCcelAttestation_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_confidentialcomputing_v1_TdxCcelAttestation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_TdxCcelAttestation_descriptor, new java.lang.String[] { "CcelAcpiTable", "CcelData", "CanonicalEventLog", "TdQuote", }); internal_static_google_cloud_confidentialcomputing_v1_SevSnpAttestation_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_cloud_confidentialcomputing_v1_SevSnpAttestation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_SevSnpAttestation_descriptor, new java.lang.String[] { "Report", "AuxBlob", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationResponse_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyAttestationResponse_descriptor, new java.lang.String[] { "OidcClaimsToken", "PartialErrors", }); internal_static_google_cloud_confidentialcomputing_v1_GcpCredentials_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_cloud_confidentialcomputing_v1_GcpCredentials_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_GcpCredentials_descriptor, new java.lang.String[] { "ServiceAccountIdTokens", }); internal_static_google_cloud_confidentialcomputing_v1_TokenOptions_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_cloud_confidentialcomputing_v1_TokenOptions_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_TokenOptions_descriptor, new java.lang.String[] { "AwsPrincipalTagsOptions", "Audience", "Nonce", "TokenType", "TokenTypeOptions", }); internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_descriptor, new java.lang.String[] { "AllowedPrincipalTags", }); internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_descriptor = internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_descriptor, new java.lang.String[] { "ContainerImageSignatures", }); internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_ContainerImageSignatures_descriptor = internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_ContainerImageSignatures_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_AwsPrincipalTagsOptions_AllowedPrincipalTags_ContainerImageSignatures_descriptor, new java.lang.String[] { "KeyIds", }); internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_descriptor, new java.lang.String[] { "Quotes", "TcgEventLog", "CanonicalEventLog", "AkCert", "CertChain", }); internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_descriptor = internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_descriptor, new java.lang.String[] { "HashAlgo", "PcrValues", "RawQuote", "RawSignature", }); internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_PcrValuesEntry_descriptor = internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_PcrValuesEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_TpmAttestation_Quote_PcrValuesEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_descriptor, new java.lang.String[] { "SignedEntities", }); internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_SignedEntity_descriptor, new java.lang.String[] { "ContainerImageSignatures", }); internal_static_google_cloud_confidentialcomputing_v1_ContainerImageSignature_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_cloud_confidentialcomputing_v1_ContainerImageSignature_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_ContainerImageSignature_descriptor, new java.lang.String[] { "Payload", "Signature", "PublicKey", "SigAlg", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_descriptor, new java.lang.String[] { "TdCcel", "TpmAttestation", "Challenge", "GcpCredentials", "SignedEntities", "GceShieldedIdentity", "Options", "TeeAttestation", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions_descriptor = internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions_descriptor, new java.lang.String[] { "AwsPrincipalTagsOptions", "Audience", "TokenProfile", "Nonce", "SignatureType", "TokenProfileOptions", }); internal_static_google_cloud_confidentialcomputing_v1_GceShieldedIdentity_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_cloud_confidentialcomputing_v1_GceShieldedIdentity_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_GceShieldedIdentity_descriptor, new java.lang.String[] { "AkCert", "AkCertChain", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceResponse_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialSpaceResponse_descriptor, new java.lang.String[] { "AttestationToken", "PartialErrors", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeRequest_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeRequest_descriptor, new java.lang.String[] { "TpmAttestation", "Challenge", "TeeAttestation", }); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeResponse_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_confidentialcomputing_v1_VerifyConfidentialGkeResponse_descriptor, new java.lang.String[] { "AttestationToken", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); registry.add(com.google.api.ResourceProto.resource); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor( descriptor, registry); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.protobuf.TimestampProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
apache/syncope
37,030
fit/core-reference/src/test/java/org/apache/syncope/fit/core/UserSelfITCase.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.syncope.fit.core; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; import jakarta.ws.rs.ForbiddenException; import jakarta.ws.rs.core.GenericType; import jakarta.ws.rs.core.Response; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Triple; import org.apache.syncope.client.lib.SyncopeClient; import org.apache.syncope.common.lib.SyncopeClientException; import org.apache.syncope.common.lib.SyncopeConstants; import org.apache.syncope.common.lib.request.BooleanReplacePatchItem; import org.apache.syncope.common.lib.request.MembershipUR; import org.apache.syncope.common.lib.request.PasswordPatch; import org.apache.syncope.common.lib.request.StringPatchItem; import org.apache.syncope.common.lib.request.StringReplacePatchItem; import org.apache.syncope.common.lib.request.UserCR; import org.apache.syncope.common.lib.request.UserUR; import org.apache.syncope.common.lib.to.MembershipTO; import org.apache.syncope.common.lib.to.NotificationTaskTO; import org.apache.syncope.common.lib.to.PagedResult; import org.apache.syncope.common.lib.to.ProvisioningResult; import org.apache.syncope.common.lib.to.UserRequestForm; import org.apache.syncope.common.lib.to.UserTO; import org.apache.syncope.common.lib.to.WorkflowTask; import org.apache.syncope.common.lib.types.AnyTypeKind; import org.apache.syncope.common.lib.types.ClientExceptionType; import org.apache.syncope.common.lib.types.PatchOperation; import org.apache.syncope.common.lib.types.TaskType; import org.apache.syncope.common.rest.api.beans.ExecSpecs; import org.apache.syncope.common.rest.api.beans.TaskQuery; import org.apache.syncope.common.rest.api.beans.UserRequestQuery; import org.apache.syncope.common.rest.api.service.AccessTokenService; import org.apache.syncope.common.rest.api.service.UserRequestService; import org.apache.syncope.common.rest.api.service.UserSelfService; import org.apache.syncope.common.rest.api.service.UserService; import org.apache.syncope.fit.AbstractITCase; import org.junit.jupiter.api.Test; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; public class UserSelfITCase extends AbstractITCase { private static void checkNotification( final String email, final String notification, final String subject) throws Exception { await().atMost(MAX_WAIT_SECONDS, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> { PagedResult<NotificationTaskTO> tasks = TASK_SERVICE.search(new TaskQuery.Builder(TaskType.NOTIFICATION). notification(notification).build()); return tasks.getResult().stream().filter(t -> t.getRecipients().contains(email) && !t.isExecuted()). findFirst().map(t -> TASK_SERVICE.execute( new ExecSpecs.Builder().key(t.getKey()).build()).getStatus() != null). orElse(false); }); verifyMail("admin@syncope.apache.org", subject, email, MAX_WAIT_SECONDS); } @Test public void selfRegistrationAllowed() { assertTrue(ANONYMOUS_CLIENT.platform().isSelfRegAllowed()); } @Test public void create() { assumeTrue(IS_FLOWABLE_ENABLED); // 1. self-registration as admin: failure try { USER_SELF_SERVICE.create(UserITCase.getUniqueSample("anonymous@syncope.apache.org")); fail("This should not happen"); } catch (ForbiddenException e) { assertNotNull(e); } // 2. self-registration as anonymous: works UserTO self = ANONYMOUS_CLIENT.getService(UserSelfService.class). create(UserITCase.getUniqueSample("anonymous@syncope.apache.org")). readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(self); assertEquals("createApproval", self.getStatus()); } @Test public void createAndApprove() { assumeTrue(IS_FLOWABLE_ENABLED); // 1. self-create user with membership: goes 'createApproval' with resources and membership but no propagation UserCR userCR = UserITCase.getUniqueSample("anonymous@syncope.apache.org"); userCR.getMemberships().add( new MembershipTO.Builder("29f96485-729e-4d31-88a1-6fc60e4677f3").build()); userCR.getResources().add(RESOURCE_NAME_TESTDB); UserTO userTO = ANONYMOUS_CLIENT.getService(UserSelfService.class). create(userCR). readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(userTO); assertEquals("createApproval", userTO.getStatus()); assertFalse(userTO.getMemberships().isEmpty()); assertFalse(userTO.getResources().isEmpty()); try { RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), userTO.getKey()); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.NotFound, e.getType()); } // 2. now approve and verify that propagation has happened UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getKey()).build()).getResult().getFirst(); form = USER_REQUEST_SERVICE.claimForm(form.getTaskId()); form.getProperty("approveCreate").get().setValue(Boolean.TRUE.toString()); userTO = USER_REQUEST_SERVICE.submitForm(form).readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(userTO); assertEquals("active", userTO.getStatus()); assertNotNull(RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), userTO.getKey())); } @Test public void createAndUnclaim() { assumeTrue(IS_FLOWABLE_ENABLED); // 1. self-create user with membership: goes 'createApproval' with resources and membership but no propagation UserCR userCR = UserITCase.getUniqueSample("anonymous@syncope.apache.org"); userCR.getMemberships().add( new MembershipTO.Builder("29f96485-729e-4d31-88a1-6fc60e4677f3").build()); userCR.getResources().add(RESOURCE_NAME_TESTDB); UserTO userTO = ANONYMOUS_CLIENT.getService(UserSelfService.class). create(userCR). readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(userTO); assertEquals("createApproval", userTO.getStatus()); assertFalse(userTO.getMemberships().isEmpty()); assertFalse(userTO.getResources().isEmpty()); try { RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), userTO.getKey()); fail(); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.NotFound, e.getType()); } // 2. unclaim and verify that propagation has NOT happened UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getKey()).build()).getResult().getFirst(); form = USER_REQUEST_SERVICE.unclaimForm(form.getTaskId()); assertNull(form.getAssignee()); assertNotNull(userTO); assertNotEquals("active", userTO.getStatus()); try { RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), userTO.getKey()); fail(); } catch (Exception e) { assertNotNull(e); } // 3. approve and verify that propagation has happened form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getKey()).build()).getResult().getFirst(); form = USER_REQUEST_SERVICE.claimForm(form.getTaskId()); form.getProperty("approveCreate").get().setValue(Boolean.TRUE.toString()); userTO = USER_REQUEST_SERVICE.submitForm(form).readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(userTO); assertEquals("active", userTO.getStatus()); assertNotNull(RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), userTO.getKey())); } @Test public void read() { UserTO user = createUser(UserITCase.getUniqueSample("selfread@syncope.apache.org")).getEntity(); UserService us2 = CLIENT_FACTORY.create(user.getUsername(), "password123").getService(UserService.class); try { us2.read(user.getKey()); fail("This should not happen"); } catch (ForbiddenException e) { assertNotNull(e); } Triple<Map<String, Set<String>>, List<String>, UserTO> self = CLIENT_FACTORY.create(user.getUsername(), "password123").self(); assertEquals(user.getUsername(), self.getRight().getUsername()); } @Test public void authenticateByPlainAttribute() { UserTO rossini = USER_SERVICE.read("rossini"); assertNotNull(rossini); String userId = rossini.getPlainAttr("userId").get().getValues().getFirst(); assertNotNull(userId); Triple<Map<String, Set<String>>, List<String>, UserTO> self = CLIENT_FACTORY.create(userId, ADMIN_PWD).self(); assertEquals(rossini.getUsername(), self.getRight().getUsername()); } @Test public void updateWithoutApproval() { // 1. create user as admin UserTO created = createUser(UserITCase.getUniqueSample("anonymous@syncope.apache.org")).getEntity(); assertNotNull(created); assertFalse(created.getUsername().endsWith("XX")); // 2. self-update (username) - works UserUR userUR = new UserUR(); userUR.setKey(created.getKey()); userUR.setUsername(new StringReplacePatchItem.Builder().value(created.getUsername() + "XX").build()); SyncopeClient authClient = CLIENT_FACTORY.create(created.getUsername(), "password123"); UserTO updated = authClient.getService(UserSelfService.class).update(userUR). readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(updated); assertEquals(IS_FLOWABLE_ENABLED ? "active" : "created", updated.getStatus()); assertTrue(updated.getUsername().endsWith("XX")); } @Test public void updateWithApproval() { assumeTrue(IS_FLOWABLE_ENABLED); // 1. create user as admin UserTO created = createUser(UserITCase.getUniqueSample("anonymous@syncope.apache.org")).getEntity(); assertNotNull(created); assertFalse(created.getUsername().endsWith("XX")); // 2. self-update (username + memberships + resource) - works but needs approval UserUR userUR = new UserUR(); userUR.setKey(created.getKey()); userUR.setUsername(new StringReplacePatchItem.Builder().value(created.getUsername() + "XX").build()); userUR.getMemberships().add(new MembershipUR.Builder("bf825fe1-7320-4a54-bd64-143b5c18ab97"). operation(PatchOperation.ADD_REPLACE). build()); userUR.getResources().add(new StringPatchItem.Builder(). operation(PatchOperation.ADD_REPLACE).value(RESOURCE_NAME_TESTDB).build()); userUR.setPassword(new PasswordPatch.Builder(). value("newPassword123").onSyncope(false).resource(RESOURCE_NAME_TESTDB).build()); SyncopeClient authClient = CLIENT_FACTORY.create(created.getUsername(), "password123"); UserTO updated = authClient.getService(UserSelfService.class).update(userUR). readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(updated); assertEquals("updateApproval", updated.getStatus()); assertFalse(updated.getUsername().endsWith("XX")); assertTrue(updated.getMemberships().isEmpty()); // no propagation happened assertTrue(updated.getResources().isEmpty()); try { RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), updated.getKey()); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.NotFound, e.getType()); } // 3. approve self-update as admin UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(updated.getKey()).build()).getResult().getFirst(); form = USER_REQUEST_SERVICE.claimForm(form.getTaskId()); form.getProperty("approveUpdate").get().setValue(Boolean.TRUE.toString()); updated = USER_REQUEST_SERVICE.submitForm(form).readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(updated); assertEquals("active", updated.getStatus()); assertTrue(updated.getUsername().endsWith("XX")); assertEquals(1, updated.getMemberships().size()); // check that propagation also happened assertTrue(updated.getResources().contains(RESOURCE_NAME_TESTDB)); assertNotNull(RESOURCE_SERVICE.readConnObject(RESOURCE_NAME_TESTDB, AnyTypeKind.USER.name(), updated.getKey())); } @Test public void delete() { UserTO created = createUser(UserITCase.getUniqueSample("anonymous@syncope.apache.org")).getEntity(); assertNotNull(created); SyncopeClient authClient = CLIENT_FACTORY.create(created.getUsername(), "password123"); UserTO deleted = authClient.getService(UserSelfService.class).delete().readEntity( new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(deleted); assertEquals(IS_FLOWABLE_ENABLED ? "deleteApproval" : null, deleted.getStatus()); } @Test public void passwordReset() throws Exception { // 0. ensure that password request DOES require security question confParamOps.set(SyncopeConstants.MASTER_DOMAIN, "passwordReset.securityQuestion", true); // 1. create an user with security question and answer UserCR user = UserITCase.getUniqueSample("pwdReset@syncope.apache.org"); user.setSecurityQuestion("887028ea-66fc-41e7-b397-620d7ea6dfbb"); user.setSecurityAnswer("Rossi"); user.getResources().add(RESOURCE_NAME_TESTDB); createUser(user); // verify propagation (including password) on external db JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource); String pwdOnResource = queryForObject(jdbcTemplate, MAX_WAIT_SECONDS, "SELECT password FROM test WHERE id=?", String.class, user.getUsername()); assertTrue(StringUtils.isNotBlank(pwdOnResource)); // 2. verify that new user is able to authenticate SyncopeClient authClient = CLIENT_FACTORY.create(user.getUsername(), "password123"); UserTO read = authClient.self().getRight(); assertNotNull(read); // 3. request password reset (as anonymous) providing the expected security answer try { ANONYMOUS_CLIENT.getService(UserSelfService.class).requestPasswordReset(user.getUsername(), "WRONG"); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.InvalidSecurityAnswer, e.getType()); } ANONYMOUS_CLIENT.getService(UserSelfService.class).requestPasswordReset(user.getUsername(), "Rossi"); if (IS_EXT_SEARCH_ENABLED) { try { Thread.sleep(2000); } catch (InterruptedException ex) { // ignore } } // 4. get token (normally sent via e-mail, now reading as admin) String email = user.getPlainAttr("email").orElseThrow().getValues().getFirst(); if (!IS_NEO4J_PERSISTENCE) { checkNotification(email, "e00945b5-1184-4d43-8e45-4318a8dcdfd4", "Password Reset request"); } String token = await().atMost(MAX_WAIT_SECONDS, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until( () -> USER_SERVICE.read(read.getKey()).getToken(), StringUtils::isNotBlank); // 5. confirm password reset try { ANONYMOUS_CLIENT.getService(UserSelfService.class).confirmPasswordReset("WRONG TOKEN", "newPassword"); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.NotFound, e.getType()); assertTrue(e.getMessage().contains("WRONG TOKEN")); } ANONYMOUS_CLIENT.getService(UserSelfService.class).confirmPasswordReset(token, "newPassword123"); if (!IS_NEO4J_PERSISTENCE) { checkNotification(email, "bef0c250-e8a7-4848-bb63-2564fc409ce2", "Password Reset successful"); } // 6. verify that password was reset and token removed authClient = CLIENT_FACTORY.create(user.getUsername(), "newPassword123"); assertNull(authClient.self().getRight().getToken()); // 7. verify that password was changed on external resource String newPwdOnResource = queryForObject(jdbcTemplate, MAX_WAIT_SECONDS, "SELECT password FROM test WHERE id=?", String.class, user.getUsername()); assertTrue(StringUtils.isNotBlank(newPwdOnResource)); assertNotEquals(pwdOnResource, newPwdOnResource); } @Test public void passwordResetWithoutSecurityQuestion() { // 0. disable security question for password reset confParamOps.set(SyncopeConstants.MASTER_DOMAIN, "passwordReset.securityQuestion", false); // 1. create an user with security question and answer UserCR user = UserITCase.getUniqueSample("pwdResetNoSecurityQuestion@syncope.apache.org"); createUser(user); // 2. verify that new user is able to authenticate SyncopeClient authClient = CLIENT_FACTORY.create(user.getUsername(), "password123"); UserTO read = authClient.self().getRight(); assertNotNull(read); // 3. request password reset (as anonymous) with no security answer ANONYMOUS_CLIENT.getService(UserSelfService.class).requestPasswordReset(user.getUsername(), null); // 4. get token (normally sent via e-mail, now reading as admin) String token = USER_SERVICE.read(read.getKey()).getToken(); assertNotNull(token); // 5. confirm password reset try { ANONYMOUS_CLIENT.getService(UserSelfService.class).confirmPasswordReset("WRONG TOKEN", "newPassword"); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.NotFound, e.getType()); assertTrue(e.getMessage().contains("WRONG TOKEN")); } ANONYMOUS_CLIENT.getService(UserSelfService.class).confirmPasswordReset(token, "newPassword123"); // 6. verify that password was reset and token removed authClient = CLIENT_FACTORY.create(user.getUsername(), "newPassword123"); read = authClient.self().getRight(); assertNotNull(read); assertNull(read.getToken()); // 7. re-enable security question for password reset confParamOps.set(SyncopeConstants.MASTER_DOMAIN, "passwordReset.securityQuestion", true); } @Test public void mustChangePassword() { assumeFalse(IS_NEO4J_PERSISTENCE); // PRE: reset vivaldi's password UserUR userUR = new UserUR(); userUR.setKey("b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee"); userUR.setPassword(new PasswordPatch.Builder().value("password321").build()); USER_SERVICE.update(userUR); // 0. access as vivaldi -> succeed SyncopeClient vivaldiClient = CLIENT_FACTORY.create("vivaldi", "password321"); Response response = vivaldiClient.getService(AccessTokenService.class).refresh(); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); // 1. update user vivaldi requiring password update userUR = new UserUR(); userUR.setKey("b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee"); userUR.setMustChangePassword(new BooleanReplacePatchItem.Builder().value(true).build()); UserTO vivaldi = updateUser(userUR).getEntity(); assertTrue(vivaldi.isMustChangePassword()); // 2. attempt to access -> fail try { vivaldiClient.self(); fail("This should not happen"); } catch (ForbiddenException e) { assertNotNull(e); assertEquals("Please change your password first", e.getMessage()); } // 3. change password vivaldiClient.getService(UserSelfService.class). mustChangePassword(new PasswordPatch.Builder().value("password123").build()); // 4. verify it worked Triple<Map<String, Set<String>>, List<String>, UserTO> self = CLIENT_FACTORY.create("vivaldi", "password123").self(); assertFalse(self.getRight().isMustChangePassword()); } @Test public void createWithReject() { assumeTrue(IS_FLOWABLE_ENABLED); UserCR userCR = UserITCase.getUniqueSample("createWithReject@syncope.apache.org"); userCR.getResources().add(RESOURCE_NAME_TESTDB); // User with group 0cbcabd2-4410-4b6b-8f05-a052b451d18f are defined in workflow as subject to approval userCR.getMemberships().add(new MembershipTO.Builder("0cbcabd2-4410-4b6b-8f05-a052b451d18f").build()); // 1. create user with group 0cbcabd2-4410-4b6b-8f05-a052b451d18f UserTO userTO = createUser(userCR).getEntity(); assertNotNull(userTO); assertEquals(1, userTO.getMemberships().size()); assertEquals("0cbcabd2-4410-4b6b-8f05-a052b451d18f", userTO.getMemberships().getFirst().getGroupKey()); assertEquals("createApproval", userTO.getStatus()); // 2. request if there is any pending task for user just created UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getKey()).build()).getResult().getFirst(); assertNotNull(form); assertNotNull(form.getUsername()); assertEquals(userTO.getUsername(), form.getUsername()); assertNotNull(form.getTaskId()); assertNull(form.getAssignee()); // 3. claim task as rossini, with role "User manager" granting entitlement to claim forms but not in // groupForWorkflowApproval, designated for approval in workflow definition: fail UserTO rossini = USER_SERVICE.read("1417acbe-cbf6-4277-9372-e75e04f97000"); if (!rossini.getRoles().contains("User manager")) { UserUR userUR = new UserUR(); userUR.setKey("1417acbe-cbf6-4277-9372-e75e04f97000"); userUR.getRoles().add(new StringPatchItem.Builder(). operation(PatchOperation.ADD_REPLACE).value("User manager").build()); rossini = updateUser(userUR).getEntity(); } assertTrue(rossini.getRoles().contains("User manager")); UserRequestService userService2 = CLIENT_FACTORY.create("rossini", ADMIN_PWD). getService(UserRequestService.class); try { userService2.claimForm(form.getTaskId()); fail("This should not happen"); } catch (SyncopeClientException e) { assertEquals(ClientExceptionType.Workflow, e.getType()); } // 4. claim task from bellini, with role "User manager" and in groupForWorkflowApproval UserRequestService userService3 = CLIENT_FACTORY.create("bellini", ADMIN_PWD). getService(UserRequestService.class); assertEquals(1, userService3.listForms( new UserRequestQuery.Builder().user(userTO.getKey()).build()).getTotalCount()); form = userService3.claimForm(form.getTaskId()); assertNotNull(form); assertNotNull(form.getTaskId()); assertNotNull(form.getAssignee()); // 5. reject user form.getProperty("approveCreate").get().setValue(Boolean.FALSE.toString()); form.getProperty("rejectReason").get().setValue("I don't like him."); userTO = userService3.submitForm(form).readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(userTO); assertEquals("rejected", userTO.getStatus()); // 6. check that rejected user was not propagated to external resource (SYNCOPE-364) JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource); Exception exception = null; try { jdbcTemplate.queryForObject("SELECT id FROM test WHERE id=?", Integer.class, userTO.getUsername()); } catch (EmptyResultDataAccessException e) { exception = e; } assertNotNull(exception); } @Test public void createWithApproval() { assumeTrue(IS_FLOWABLE_ENABLED); // read forms *before* any operation PagedResult<UserRequestForm> forms = USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()); long preForms = forms.getTotalCount(); UserCR userCR = UserITCase.getUniqueSample("createWithApproval@syncope.apache.org"); userCR.getResources().add(RESOURCE_NAME_TESTDB); // User with group 0cbcabd2-4410-4b6b-8f05-a052b451d18f are defined in workflow as subject to approval userCR.getMemberships().add( new MembershipTO.Builder("0cbcabd2-4410-4b6b-8f05-a052b451d18f").build()); // 1. create user and verify that no propagation occurred) ProvisioningResult<UserTO> result = createUser(userCR); assertNotNull(result); UserTO userTO = result.getEntity(); assertEquals(1, userTO.getMemberships().size()); assertEquals("0cbcabd2-4410-4b6b-8f05-a052b451d18f", userTO.getMemberships().getFirst().getGroupKey()); assertEquals("createApproval", userTO.getStatus()); assertEquals(Set.of(RESOURCE_NAME_TESTDB), userTO.getResources()); assertTrue(result.getPropagationStatuses().isEmpty()); JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource); Exception exception = null; try { jdbcTemplate.queryForObject("SELECT id FROM test WHERE id=?", Integer.class, userTO.getUsername()); } catch (EmptyResultDataAccessException e) { exception = e; } assertNotNull(exception); // 2. request if there is any pending form for user just created forms = USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()); assertEquals(preForms + 1, forms.getTotalCount()); // 3. as admin, update user: still pending approval String updatedUsername = "changed-" + UUID.randomUUID(); UserUR userUR = new UserUR(); userUR.setKey(userTO.getKey()); userUR.setUsername(new StringReplacePatchItem.Builder().value(updatedUsername).build()); updateUser(userUR); UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getKey()).build()).getResult().getFirst(); assertNotNull(form); assertNotNull(form.getTaskId()); assertNotNull(form.getUserTO()); assertEquals(updatedUsername, form.getUserTO().getUsername()); assertNull(form.getUserUR()); assertNull(form.getAssignee()); // 4. claim task (as admin) form = USER_REQUEST_SERVICE.claimForm(form.getTaskId()); assertNotNull(form); assertNotNull(form.getTaskId()); assertNotNull(form.getUserTO()); assertEquals(updatedUsername, form.getUserTO().getUsername()); assertNull(form.getUserUR()); assertNotNull(form.getAssignee()); // 5. approve user (and verify that propagation occurred) form.getProperty("approveCreate").get().setValue(Boolean.TRUE.toString()); userTO = USER_REQUEST_SERVICE.submitForm(form).readEntity(new GenericType<ProvisioningResult<UserTO>>() { }).getEntity(); assertNotNull(userTO); assertEquals(updatedUsername, userTO.getUsername()); assertEquals("active", userTO.getStatus()); assertEquals(Set.of(RESOURCE_NAME_TESTDB), userTO.getResources()); String username = queryForObject(jdbcTemplate, MAX_WAIT_SECONDS, "SELECT id FROM test WHERE id=?", String.class, userTO.getUsername()); assertEquals(userTO.getUsername(), username); // 6. update user userUR = new UserUR(); userUR.setKey(userTO.getKey()); userUR.setPassword(new PasswordPatch.Builder().value("anotherPassword123").build()); userTO = updateUser(userUR).getEntity(); assertNotNull(userTO); } @Test public void updateApproval() { assumeTrue(IS_FLOWABLE_ENABLED); // read forms *before* any operation PagedResult<UserRequestForm> forms = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().build()); long preForms = forms.getTotalCount(); UserTO created = createUser(UserITCase.getUniqueSample("updateApproval@syncope.apache.org")).getEntity(); assertNotNull(created); assertEquals("/", created.getRealm()); assertEquals(0, created.getMemberships().size()); UserUR req = new UserUR(); req.setKey(created.getKey()); req.getMemberships().add(new MembershipUR.Builder("b1f7c12d-ec83-441f-a50e-1691daaedf3b").build()); SyncopeClient client = CLIENT_FACTORY.create(created.getUsername(), "password123"); Response response = client.getService(UserSelfService.class).update(req); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("updateApproval", USER_SERVICE.read(created.getKey()).getStatus()); forms = USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()); assertEquals(preForms + 1, forms.getTotalCount()); UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(created.getKey()).build()).getResult().getFirst(); assertNotNull(form); assertNotNull(form.getTaskId()); assertNull(form.getAssignee()); assertNotNull(form.getUserTO()); assertNotNull(form.getUserUR()); assertEquals(req, form.getUserUR()); // as admin, update user: still pending approval UserUR adminPatch = new UserUR(); adminPatch.setKey(created.getKey()); adminPatch.setRealm(new StringReplacePatchItem.Builder().value("/even/two").build()); UserTO updated = updateUser(adminPatch).getEntity(); assertEquals("updateApproval", updated.getStatus()); assertEquals("/even/two", updated.getRealm()); assertEquals(0, updated.getMemberships().size()); // the patch is not updated in the approval form form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(created.getKey()).build()).getResult().getFirst(); assertEquals(req, form.getUserUR()); // approve the user form = USER_REQUEST_SERVICE.claimForm(form.getTaskId()); form.getProperty("approveUpdate").get().setValue(Boolean.TRUE.toString()); USER_REQUEST_SERVICE.submitForm(form); // verify that the approved user bears both original and further changes UserTO approved = USER_SERVICE.read(created.getKey()); assertEquals("active", approved.getStatus()); assertEquals("/even/two", approved.getRealm()); assertEquals(1, approved.getMemberships().size()); assertTrue(approved.getMembership("b1f7c12d-ec83-441f-a50e-1691daaedf3b").isPresent()); } @Test public void availableTasks() { assumeTrue(IS_FLOWABLE_ENABLED); UserTO user = createUser(UserITCase.getUniqueSample("availableTasks@apache.org")).getEntity(); assertEquals("active", user.getStatus()); List<WorkflowTask> tasks = USER_WORKFLOW_TASK_SERVICE.getAvailableTasks(user.getKey()); assertNotNull(tasks); assertTrue(tasks.stream().anyMatch(task -> "update".equals(task.getName()))); assertTrue(tasks.stream().anyMatch(task -> "suspend".equals(task.getName()))); assertTrue(tasks.stream().anyMatch(task -> "delete".equals(task.getName()))); } @Test public void issueSYNCOPE15() { assumeTrue(IS_FLOWABLE_ENABLED); // read forms *before* any operation PagedResult<UserRequestForm> forms = USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()); long preForms = forms.getTotalCount(); UserCR userCR = UserITCase.getUniqueSample("issueSYNCOPE15@syncope.apache.org"); userCR.getResources().clear(); userCR.getMemberships().clear(); // Users with group 0cbcabd2-4410-4b6b-8f05-a052b451d18f are defined in workflow as subject to approval userCR.getMemberships().add(new MembershipTO.Builder("0cbcabd2-4410-4b6b-8f05-a052b451d18f").build()); // 1. create user with group 0cbcabd2-4410-4b6b-8f05-a052b451d18f (and verify that no propagation occurred) ProvisioningResult<UserTO> userTO = createUser(userCR); assertTrue(userTO.getPropagationStatuses().isEmpty()); // 2. request if there is any pending form for user just created forms = USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()); assertEquals(preForms + 1, forms.getTotalCount()); UserRequestForm form = USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getEntity().getKey()).build()).getResult().getFirst(); assertNotNull(form); // 3. first claim by bellini .... UserRequestService userService3 = CLIENT_FACTORY.create("bellini", ADMIN_PWD). getService(UserRequestService.class); form = userService3.claimForm(form.getTaskId()); assertNotNull(form); assertNotNull(form.getTaskId()); assertNotNull(form.getAssignee()); // 4. second claim task by admin form = USER_REQUEST_SERVICE.claimForm(form.getTaskId()); assertNotNull(form); // 5. approve user form.getProperty("approveCreate").get().setValue(Boolean.TRUE.toString()); // 6. submit approve USER_REQUEST_SERVICE.submitForm(form); assertEquals(preForms, USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()).getTotalCount()); assertTrue(USER_REQUEST_SERVICE.listForms( new UserRequestQuery.Builder().user(userTO.getEntity().getKey()).build()).getResult().isEmpty()); // 7.check that no more forms are still to be processed forms = USER_REQUEST_SERVICE.listForms(new UserRequestQuery.Builder().build()); assertEquals(preForms, forms.getTotalCount()); } @Test public void issueSYNCOPE373() { UserTO userTO = ADMIN_CLIENT.self().getRight(); assertEquals(ADMIN_UNAME, userTO.getUsername()); } }
googleapis/google-cloud-java
36,908
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/QuestionAnsweringRelevanceInput.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> * Input for question answering relevance metric. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput} */ public final class QuestionAnsweringRelevanceInput extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput) QuestionAnsweringRelevanceInputOrBuilder { private static final long serialVersionUID = 0L; // Use QuestionAnsweringRelevanceInput.newBuilder() to construct. private QuestionAnsweringRelevanceInput( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private QuestionAnsweringRelevanceInput() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new QuestionAnsweringRelevanceInput(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringRelevanceInput_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringRelevanceInput_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput.class, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput.Builder.class); } private int bitField0_; public static final int METRIC_SPEC_FIELD_NUMBER = 1; private com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metricSpec_; /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec 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 question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The metricSpec. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec getMetricSpec() { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.getDefaultInstance() : metricSpec_; } /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpecOrBuilder getMetricSpecOrBuilder() { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.getDefaultInstance() : metricSpec_; } public static final int INSTANCE_FIELD_NUMBER = 2; private com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance_; /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance 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. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The instance. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance getInstance() { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance .getDefaultInstance() : instance_; } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstanceOrBuilder getInstanceOrBuilder() { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance .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.QuestionAnsweringRelevanceInput)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput other = (com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput) 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.QuestionAnsweringRelevanceInput parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Input for question answering relevance metric. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput) com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInputOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringRelevanceInput_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringRelevanceInput_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput.class, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput.Builder.class); } // Construct using // com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput.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_QuestionAnsweringRelevanceInput_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput .getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput build() { com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput buildPartial() { com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput result = new com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput 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.QuestionAnsweringRelevanceInput) { return mergeFrom( (com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput other) { if (other == com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput .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.QuestionAnsweringRelevanceSpec metricSpec_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.Builder, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpecOrBuilder> metricSpecBuilder_; /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec 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 question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The metricSpec. */ public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec getMetricSpec() { if (metricSpecBuilder_ == null) { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec .getDefaultInstance() : metricSpec_; } else { return metricSpecBuilder_.getMessage(); } } /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setMetricSpec( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec 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 question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setMetricSpec( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.Builder builderForValue) { if (metricSpecBuilder_ == null) { metricSpec_ = builderForValue.build(); } else { metricSpecBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeMetricSpec( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec value) { if (metricSpecBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && metricSpec_ != null && metricSpec_ != com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec .getDefaultInstance()) { getMetricSpecBuilder().mergeFrom(value); } else { metricSpec_ = value; } } else { metricSpecBuilder_.mergeFrom(value); } if (metricSpec_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec 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 question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.Builder getMetricSpecBuilder() { bitField0_ |= 0x00000001; onChanged(); return getMetricSpecFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpecOrBuilder getMetricSpecOrBuilder() { if (metricSpecBuilder_ != null) { return metricSpecBuilder_.getMessageOrBuilder(); } else { return metricSpec_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec .getDefaultInstance() : metricSpec_; } } /** * * * <pre> * Required. Spec for question answering relevance score metric. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.Builder, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpecOrBuilder> getMetricSpecFieldBuilder() { if (metricSpecBuilder_ == null) { metricSpecBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpec.Builder, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceSpecOrBuilder>( getMetricSpec(), getParentForChildren(), isClean()); metricSpec_ = null; } return metricSpecBuilder_; } private com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance.Builder, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstanceOrBuilder> instanceBuilder_; /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the instance field is set. */ public boolean hasInstance() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The instance. */ public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance getInstance() { if (instanceBuilder_ == null) { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance .getDefaultInstance() : instance_; } else { return instanceBuilder_.getMessage(); } } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setInstance( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance value) { if (instanceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } instance_ = value; } else { instanceBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setInstance( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance.Builder builderForValue) { if (instanceBuilder_ == null) { instance_ = builderForValue.build(); } else { instanceBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeInstance( com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance value) { if (instanceBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && instance_ != null && instance_ != com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance .getDefaultInstance()) { getInstanceBuilder().mergeFrom(value); } else { instance_ = value; } } else { instanceBuilder_.mergeFrom(value); } if (instance_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance 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. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance.Builder getInstanceBuilder() { bitField0_ |= 0x00000002; onChanged(); return getInstanceFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstanceOrBuilder getInstanceOrBuilder() { if (instanceBuilder_ != null) { return instanceBuilder_.getMessageOrBuilder(); } else { return instance_ == null ? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance .getDefaultInstance() : instance_; } } /** * * * <pre> * Required. Question answering relevance instance. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance instance = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance.Builder, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstanceOrBuilder> getInstanceFieldBuilder() { if (instanceBuilder_ == null) { instanceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstance.Builder, com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInstanceOrBuilder>( 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.QuestionAnsweringRelevanceInput) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput) private static final com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput(); } public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<QuestionAnsweringRelevanceInput> PARSER = new com.google.protobuf.AbstractParser<QuestionAnsweringRelevanceInput>() { @java.lang.Override public QuestionAnsweringRelevanceInput 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<QuestionAnsweringRelevanceInput> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<QuestionAnsweringRelevanceInput> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringRelevanceInput getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/pulsar
37,195
tiered-storage/jcloud/src/main/java/org/apache/bookkeeper/mledger/offload/jcloud/impl/BlobStoreManagedLedgerOffloader.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.bookkeeper.mledger.offload.jcloud.impl; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.client.api.ReadHandle; import org.apache.bookkeeper.common.util.OrderedScheduler; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.LedgerOffloader; import org.apache.bookkeeper.mledger.LedgerOffloader.OffloadHandle.OfferEntryResult; import org.apache.bookkeeper.mledger.LedgerOffloaderStats; import org.apache.bookkeeper.mledger.ManagedLedger; import org.apache.bookkeeper.mledger.ManagedLedgerException; import org.apache.bookkeeper.mledger.OffloadedLedgerMetadata; import org.apache.bookkeeper.mledger.OffloadedLedgerMetadataConsumer; import org.apache.bookkeeper.mledger.Position; import org.apache.bookkeeper.mledger.PositionFactory; import org.apache.bookkeeper.mledger.impl.EntryImpl; import org.apache.bookkeeper.mledger.impl.OffloadSegmentInfoImpl; import org.apache.bookkeeper.mledger.offload.jcloud.BlockAwareSegmentInputStream; import org.apache.bookkeeper.mledger.offload.jcloud.OffloadIndexBlock; import org.apache.bookkeeper.mledger.offload.jcloud.OffloadIndexBlock.IndexInputStream; import org.apache.bookkeeper.mledger.offload.jcloud.OffloadIndexBlockBuilder; import org.apache.bookkeeper.mledger.offload.jcloud.OffloadIndexBlockV2; import org.apache.bookkeeper.mledger.offload.jcloud.OffloadIndexBlockV2Builder; import org.apache.bookkeeper.mledger.offload.jcloud.provider.BlobStoreLocation; import org.apache.bookkeeper.mledger.offload.jcloud.provider.TieredStorageConfiguration; import org.apache.bookkeeper.mledger.proto.MLDataFormats; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.OffloadPolicies; import org.apache.pulsar.common.policies.data.OffloadPoliciesImpl; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobBuilder; import org.jclouds.blobstore.domain.MultipartPart; import org.jclouds.blobstore.domain.MultipartUpload; import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.options.PutOptions; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; import org.jclouds.io.payloads.InputStreamPayload; /** * Tiered Storage Offloader that is backed by a JCloud Blob Store. * <p> * The constructor takes an instance of TieredStorageConfiguration, which * contains all of the configuration data necessary to connect to a JCloud * Provider service. * </p> */ @Slf4j public class BlobStoreManagedLedgerOffloader implements LedgerOffloader { private static final String MANAGED_LEDGER_NAME = "ManagedLedgerName"; private final OrderedScheduler scheduler; private final OrderedScheduler readExecutor; private final TieredStorageConfiguration config; private final OffloadPolicies policies; private final Location writeLocation; // metadata to be stored as part of the offloaded ledger metadata private final Map<String, String> userMetadata; private final ConcurrentMap<BlobStoreLocation, BlobStore> blobStores = new ConcurrentHashMap<>(); private OffloadSegmentInfoImpl segmentInfo; private final AtomicLong bufferLength = new AtomicLong(0); private final AtomicLong segmentLength = new AtomicLong(0); private final long maxBufferLength; private final OffsetsCache entryOffsetsCache; private final ConcurrentLinkedQueue<Entry> offloadBuffer = new ConcurrentLinkedQueue<>(); private CompletableFuture<OffloadResult> offloadResult; private volatile Position lastOfferedPosition = PositionFactory.LATEST; private final Duration maxSegmentCloseTime; private final long minSegmentCloseTimeMillis; private final long segmentBeginTimeMillis; private final long maxSegmentLength; private final int streamingBlockSize; private volatile ManagedLedger ml; private OffloadIndexBlockV2Builder streamingIndexBuilder; private final LedgerOffloaderStats offloaderStats; public static BlobStoreManagedLedgerOffloader create(TieredStorageConfiguration config, Map<String, String> userMetadata, OrderedScheduler scheduler, OrderedScheduler readExecutor, LedgerOffloaderStats offloaderStats, OffsetsCache entryOffsetsCache) throws IOException { return new BlobStoreManagedLedgerOffloader(config, scheduler, readExecutor, userMetadata, offloaderStats, entryOffsetsCache); } BlobStoreManagedLedgerOffloader(TieredStorageConfiguration config, OrderedScheduler scheduler, OrderedScheduler readExecutor, Map<String, String> userMetadata, LedgerOffloaderStats offloaderStats, OffsetsCache entryOffsetsCache) { this.scheduler = scheduler; this.readExecutor = readExecutor; this.userMetadata = userMetadata; this.config = config; Properties properties = new Properties(); properties.putAll(config.getConfigProperties()); this.policies = OffloadPoliciesImpl.create(properties); this.streamingBlockSize = config.getMinBlockSizeInBytes(); this.maxSegmentCloseTime = Duration.ofSeconds(config.getMaxSegmentTimeInSecond()); this.maxSegmentLength = config.getMaxSegmentSizeInBytes(); this.minSegmentCloseTimeMillis = Duration.ofSeconds(config.getMinSegmentTimeInSecond()).toMillis(); //ensure buffer can have enough content to fill a block this.maxBufferLength = Math.max(config.getWriteBufferSizeInBytes(), config.getMinBlockSizeInBytes()); this.entryOffsetsCache = entryOffsetsCache; this.segmentBeginTimeMillis = System.currentTimeMillis(); if (!Strings.isNullOrEmpty(config.getRegion())) { this.writeLocation = new LocationBuilder() .scope(LocationScope.REGION) .id(config.getRegion()) .description(config.getRegion()) .build(); } else { this.writeLocation = null; } log.info("Constructor offload driver: {}, host: {}, container: {}, region: {} ", config.getProvider().getDriver(), config.getServiceEndpoint(), config.getBucket(), config.getRegion()); this.offloaderStats = offloaderStats; log.info("The ledger offloader was created."); } private BlobStore getBlobStore(BlobStoreLocation blobStoreLocation) { return blobStores.computeIfAbsent(blobStoreLocation, location -> { log.info("Creating blob store for location {}", location); return config.getBlobStore(); }); } @Override public String getOffloadDriverName() { return config.getDriver(); } @Override public Map<String, String> getOffloadDriverMetadata() { return config.getOffloadDriverMetadata(); } /** * Upload the DataBlocks associated with the given ReadHandle using MultiPartUpload, * Creating indexBlocks for each corresponding DataBlock that is uploaded. */ @Override public CompletableFuture<Void> offload(ReadHandle readHandle, UUID uuid, Map<String, String> extraMetadata) { final String managedLedgerName = extraMetadata.get(MANAGED_LEDGER_NAME); final String topicName = TopicName.fromPersistenceNamingEncoding(managedLedgerName); CompletableFuture<Void> promise = new CompletableFuture<>(); scheduler.chooseThread(readHandle.getId()).execute(() -> { final BlobStore writeBlobStore = getBlobStore(config.getBlobStoreLocation()); log.info("offload {} uuid {} extraMetadata {} to {} {}", readHandle.getId(), uuid, extraMetadata, config.getBlobStoreLocation(), writeBlobStore); if (!readHandle.isClosed() || readHandle.getLastAddConfirmed() < 0) { promise.completeExceptionally( new IllegalArgumentException("An empty or open ledger should never be offloaded")); return; } if (readHandle.getLength() <= 0) { log.warn("[{}] Ledger [{}] has zero length, but it contains {} entries." + " Attempting to offload ledger since it contains entries.", topicName, readHandle.getId(), readHandle.getLastAddConfirmed() + 1); } OffloadIndexBlockBuilder indexBuilder = OffloadIndexBlockBuilder.create() .withLedgerMetadata(readHandle.getLedgerMetadata()) .withDataBlockHeaderLength(BlockAwareSegmentInputStreamImpl.getHeaderSize()); String dataBlockKey = DataBlockUtils.dataBlockOffloadKey(readHandle.getId(), uuid); String indexBlockKey = DataBlockUtils.indexBlockOffloadKey(readHandle.getId(), uuid); log.info("ledger {} dataBlockKey {} indexBlockKey {}", readHandle.getId(), dataBlockKey, indexBlockKey); MultipartUpload mpu = null; List<MultipartPart> parts = Lists.newArrayList(); // init multi part upload for data block. try { BlobBuilder blobBuilder = writeBlobStore.blobBuilder(dataBlockKey); Map<String, String> objectMetadata = new HashMap<>(userMetadata); objectMetadata.put("role", "data"); if (extraMetadata != null) { objectMetadata.putAll(extraMetadata); } DataBlockUtils.addVersionInfo(blobBuilder, objectMetadata); Blob blob = blobBuilder.build(); log.info("initiateMultipartUpload bucket {}, metadata {} ", config.getBucket(), blob.getMetadata()); mpu = writeBlobStore.initiateMultipartUpload(config.getBucket(), blob.getMetadata(), new PutOptions()); } catch (Throwable t) { promise.completeExceptionally(t); return; } long dataObjectLength = 0; // start multi part upload for data block. try { long startEntry = 0; int partId = 1; long start = System.nanoTime(); long entryBytesWritten = 0; while (startEntry <= readHandle.getLastAddConfirmed()) { int blockSize = BlockAwareSegmentInputStreamImpl .calculateBlockSize(config.getMaxBlockSizeInBytes(), readHandle, startEntry, entryBytesWritten); try (BlockAwareSegmentInputStream blockStream = new BlockAwareSegmentInputStreamImpl( readHandle, startEntry, blockSize, this.offloaderStats, managedLedgerName)) { Payload partPayload = Payloads.newInputStreamPayload(blockStream); partPayload.getContentMetadata().setContentLength((long) blockSize); partPayload.getContentMetadata().setContentType("application/octet-stream"); parts.add(writeBlobStore.uploadMultipartPart(mpu, partId, partPayload)); log.debug("UploadMultipartPart. container: {}, blobName: {}, partId: {}, mpu: {}", config.getBucket(), dataBlockKey, partId, mpu.id()); indexBuilder.addBlock(startEntry, partId, blockSize); if (blockStream.getEndEntryId() != -1) { startEntry = blockStream.getEndEntryId() + 1; } else { // could not read entry from ledger. break; } entryBytesWritten += blockStream.getBlockEntryBytesCount(); partId++; this.offloaderStats.recordOffloadBytes(topicName, blockStream.getBlockEntryBytesCount()); } dataObjectLength += blockSize; } String etag = writeBlobStore.completeMultipartUpload(mpu, parts); log.info("Ledger {}, upload finished, etag {}", readHandle.getId(), etag); mpu = null; } catch (Throwable t) { try { if (mpu != null) { writeBlobStore.abortMultipartUpload(mpu); } } catch (Throwable throwable) { log.error("Failed abortMultipartUpload in bucket - {} with key - {}, uploadId - {}.", config.getBucket(), dataBlockKey, mpu.id(), throwable); } this.offloaderStats.recordWriteToStorageError(topicName); this.offloaderStats.recordOffloadError(topicName); promise.completeExceptionally(t); return; } // upload index block try (OffloadIndexBlock index = indexBuilder.withDataObjectLength(dataObjectLength).build(); IndexInputStream indexStream = index.toStream()) { // write the index block BlobBuilder blobBuilder = writeBlobStore.blobBuilder(indexBlockKey); Map<String, String> objectMetadata = new HashMap<>(userMetadata); objectMetadata.put("role", "index"); if (extraMetadata != null) { objectMetadata.putAll(extraMetadata); } DataBlockUtils.addVersionInfo(blobBuilder, objectMetadata); Payload indexPayload = Payloads.newInputStreamPayload(indexStream); indexPayload.getContentMetadata().setContentLength((long) indexStream.getStreamSize()); indexPayload.getContentMetadata().setContentType("application/octet-stream"); Blob blob = blobBuilder .payload(indexPayload) .contentLength((long) indexStream.getStreamSize()) .build(); writeBlobStore.putBlob(config.getBucket(), blob); promise.complete(null); } catch (Throwable t) { try { writeBlobStore.removeBlob(config.getBucket(), dataBlockKey); } catch (Throwable throwable) { log.error("Failed deleteObject in bucket - {} with key - {}.", config.getBucket(), dataBlockKey, throwable); } this.offloaderStats.recordWriteToStorageError(topicName); this.offloaderStats.recordOffloadError(topicName); promise.completeExceptionally(t); return; } }); return promise; } BlobStore blobStore; String streamingDataBlockKey; String streamingDataIndexKey; MultipartUpload streamingMpu = null; List<MultipartPart> streamingParts = Lists.newArrayList(); @Override public CompletableFuture<OffloadHandle> streamingOffload(@NonNull ManagedLedger ml, UUID uuid, long beginLedger, long beginEntry, Map<String, String> driverMetadata) { if (this.ml != null) { log.error("streamingOffload should only be called once"); final CompletableFuture<OffloadHandle> result = new CompletableFuture<>(); result.completeExceptionally(new RuntimeException("streamingOffload should only be called once")); } this.ml = ml; this.segmentInfo = new OffloadSegmentInfoImpl(uuid, beginLedger, beginEntry, config.getDriver(), driverMetadata); log.debug("begin offload with {}:{}", beginLedger, beginEntry); this.offloadResult = new CompletableFuture<>(); blobStore = getBlobStore(config.getBlobStoreLocation()); streamingIndexBuilder = OffloadIndexBlockV2Builder.create(); streamingDataBlockKey = segmentInfo.uuid.toString(); streamingDataIndexKey = String.format("%s-index", segmentInfo.uuid); BlobBuilder blobBuilder = blobStore.blobBuilder(streamingDataBlockKey); DataBlockUtils.addVersionInfo(blobBuilder, userMetadata); Blob blob = blobBuilder.build(); streamingMpu = blobStore .initiateMultipartUpload(config.getBucket(), blob.getMetadata(), new PutOptions()); scheduler.chooseThread(segmentInfo).execute(() -> { log.info("start offloading segment: {}", segmentInfo); streamingOffloadLoop(1, 0); }); scheduler.schedule(this::closeSegment, maxSegmentCloseTime.toMillis(), TimeUnit.MILLISECONDS); return CompletableFuture.completedFuture(new OffloadHandle() { @Override public Position lastOffered() { return BlobStoreManagedLedgerOffloader.this.lastOffered(); } @Override public CompletableFuture<Position> lastOfferedAsync() { return CompletableFuture.completedFuture(lastOffered()); } @Override public OfferEntryResult offerEntry(Entry entry) { return BlobStoreManagedLedgerOffloader.this.offerEntry(entry); } @Override public CompletableFuture<OfferEntryResult> offerEntryAsync(Entry entry) { return CompletableFuture.completedFuture(offerEntry(entry)); } @Override public CompletableFuture<OffloadResult> getOffloadResultAsync() { return BlobStoreManagedLedgerOffloader.this.getOffloadResultAsync(); } @Override public boolean close() { return BlobStoreManagedLedgerOffloader.this.closeSegment(); } }); } private void streamingOffloadLoop(int partId, int dataObjectLength) { log.debug("streaming offload loop {} {}", partId, dataObjectLength); if (segmentInfo.isClosed() && offloadBuffer.isEmpty()) { buildIndexAndCompleteResult(dataObjectLength); offloadResult.complete(segmentInfo.result()); } else if ((segmentInfo.isClosed() && !offloadBuffer.isEmpty()) // last time to build and upload block || bufferLength.get() >= streamingBlockSize // buffer size full, build and upload block ) { List<Entry> entries = new LinkedList<>(); int blockEntrySize = 0; final Entry firstEntry = offloadBuffer.poll(); entries.add(firstEntry); long blockLedgerId = firstEntry.getLedgerId(); long blockEntryId = firstEntry.getEntryId(); while (!offloadBuffer.isEmpty() && offloadBuffer.peek().getLedgerId() == blockLedgerId && blockEntrySize <= streamingBlockSize) { final Entry entryInBlock = offloadBuffer.poll(); final int entrySize = entryInBlock.getLength(); bufferLength.addAndGet(-entrySize); blockEntrySize += entrySize; entries.add(entryInBlock); } final int blockSize = BufferedOffloadStream .calculateBlockSize(streamingBlockSize, entries.size(), blockEntrySize); buildBlockAndUpload(blockSize, entries, blockLedgerId, blockEntryId, partId); streamingOffloadLoop(partId + 1, dataObjectLength + blockSize); } else { log.debug("not enough data, delay schedule for part: {} length: {}", partId, dataObjectLength); scheduler.chooseThread(segmentInfo) .schedule(() -> { streamingOffloadLoop(partId, dataObjectLength); }, 100, TimeUnit.MILLISECONDS); } } private void buildBlockAndUpload(int blockSize, List<Entry> entries, long blockLedgerId, long beginEntryId, int partId) { try (final BufferedOffloadStream payloadStream = new BufferedOffloadStream(blockSize, entries, blockLedgerId, beginEntryId)) { log.debug("begin upload payload: {} {}", blockLedgerId, beginEntryId); Payload partPayload = Payloads.newInputStreamPayload(payloadStream); partPayload.getContentMetadata().setContentType("application/octet-stream"); streamingParts.add(blobStore.uploadMultipartPart(streamingMpu, partId, partPayload)); streamingIndexBuilder.withDataBlockHeaderLength(StreamingDataBlockHeaderImpl.getDataStartOffset()); streamingIndexBuilder.addBlock(blockLedgerId, beginEntryId, partId, blockSize); final MLDataFormats.ManagedLedgerInfo.LedgerInfo ledgerInfo = ml.getLedgerInfo(blockLedgerId).get(); final MLDataFormats.ManagedLedgerInfo.LedgerInfo.Builder ledgerInfoBuilder = MLDataFormats.ManagedLedgerInfo.LedgerInfo.newBuilder(); if (ledgerInfo != null) { ledgerInfoBuilder.mergeFrom(ledgerInfo); } if (ledgerInfoBuilder.getEntries() == 0) { //ledger unclosed, use last entry id of the block ledgerInfoBuilder.setEntries(payloadStream.getEndEntryId() + 1); } streamingIndexBuilder.addLedgerMeta(blockLedgerId, ledgerInfoBuilder.build()); log.debug("UploadMultipartPart. container: {}, blobName: {}, partId: {}, mpu: {}", config.getBucket(), streamingDataBlockKey, partId, streamingMpu.id()); } catch (Throwable e) { blobStore.abortMultipartUpload(streamingMpu); offloadResult.completeExceptionally(e); return; } } private void buildIndexAndCompleteResult(long dataObjectLength) { try { blobStore.completeMultipartUpload(streamingMpu, streamingParts); streamingIndexBuilder.withDataObjectLength(dataObjectLength); final OffloadIndexBlockV2 index = streamingIndexBuilder.buildV2(); final IndexInputStream indexStream = index.toStream(); final BlobBuilder indexBlobBuilder = blobStore.blobBuilder(streamingDataIndexKey); streamingIndexBuilder.withDataBlockHeaderLength(StreamingDataBlockHeaderImpl.getDataStartOffset()); DataBlockUtils.addVersionInfo(indexBlobBuilder, userMetadata); try (final InputStreamPayload indexPayLoad = Payloads.newInputStreamPayload(indexStream)) { indexPayLoad.getContentMetadata().setContentLength(indexStream.getStreamSize()); indexPayLoad.getContentMetadata().setContentType("application/octet-stream"); final Blob indexBlob = indexBlobBuilder.payload(indexPayLoad) .contentLength(indexStream.getStreamSize()) .build(); blobStore.putBlob(config.getBucket(), indexBlob); final OffloadResult result = segmentInfo.result(); offloadResult.complete(result); log.debug("offload segment completed {}", result); } catch (Exception e) { log.error("streaming offload failed", e); offloadResult.completeExceptionally(e); } } catch (Exception e) { log.error("streaming offload failed", e); offloadResult.completeExceptionally(e); } } private CompletableFuture<OffloadResult> getOffloadResultAsync() { return this.offloadResult; } private synchronized OfferEntryResult offerEntry(Entry entry) { if (segmentInfo.isClosed()) { log.debug("Segment already closed {}", segmentInfo); return OfferEntryResult.FAIL_SEGMENT_CLOSED; } else if (maxBufferLength <= bufferLength.get()) { //buffer length can over fill maxBufferLength a bit with the last entry //to prevent insufficient content to build a block return OfferEntryResult.FAIL_BUFFER_FULL; } else { final EntryImpl entryImpl = EntryImpl .create(entry.getLedgerId(), entry.getEntryId(), entry.getDataBuffer()); offloadBuffer.add(entryImpl); bufferLength.getAndAdd(entryImpl.getLength()); segmentLength.getAndAdd(entryImpl.getLength()); lastOfferedPosition = entryImpl.getPosition(); if (segmentLength.get() >= maxSegmentLength && System.currentTimeMillis() - segmentBeginTimeMillis >= minSegmentCloseTimeMillis) { closeSegment(); } return OfferEntryResult.SUCCESS; } } private synchronized boolean closeSegment() { final boolean result = !segmentInfo.isClosed(); log.debug("close segment {} {}", lastOfferedPosition.getLedgerId(), lastOfferedPosition.getEntryId()); this.segmentInfo.closeSegment(lastOfferedPosition.getLedgerId(), lastOfferedPosition.getEntryId()); return result; } private Position lastOffered() { return lastOfferedPosition; } /** * Attempts to create a BlobStoreLocation from the values in the offloadDriverMetadata, * however, if no values are available, it defaults to the currently configured * provider, region, bucket, etc. * * @param offloadDriverMetadata * @return */ private BlobStoreLocation getBlobStoreLocation(Map<String, String> offloadDriverMetadata) { return (!offloadDriverMetadata.isEmpty()) ? new BlobStoreLocation(offloadDriverMetadata) : new BlobStoreLocation(getOffloadDriverMetadata()); } @Override public CompletableFuture<ReadHandle> readOffloaded(long ledgerId, UUID uid, Map<String, String> offloadDriverMetadata) { BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata); String readBucket = bsKey.getBucket(); CompletableFuture<ReadHandle> promise = new CompletableFuture<>(); String key = DataBlockUtils.dataBlockOffloadKey(ledgerId, uid); String indexKey = DataBlockUtils.indexBlockOffloadKey(ledgerId, uid); readExecutor.chooseThread(ledgerId).execute(() -> { try { BlobStore readBlobstore = getBlobStore(config.getBlobStoreLocation()); promise.complete(BlobStoreBackedReadHandleImpl.open(readExecutor.chooseThread(ledgerId), readBlobstore, readBucket, key, indexKey, DataBlockUtils.VERSION_CHECK, ledgerId, config.getReadBufferSizeInBytes(), this.offloaderStats, offloadDriverMetadata.get(MANAGED_LEDGER_NAME), this.entryOffsetsCache)); } catch (Throwable t) { log.error("Failed readOffloaded: ", t); promise.completeExceptionally(t); } }); return promise; } @Override public CompletableFuture<ReadHandle> readOffloaded(long ledgerId, MLDataFormats.OffloadContext ledgerContext, Map<String, String> offloadDriverMetadata) { BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata); String readBucket = bsKey.getBucket(); CompletableFuture<ReadHandle> promise = new CompletableFuture<>(); final List<MLDataFormats.OffloadSegment> offloadSegmentList = ledgerContext.getOffloadSegmentList(); List<String> keys = Lists.newLinkedList(); List<String> indexKeys = Lists.newLinkedList(); offloadSegmentList.forEach(seg -> { final UUID uuid = new UUID(seg.getUidMsb(), seg.getUidLsb()); final String key = uuid.toString(); final String indexKey = DataBlockUtils.indexBlockOffloadKey(uuid); keys.add(key); indexKeys.add(indexKey); }); readExecutor.chooseThread(ledgerId).execute(() -> { try { BlobStore readBlobstore = getBlobStore(config.getBlobStoreLocation()); promise.complete(BlobStoreBackedReadHandleImplV2.open(readExecutor.chooseThread(ledgerId), readBlobstore, readBucket, keys, indexKeys, DataBlockUtils.VERSION_CHECK, ledgerId, config.getReadBufferSizeInBytes(), this.offloaderStats, offloadDriverMetadata.get(MANAGED_LEDGER_NAME))); } catch (Throwable t) { log.error("Failed readOffloaded: ", t); promise.completeExceptionally(t); } }); return promise; } @Override public CompletableFuture<Void> deleteOffloaded(long ledgerId, UUID uid, Map<String, String> offloadDriverMetadata) { BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata); String readBucket = bsKey.getBucket(offloadDriverMetadata); CompletableFuture<Void> promise = new CompletableFuture<>(); scheduler.chooseThread(ledgerId).execute(() -> { try { BlobStore readBlobstore = getBlobStore(config.getBlobStoreLocation()); readBlobstore.removeBlobs(readBucket, ImmutableList.of(DataBlockUtils.dataBlockOffloadKey(ledgerId, uid), DataBlockUtils.indexBlockOffloadKey(ledgerId, uid))); promise.complete(null); } catch (Throwable t) { log.error("Failed delete Blob", t); promise.completeExceptionally(t); } }); return promise.whenComplete((__, t) -> { if (null != this.ml) { this.offloaderStats.recordDeleteOffloadOps( TopicName.fromPersistenceNamingEncoding(this.ml.getName()), t == null); } }); } @Override public CompletableFuture<Void> deleteOffloaded(UUID uid, Map<String, String> offloadDriverMetadata) { BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata); String readBucket = bsKey.getBucket(offloadDriverMetadata); CompletableFuture<Void> promise = new CompletableFuture<>(); scheduler.execute(() -> { try { BlobStore readBlobstore = getBlobStore(config.getBlobStoreLocation()); readBlobstore.removeBlobs(readBucket, ImmutableList.of(uid.toString(), DataBlockUtils.indexBlockOffloadKey(uid))); promise.complete(null); } catch (Throwable t) { log.error("Failed delete Blob", t); promise.completeExceptionally(t); } }); return promise.whenComplete((__, t) -> this.offloaderStats.recordDeleteOffloadOps( TopicName.fromPersistenceNamingEncoding(this.ml.getName()), t == null)); } @Override public OffloadPolicies getOffloadPolicies() { return this.policies; } @Override public void close() { for (BlobStore readBlobStore : blobStores.values()) { if (readBlobStore != null) { readBlobStore.getContext().close(); } } } @Override public void scanLedgers(OffloadedLedgerMetadataConsumer consumer, Map<String, String> offloadDriverMetadata) throws ManagedLedgerException { BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata); String endpoint = bsKey.getEndpoint(); String readBucket = bsKey.getBucket(); log.info("Scanning bucket {}, bsKey {}, location {} endpoint{} ", readBucket, bsKey, config.getBlobStoreLocation(), endpoint); BlobStore readBlobstore = getBlobStore(config.getBlobStoreLocation()); int batchSize = 100; String bucketName = config.getBucket(); String marker = null; do { marker = scanContainer(consumer, readBlobstore, bucketName, marker, batchSize); } while (marker != null); } private String scanContainer(OffloadedLedgerMetadataConsumer consumer, BlobStore readBlobstore, String bucketName, String lastMarker, int batchSize) throws ManagedLedgerException { ListContainerOptions options = new ListContainerOptions() .maxResults(batchSize) .withDetails(); if (lastMarker != null) { options.afterMarker(lastMarker); } PageSet<? extends StorageMetadata> pages = readBlobstore.list(bucketName, options); for (StorageMetadata md : pages) { log.info("Found {} ", md); String name = md.getName(); Long size = md.getSize(); Date lastModified = md.getLastModified(); StorageType type = md.getType(); if (type != StorageType.BLOB) { continue; } URI uri = md.getUri(); Map<String, String> userMetadata = md.getUserMetadata(); Long ledgerId = DataBlockUtils.parseLedgerId(name); String contextUuid = DataBlockUtils.parseContextUuid(name, ledgerId); log.info("info {} {} {} {} {} {} ledgerId {}", name, size, lastModified, type, uri, userMetadata, ledgerId); OffloadedLedgerMetadata offloadedLedgerMetadata = OffloadedLedgerMetadata.builder() .name(name) .bucketName(bucketName) .uuid(contextUuid) .ledgerId(ledgerId != null ? ledgerId : -1) .lastModified(lastModified != null ? lastModified.getTime() : 0) .size(size != null ? size : -1) .uri(uri != null ? uri.toString() : null) .userMetadata(userMetadata != null ? userMetadata : Collections.emptyMap()) .build(); try { boolean canContinue = consumer.accept(offloadedLedgerMetadata); if (!canContinue) { log.info("Iteration stopped by the OffloadedLedgerMetadataConsumer"); return null; } } catch (Exception err) { log.error("Error in the OffloadedLedgerMetadataConsumer", err); if (err instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw ManagedLedgerException.getManagedLedgerException(err); } } log.info("NextMarker is {}", pages.getNextMarker()); return pages.getNextMarker(); } }
oracle/graal
37,085
substratevm/src/com.oracle.graal.pointsto/src/com/oracle/graal/pointsto/meta/AnalysisUniverse.java
/* * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.pointsto.meta; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; import org.graalvm.nativeimage.hosted.Feature.DuringAnalysisAccess; import org.graalvm.nativeimage.impl.AnnotationExtractor; import org.graalvm.word.WordBase; import com.oracle.graal.pointsto.AnalysisPolicy; import com.oracle.graal.pointsto.BigBang; import com.oracle.graal.pointsto.ObjectScanner; import com.oracle.graal.pointsto.api.HostVM; import com.oracle.graal.pointsto.api.ImageLayerLoader; import com.oracle.graal.pointsto.api.ImageLayerWriter; import com.oracle.graal.pointsto.constraints.UnsupportedFeatureException; import com.oracle.graal.pointsto.heap.HeapSnapshotVerifier; import com.oracle.graal.pointsto.heap.HostedValuesProvider; import com.oracle.graal.pointsto.heap.ImageHeapConstant; import com.oracle.graal.pointsto.heap.ImageHeapScanner; import com.oracle.graal.pointsto.infrastructure.OriginalClassProvider; import com.oracle.graal.pointsto.infrastructure.ResolvedSignature; import com.oracle.graal.pointsto.infrastructure.SubstitutionProcessor; import com.oracle.graal.pointsto.infrastructure.Universe; import com.oracle.graal.pointsto.infrastructure.WrappedConstantPool; import com.oracle.graal.pointsto.infrastructure.WrappedJavaType; import com.oracle.graal.pointsto.meta.AnalysisElement.MethodOverrideReachableNotification; import com.oracle.graal.pointsto.util.AnalysisError; import com.oracle.graal.pointsto.util.ConcurrentLightHashSet; import jdk.graal.compiler.api.replacements.SnippetReflectionProvider; import jdk.graal.compiler.core.common.SuppressFBWarnings; import jdk.vm.ci.code.BytecodePosition; import jdk.vm.ci.common.JVMCIError; import jdk.vm.ci.meta.Constant; import jdk.vm.ci.meta.ConstantPool; import jdk.vm.ci.meta.JavaConstant; import jdk.vm.ci.meta.JavaField; import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.JavaMethod; import jdk.vm.ci.meta.JavaType; import jdk.vm.ci.meta.MetaAccessProvider; import jdk.vm.ci.meta.ResolvedJavaField; import jdk.vm.ci.meta.ResolvedJavaMethod; import jdk.vm.ci.meta.ResolvedJavaType; import jdk.vm.ci.meta.Signature; public class AnalysisUniverse implements Universe { protected final HostVM hostVM; private static final int ESTIMATED_FIELDS_PER_TYPE = 3; public static final int ESTIMATED_NUMBER_OF_TYPES = 2000; static final int ESTIMATED_METHODS_PER_TYPE = 15; static final int ESTIMATED_EMBEDDED_ROOTS = 500; private final ConcurrentMap<ResolvedJavaType, Object> types = new ConcurrentHashMap<>(ESTIMATED_NUMBER_OF_TYPES); private final ConcurrentMap<ResolvedJavaField, AnalysisField> fields = new ConcurrentHashMap<>(ESTIMATED_FIELDS_PER_TYPE * ESTIMATED_NUMBER_OF_TYPES); private final ConcurrentMap<ResolvedJavaMethod, AnalysisMethod> methods = new ConcurrentHashMap<>(ESTIMATED_METHODS_PER_TYPE * ESTIMATED_NUMBER_OF_TYPES); private final ConcurrentMap<ResolvedSignature<AnalysisType>, ResolvedSignature<AnalysisType>> uniqueSignatures = new ConcurrentHashMap<>(); private final ConcurrentMap<ConstantPool, WrappedConstantPool> constantPools = new ConcurrentHashMap<>(ESTIMATED_NUMBER_OF_TYPES); private final ConcurrentHashMap<Constant, Object> embeddedRoots = new ConcurrentHashMap<>(ESTIMATED_EMBEDDED_ROOTS); private final ConcurrentMap<AnalysisField, Boolean> unsafeAccessedStaticFields; private boolean sealed; private volatile AnalysisType[] typesById = new AnalysisType[ESTIMATED_NUMBER_OF_TYPES]; final AtomicInteger nextTypeId = new AtomicInteger(1); final AtomicInteger nextMethodId = new AtomicInteger(1); final AtomicInteger nextFieldId = new AtomicInteger(1); protected final SubstitutionProcessor substitutions; private Function<Object, Object>[] objectReplacers; private Function<Object, ImageHeapConstant>[] objectToConstantReplacers; private Consumer<AnalysisType>[] onTypeCreatedCallbacks; private SubstitutionProcessor[] featureSubstitutions; private SubstitutionProcessor[] featureNativeSubstitutions; private final MetaAccessProvider originalMetaAccess; private final AnalysisFactory analysisFactory; private final AnnotationExtractor annotationExtractor; private final AtomicInteger numReachableTypes = new AtomicInteger(); private AnalysisType objectClass; private AnalysisType cloneableClass; private final JavaKind wordKind; private AnalysisPolicy analysisPolicy; private ImageHeapScanner heapScanner; private ImageLayerWriter imageLayerWriter; private ImageLayerLoader imageLayerLoader; private HeapSnapshotVerifier heapVerifier; private BigBang bb; private DuringAnalysisAccess concurrentAnalysisAccess; private final Map<AnalysisMethod, Set<MethodOverrideReachableNotification>> methodOverrideReachableNotifications = new ConcurrentHashMap<>(); public JavaKind getWordKind() { return wordKind; } @SuppressWarnings("unchecked") public AnalysisUniverse(HostVM hostVM, JavaKind wordKind, AnalysisPolicy analysisPolicy, SubstitutionProcessor substitutions, MetaAccessProvider originalMetaAccess, AnalysisFactory analysisFactory, AnnotationExtractor annotationExtractor) { this.hostVM = hostVM; this.wordKind = wordKind; this.analysisPolicy = analysisPolicy; this.substitutions = substitutions; this.originalMetaAccess = originalMetaAccess; this.analysisFactory = analysisFactory; this.annotationExtractor = annotationExtractor; sealed = false; objectReplacers = (Function<Object, Object>[]) new Function<?, ?>[0]; objectToConstantReplacers = (Function<Object, ImageHeapConstant>[]) new Function<?, ?>[0]; onTypeCreatedCallbacks = (Consumer<AnalysisType>[]) new Consumer<?>[0]; featureSubstitutions = new SubstitutionProcessor[0]; featureNativeSubstitutions = new SubstitutionProcessor[0]; unsafeAccessedStaticFields = analysisPolicy.useConservativeUnsafeAccess() ? null : new ConcurrentHashMap<>(); } @Override public HostVM hostVM() { return hostVM; } protected AnnotationExtractor getAnnotationExtractor() { return annotationExtractor; } public int getNextTypeId() { return nextTypeId.get(); } public int getNextMethodId() { return nextMethodId.get(); } public int getNextFieldId() { return nextFieldId.get(); } public void seal() { sealed = true; } public boolean sealed() { return sealed; } public AnalysisType optionalLookup(ResolvedJavaType type) { ResolvedJavaType actualType = substitutions.lookup(type); Object claim = types.get(actualType); if (claim instanceof AnalysisType) { return (AnalysisType) claim; } return null; } @Override public AnalysisType lookup(JavaType type) { JavaType result = lookupAllowUnresolved(type); if (result == null) { return null; } else if (result instanceof ResolvedJavaType) { return (AnalysisType) result; } throw new UnsupportedFeatureException("Unresolved type found. Probably there are some compilation or classpath problems. " + type.toJavaName(true)); } @Override public JavaType lookupAllowUnresolved(JavaType rawType) { if (rawType == null) { return null; } if (!(rawType instanceof ResolvedJavaType)) { return rawType; } assert !(rawType instanceof AnalysisType) : "lookupAllowUnresolved does not support analysis types."; ResolvedJavaType hostType = (ResolvedJavaType) rawType; ResolvedJavaType type = substitutions.lookup(hostType); AnalysisType result = optionalLookup(type); if (result == null) { result = createType(type); if (hostVM.buildingExtensionLayer() && result.isInBaseLayer()) { imageLayerLoader.initializeBaseLayerType(result); } } assert typesById[result.getId()].equals(result) : result; return result; } @SuppressFBWarnings(value = {"ES_COMPARING_STRINGS_WITH_EQ"}, justification = "Bug in findbugs") private AnalysisType createType(ResolvedJavaType type) { if (!hostVM.platformSupported(type)) { throw new UnsupportedFeatureException("Type is not available in this platform: " + type.toJavaName(true)); } if (sealed && !type.isArray()) { /* * We allow new array classes to be created at any time, since they do not affect the * closed world analysis. */ throw AnalysisError.typeNotFound(type); } /* Run additional checks on the type. */ hostVM.checkType(type, this); /* * We do not want multiple threads to create the AnalysisType simultaneously, because we * want a unique id number per type. So claim the type first, and only when the claim * succeeds create the AnalysisType. */ Object claim = Thread.currentThread().getName(); retry: while (true) { Object result = types.putIfAbsent(type, claim); if (result instanceof AnalysisType) { return (AnalysisType) result; } else if (result != null) { /* * Another thread installed a claim, wait until that thread publishes the * AnalysisType. */ do { result = types.get(type); if (result == null) { /* * The other thread gave up, probably because of an exception. Re-try to * create the type ourself. Probably we are going to fail and throw an * exception too, but that is OK. */ continue retry; } else if (result == claim) { /* * We are waiting for a type that we have claimed ourselves => deadlock. */ throw JVMCIError.shouldNotReachHere("Deadlock creating new types"); } } while (!(result instanceof AnalysisType)); return (AnalysisType) result; } else { break retry; } } try { JavaKind storageKind = originalMetaAccess.lookupJavaType(WordBase.class).isAssignableFrom(OriginalClassProvider.getOriginalType(type)) ? wordKind : type.getJavaKind(); AnalysisType newValue = analysisFactory.createType(this, type, storageKind, objectClass, cloneableClass); synchronized (this) { /* * Synchronize modifications of typesById, so that we do not lose array stores in * one thread that run concurrently with Arrays.copyOf in another thread. This is * the only code that writes to typesById. Reads from typesById in other parts do * not need synchronization because typesById is a volatile field, i.e., reads * always pick up the latest and longest array; and we never publish a type before * it is registered in typesById, i.e., before the array has the appropriate length. */ if (newValue.getId() >= typesById.length) { typesById = Arrays.copyOf(typesById, typesById.length * 2); } assert typesById[newValue.getId()] == null; typesById[newValue.getId()] = newValue; if (objectClass == null && newValue.isJavaLangObject()) { objectClass = newValue; } else if (cloneableClass == null && newValue.toJavaName(true).equals(Cloneable.class.getName())) { cloneableClass = newValue; } } /* * Registering the type can throw an exception. Doing it after the synchronized block * ensures that typesById doesn't contain any null values. This could happen since the * AnalysisType constructor increments the nextTypeId counter. */ if (hostVM.buildingExtensionLayer() && imageLayerLoader.hasDynamicHubIdentityHashCode(newValue.getId())) { hostVM.registerType(newValue, imageLayerLoader.getDynamicHubIdentityHashCode(newValue.getId())); } else { hostVM.registerType(newValue); } /* Register the type as assignable with all its super types before it is published. */ if (bb != null) { newValue.registerAsAssignable(bb); } /* * Now that our type is correctly registered in the id-to-type array, make it accessible * by other threads. */ Object oldValue = types.put(type, newValue); assert oldValue == claim : oldValue + " != " + claim; claim = null; /* * Trigger type creation callbacks. Note this will run in parallel with other threads * being able to retrieve this AnalysisType from {@code types}. */ runOnTypeCreatedCallbacks(newValue); return newValue; } finally { /* In case of any exception, remove the claim so that we do not deadlock. */ if (claim != null) { types.remove(type, claim); } } } @Override public AnalysisField lookup(JavaField field) { JavaField result = lookupAllowUnresolved(field); if (result == null) { return null; } else if (result instanceof ResolvedJavaField) { return (AnalysisField) result; } throw new UnsupportedFeatureException("Unresolved field found. Probably there are some compilation or classpath problems. " + field.format("%H.%n")); } @Override public JavaField lookupAllowUnresolved(JavaField rawField) { if (rawField == null) { return null; } if (!(rawField instanceof ResolvedJavaField)) { return rawField; } assert !(rawField instanceof AnalysisField) : rawField; ResolvedJavaField field = (ResolvedJavaField) rawField; field = substitutions.lookup(field); AnalysisField result = fields.get(field); if (result == null) { result = createField(field); } return result; } private AnalysisField createField(ResolvedJavaField field) { if (!hostVM.platformSupported(field)) { throw new UnsupportedFeatureException("Field is not available in this platform: " + field.format("%H.%n")); } if (sealed) { return null; } AnalysisField newValue = analysisFactory.createField(this, field); AnalysisField result = fields.computeIfAbsent(field, f -> { if (newValue.isInBaseLayer()) { getImageLayerLoader().addBaseLayerField(newValue); } return newValue; }); if (result.equals(newValue)) { if (newValue.isInBaseLayer()) { getImageLayerLoader().initializeBaseLayerField(newValue); } } return result; } @Override public AnalysisMethod lookup(JavaMethod method) { JavaMethod result = lookupAllowUnresolved(method); if (result == null) { return null; } else if (result instanceof ResolvedJavaMethod) { return (AnalysisMethod) result; } throw new UnsupportedFeatureException("Unresolved method found: " + (method != null ? method.format("%H.%n(%p)") : "null") + ". Probably there are some compilation or classpath problems. "); } @Override public JavaMethod lookupAllowUnresolved(JavaMethod rawMethod) { if (rawMethod == null) { return null; } if (!(rawMethod instanceof ResolvedJavaMethod)) { return rawMethod; } assert !(rawMethod instanceof AnalysisMethod) : rawMethod; ResolvedJavaMethod method = (ResolvedJavaMethod) rawMethod; method = substitutions.lookup(method); AnalysisMethod result = methods.get(method); if (result == null) { result = createMethod(method); } return result; } private AnalysisMethod createMethod(ResolvedJavaMethod method) { if (!hostVM.platformSupported(method)) { throw new UnsupportedFeatureException("Method " + method.format("%H.%n(%p)" + " is not available in this platform.")); } if (sealed) { return null; } AnalysisMethod newValue = analysisFactory.createMethod(this, method); AnalysisMethod result = methods.computeIfAbsent(method, m -> { if (newValue.isInBaseLayer()) { getImageLayerLoader().addBaseLayerMethod(newValue); } return newValue; }); if (result.equals(newValue)) { prepareMethodImplementations(newValue); } return result; } /** Prepare information that {@link AnalysisMethod#collectMethodImplementations} needs. */ private static void prepareMethodImplementations(AnalysisMethod method) { if (!method.canBeStaticallyBound() && !method.isConstructor()) { ConcurrentLightHashSet.addElement(method.declaringClass, AnalysisType.overrideableMethodsUpdater, method); for (AnalysisType subtype : method.declaringClass.getAllSubtypes()) { AnalysisMethod override = subtype.resolveConcreteMethod(method, null); if (override != null && !override.equals(method)) { ConcurrentLightHashSet.addElement(method, AnalysisMethod.allImplementationsUpdater, override); if (method.reachableInCurrentLayer()) { override.setReachableInCurrentLayer(); } } } } } public AnalysisMethod[] lookup(JavaMethod[] inputs) { List<AnalysisMethod> result = new ArrayList<>(inputs.length); for (JavaMethod method : inputs) { if (hostVM.platformSupported((ResolvedJavaMethod) method)) { AnalysisMethod aMethod = lookup(method); if (aMethod != null) { result.add(aMethod); } } } return result.toArray(AnalysisMethod.EMPTY_ARRAY); } @Override public ResolvedSignature<AnalysisType> lookup(Signature signature, ResolvedJavaType defaultAccessingClass) { assert !(defaultAccessingClass instanceof WrappedJavaType) : defaultAccessingClass; AnalysisType[] paramTypes = new AnalysisType[signature.getParameterCount(false)]; for (int i = 0; i < paramTypes.length; i++) { paramTypes[i] = lookup(resolveSignatureType(signature.getParameterType(i, defaultAccessingClass), defaultAccessingClass)); } AnalysisType returnType = lookup(resolveSignatureType(signature.getReturnType(defaultAccessingClass), defaultAccessingClass)); ResolvedSignature<AnalysisType> key = ResolvedSignature.fromArray(paramTypes, returnType); return uniqueSignatures.computeIfAbsent(key, k -> k); } private ResolvedJavaType resolveSignatureType(JavaType type, ResolvedJavaType defaultAccessingClass) { /* * We must not invoke resolve() on an already resolved type because it can actually fail the * accessibility check when synthetic methods and synthetic signatures are involved. */ if (type instanceof ResolvedJavaType resolvedType) { return resolvedType; } try { return type.resolve(defaultAccessingClass); } catch (LinkageError e) { /* * Type resolution fails if the parameter type is missing. Just erase the type by * returning the Object type. */ return objectType().getWrapped(); } } @Override public WrappedConstantPool lookup(ConstantPool constantPool, ResolvedJavaType defaultAccessingClass) { assert !(constantPool instanceof WrappedConstantPool) : constantPool; assert !(defaultAccessingClass instanceof WrappedJavaType) : defaultAccessingClass; WrappedConstantPool result = constantPools.get(constantPool); if (result == null) { WrappedConstantPool newValue = new WrappedConstantPool(this, constantPool, defaultAccessingClass); WrappedConstantPool oldValue = constantPools.putIfAbsent(constantPool, newValue); result = oldValue != null ? oldValue : newValue; } return result; } @Override public JavaConstant lookup(JavaConstant constant) { if (constant == null || constant.isNull() || constant.getJavaKind().isPrimitive()) { return constant; } return heapScanner.createImageHeapConstant(getHostedValuesProvider().interceptHosted(constant), ObjectScanner.OtherReason.UNKNOWN); } public boolean isTypeCreated(int typeId) { return typesById.length > typeId && typesById[typeId] != null; } public List<AnalysisType> getTypes() { /* * The typesById array can contain null values because the ids from the base layers are * reserved when they are loaded in a new layer. */ return Arrays.asList(typesById).subList(0, getNextTypeId()).stream().filter(Objects::nonNull).toList(); } public AnalysisType getType(int typeId) { AnalysisType result = typesById[typeId]; assert result.getId() == typeId : result; return result; } public Collection<AnalysisField> getFields() { return fields.values(); } public AnalysisField getField(ResolvedJavaField resolvedJavaField) { return fields.get(resolvedJavaField); } public Collection<AnalysisMethod> getMethods() { return methods.values(); } public AnalysisMethod getMethod(ResolvedJavaMethod resolvedJavaMethod) { return methods.get(resolvedJavaMethod); } /** * Returns the root {@link AnalysisMethod}s. Accessing the roots is useful when traversing the * call graph. * * @param universe the universe from which the roots are derived from. * @return the call tree roots. */ public static List<AnalysisMethod> getCallTreeRoots(AnalysisUniverse universe) { List<AnalysisMethod> roots = new ArrayList<>(); for (AnalysisMethod m : universe.getMethods()) { if (m.isDirectRootMethod() && m.isSimplyImplementationInvoked()) { roots.add(m); } if (m.isVirtualRootMethod()) { for (AnalysisMethod impl : m.collectMethodImplementations(false)) { AnalysisError.guarantee(impl.isImplementationInvoked()); roots.add(impl); } } } return roots; } public Map<Constant, Object> getEmbeddedRoots() { return embeddedRoots; } /** * Register an embedded root, i.e., a JavaConstant embedded in a Graal graph via a ConstantNode. */ public void registerEmbeddedRoot(JavaConstant root, BytecodePosition position) { this.heapScanner.scanEmbeddedRoot(root, position); this.embeddedRoots.put(root, position); } public void registerUnsafeAccessedStaticField(AnalysisField field) { AnalysisError.guarantee(!analysisPolicy.useConservativeUnsafeAccess(), "With conservative unsafe access we don't track unsafe accessed fields."); AnalysisError.guarantee(!field.getType().isWordType(), "static Word fields cannot be unsafe accessed %s", this); unsafeAccessedStaticFields.put(field, true); } public Set<AnalysisField> getUnsafeAccessedStaticFields() { AnalysisError.guarantee(!analysisPolicy.useConservativeUnsafeAccess(), "With conservative unsafe access we don't track unsafe accessed fields."); return unsafeAccessedStaticFields.keySet(); } public void registerObjectReplacer(Function<Object, Object> replacer) { assert replacer != null; objectReplacers = Arrays.copyOf(objectReplacers, objectReplacers.length + 1); objectReplacers[objectReplacers.length - 1] = replacer; } public void registerObjectToConstantReplacer(Function<Object, ImageHeapConstant> replacer) { assert replacer != null; objectToConstantReplacers = Arrays.copyOf(objectToConstantReplacers, objectToConstantReplacers.length + 1); objectToConstantReplacers[objectToConstantReplacers.length - 1] = replacer; } public void registerOnTypeCreatedCallback(Consumer<AnalysisType> consumer) { assert consumer != null; assert !bb.isInitialized() : "too late to add a callback"; onTypeCreatedCallbacks = Arrays.copyOf(onTypeCreatedCallbacks, onTypeCreatedCallbacks.length + 1); onTypeCreatedCallbacks[onTypeCreatedCallbacks.length - 1] = consumer; } public void registerFeatureSubstitution(SubstitutionProcessor substitution) { SubstitutionProcessor[] subs = featureSubstitutions; subs = Arrays.copyOf(subs, subs.length + 1); subs[subs.length - 1] = substitution; featureSubstitutions = subs; } public SubstitutionProcessor[] getFeatureSubstitutions() { return featureSubstitutions; } public void registerFeatureNativeSubstitution(SubstitutionProcessor substitution) { SubstitutionProcessor[] nativeSubs = featureNativeSubstitutions; nativeSubs = Arrays.copyOf(nativeSubs, nativeSubs.length + 1); nativeSubs[nativeSubs.length - 1] = substitution; featureNativeSubstitutions = nativeSubs; } public SubstitutionProcessor[] getFeatureNativeSubstitutions() { return featureNativeSubstitutions; } public Object replaceObject(Object source) { return replaceObject0(source, false); } public JavaConstant replaceObjectWithConstant(Object source) { return replaceObjectWithConstant(source, getHostedValuesProvider()::forObject); } public JavaConstant replaceObjectWithConstant(Object source, Function<Object, JavaConstant> converter) { assert !(source instanceof ImageHeapConstant) : source; var replacedObject = replaceObject0(source, true); if (replacedObject instanceof ImageHeapConstant constant) { return constant; } return converter.apply(replacedObject); } /** * Invokes all registered object replacers and "object to constant" replacers for an object.> * * <p> * The "object to constant" replacer is allowed to successfully complete only when * {@code allowObjectToConstantReplacement} is true. When * {@code allowObjectToConstantReplacement} is false, if any "object to constant" replacer is * triggered we throw an error. * * @param source The source object * @param allowObjectToConstantReplacement whether object to constant replacement is supported * @return The replaced object or the original source, if the source is not replaced by any * registered replacer. */ private Object replaceObject0(Object source, boolean allowObjectToConstantReplacement) { if (source == null) { return null; } Object destination = source; for (Function<Object, Object> replacer : objectReplacers) { destination = replacer.apply(destination); } ImageHeapConstant ihc = null; for (Function<Object, ImageHeapConstant> replacer : objectToConstantReplacers) { var result = replacer.apply(destination); if (result != null) { AnalysisError.guarantee(allowObjectToConstantReplacement, "Object to constant replacement has been triggered from an unsupported location"); AnalysisError.guarantee(ihc == null, "Multiple object to constant replacers have been trigger on a single object %s %s %s", destination, ihc, result); ihc = result; } } return ihc == null ? destination : ihc; } public void notifyBigBangInitialized() { assert bb.isInitialized(); /* * It is possible for types to be created before all typeCreationCallbacks are installed. * Hence, we trigger the typeCreationCallbacks for all types created prior to the completion * of big bang initialization at this point. */ for (var obj : types.values().toArray()) { /* * Nominally the map values are of type object and can hold a thread object while an * AnalysisType is being created. However, this method is called when all values will be * of type AnalysisType. */ AnalysisType aType = (AnalysisType) obj; runOnTypeCreatedCallbacks(aType); } } private void runOnTypeCreatedCallbacks(AnalysisType type) { if (bb == null || !bb.isInitialized()) { /* * Until the big bang is initialized, it is possible for more callbacks to be * registered. Hence, these hooks are run on all types created before big bang * initialization via {@code notifyBigBangInitialized} */ return; } for (var callback : onTypeCreatedCallbacks) { bb.postTask((t) -> callback.accept(type)); } } public void registerOverrideReachabilityNotification(AnalysisMethod declaredMethod, MethodOverrideReachableNotification notification) { methodOverrideReachableNotifications.computeIfAbsent(declaredMethod, m -> ConcurrentHashMap.newKeySet()).add(notification); } public void runAtFixedPoint() { /* * It is too expensive to immediately send out override notifications when a new method * becomes reachable. We therefore send them out after the analysis has reached a fixed * point. When new tasks are scheduled, the parallel analysis must be restarted. */ for (var entry : methodOverrideReachableNotifications.entrySet()) { var method = entry.getKey(); for (var override : method.collectMethodImplementations(true)) { for (var notification : entry.getValue()) { notification.notifyCallback(this, override); } } } } /** * Collect and returns *all reachable* subtypes of this type, not only the immediate subtypes. * To access the immediate sub-types use {@link AnalysisType#getSubTypes()}. * * Since the sub-types are updated continuously as the universe is expanded this method may * return different results on each call, until the analysis universe reaches a stable state. */ public static Set<AnalysisType> reachableSubtypes(AnalysisType baseType) { Set<AnalysisType> result = baseType.getAllSubtypes(); result.removeIf(t -> !t.isReachable()); return result; } @Override public SnippetReflectionProvider getSnippetReflection() { return bb.getSnippetReflectionProvider(); } @Override public AnalysisType objectType() { return objectClass; } public void onFieldAccessed(AnalysisField field) { bb.onFieldAccessed(field); } public void onTypeInstantiated(AnalysisType type) { hostVM.onTypeInstantiated(bb, type); bb.onTypeInstantiated(type); } public void onTypeReachable(AnalysisType type) { hostVM.onTypeReachable(bb, type); if (bb != null) { bb.onTypeReachable(type); } } public void initializeMetaData(AnalysisType type) { bb.initializeMetaData(type); } public SubstitutionProcessor getSubstitutions() { return substitutions; } public AnalysisPolicy analysisPolicy() { return analysisPolicy; } public MetaAccessProvider getOriginalMetaAccess() { return originalMetaAccess; } public void setBigBang(BigBang bb) { this.bb = bb; } public BigBang getBigbang() { return bb; } public void setConcurrentAnalysisAccess(DuringAnalysisAccess access) { this.concurrentAnalysisAccess = access; } public DuringAnalysisAccess getConcurrentAnalysisAccess() { AnalysisError.guarantee(concurrentAnalysisAccess != null, "The requested DuringAnalysisAccess object is not available. " + "This means that an analysis task is executed too eagerly, before analysis. " + "Make sure that all analysis tasks are posted to the analysis execution engine."); return concurrentAnalysisAccess; } public void setHeapScanner(ImageHeapScanner heapScanner) { this.heapScanner = heapScanner; } public ImageHeapScanner getHeapScanner() { return heapScanner; } public void setImageLayerWriter(ImageLayerWriter imageLayerWriter) { this.imageLayerWriter = imageLayerWriter; } public ImageLayerWriter getImageLayerWriter() { return imageLayerWriter; } public void setImageLayerLoader(ImageLayerLoader imageLayerLoader) { this.imageLayerLoader = imageLayerLoader; } public ImageLayerLoader getImageLayerLoader() { return imageLayerLoader; } public HostedValuesProvider getHostedValuesProvider() { return heapScanner.getHostedValuesProvider(); } public void setHeapVerifier(HeapSnapshotVerifier heapVerifier) { this.heapVerifier = heapVerifier; } public HeapSnapshotVerifier getHeapVerifier() { return heapVerifier; } public void notifyReachableType() { numReachableTypes.incrementAndGet(); } public int getReachableTypes() { return numReachableTypes.get(); } public void setStartTypeId(int startTid) { /* No type was created yet, so the array can be overwritten without any concurrency issue */ typesById = new AnalysisType[startTid]; setStartId(nextTypeId, startTid, 1); } public void setStartMethodId(int startMid) { setStartId(nextMethodId, startMid, 1); } public void setStartFieldId(int startFid) { setStartId(nextFieldId, startFid, 1); } private static void setStartId(AtomicInteger nextId, int startFid, int expectedStartValue) { if (nextId.compareAndExchange(expectedStartValue, startFid) != expectedStartValue) { throw AnalysisError.shouldNotReachHere("An id was assigned before the start id was set."); } } public int computeNextTypeId() { return nextTypeId.getAndIncrement(); } public int computeNextMethodId() { return nextMethodId.getAndIncrement(); } public int computeNextFieldId() { return nextFieldId.getAndIncrement(); } }
googleapis/google-cloud-java
36,843
java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/ListDataStreamsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1alpha/analytics_admin.proto // Protobuf Java Version: 3.25.8 package com.google.analytics.admin.v1alpha; /** * * * <pre> * Response message for ListDataStreams RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1alpha.ListDataStreamsResponse} */ public final class ListDataStreamsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.ListDataStreamsResponse) ListDataStreamsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDataStreamsResponse.newBuilder() to construct. private ListDataStreamsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDataStreamsResponse() { dataStreams_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDataStreamsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListDataStreamsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListDataStreamsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.ListDataStreamsResponse.class, com.google.analytics.admin.v1alpha.ListDataStreamsResponse.Builder.class); } public static final int DATA_STREAMS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.analytics.admin.v1alpha.DataStream> dataStreams_; /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ @java.lang.Override public java.util.List<com.google.analytics.admin.v1alpha.DataStream> getDataStreamsList() { return dataStreams_; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.analytics.admin.v1alpha.DataStreamOrBuilder> getDataStreamsOrBuilderList() { return dataStreams_; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ @java.lang.Override public int getDataStreamsCount() { return dataStreams_.size(); } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1alpha.DataStream getDataStreams(int index) { return dataStreams_.get(index); } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1alpha.DataStreamOrBuilder getDataStreamsOrBuilder(int index) { return dataStreams_.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 < dataStreams_.size(); i++) { output.writeMessage(1, dataStreams_.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 < dataStreams_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataStreams_.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.v1alpha.ListDataStreamsResponse)) { return super.equals(obj); } com.google.analytics.admin.v1alpha.ListDataStreamsResponse other = (com.google.analytics.admin.v1alpha.ListDataStreamsResponse) obj; if (!getDataStreamsList().equals(other.getDataStreamsList())) 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 (getDataStreamsCount() > 0) { hash = (37 * hash) + DATA_STREAMS_FIELD_NUMBER; hash = (53 * hash) + getDataStreamsList().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.v1alpha.ListDataStreamsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.analytics.admin.v1alpha.ListDataStreamsResponse 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 ListDataStreams RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1alpha.ListDataStreamsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.ListDataStreamsResponse) com.google.analytics.admin.v1alpha.ListDataStreamsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListDataStreamsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListDataStreamsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.ListDataStreamsResponse.class, com.google.analytics.admin.v1alpha.ListDataStreamsResponse.Builder.class); } // Construct using com.google.analytics.admin.v1alpha.ListDataStreamsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dataStreamsBuilder_ == null) { dataStreams_ = java.util.Collections.emptyList(); } else { dataStreams_ = null; dataStreamsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListDataStreamsResponse_descriptor; } @java.lang.Override public com.google.analytics.admin.v1alpha.ListDataStreamsResponse getDefaultInstanceForType() { return com.google.analytics.admin.v1alpha.ListDataStreamsResponse.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1alpha.ListDataStreamsResponse build() { com.google.analytics.admin.v1alpha.ListDataStreamsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1alpha.ListDataStreamsResponse buildPartial() { com.google.analytics.admin.v1alpha.ListDataStreamsResponse result = new com.google.analytics.admin.v1alpha.ListDataStreamsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.analytics.admin.v1alpha.ListDataStreamsResponse result) { if (dataStreamsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dataStreams_ = java.util.Collections.unmodifiableList(dataStreams_); bitField0_ = (bitField0_ & ~0x00000001); } result.dataStreams_ = dataStreams_; } else { result.dataStreams_ = dataStreamsBuilder_.build(); } } private void buildPartial0(com.google.analytics.admin.v1alpha.ListDataStreamsResponse 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.v1alpha.ListDataStreamsResponse) { return mergeFrom((com.google.analytics.admin.v1alpha.ListDataStreamsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1alpha.ListDataStreamsResponse other) { if (other == com.google.analytics.admin.v1alpha.ListDataStreamsResponse.getDefaultInstance()) return this; if (dataStreamsBuilder_ == null) { if (!other.dataStreams_.isEmpty()) { if (dataStreams_.isEmpty()) { dataStreams_ = other.dataStreams_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDataStreamsIsMutable(); dataStreams_.addAll(other.dataStreams_); } onChanged(); } } else { if (!other.dataStreams_.isEmpty()) { if (dataStreamsBuilder_.isEmpty()) { dataStreamsBuilder_.dispose(); dataStreamsBuilder_ = null; dataStreams_ = other.dataStreams_; bitField0_ = (bitField0_ & ~0x00000001); dataStreamsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDataStreamsFieldBuilder() : null; } else { dataStreamsBuilder_.addAllMessages(other.dataStreams_); } } } 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.v1alpha.DataStream m = input.readMessage( com.google.analytics.admin.v1alpha.DataStream.parser(), extensionRegistry); if (dataStreamsBuilder_ == null) { ensureDataStreamsIsMutable(); dataStreams_.add(m); } else { dataStreamsBuilder_.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.v1alpha.DataStream> dataStreams_ = java.util.Collections.emptyList(); private void ensureDataStreamsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dataStreams_ = new java.util.ArrayList<com.google.analytics.admin.v1alpha.DataStream>(dataStreams_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1alpha.DataStream, com.google.analytics.admin.v1alpha.DataStream.Builder, com.google.analytics.admin.v1alpha.DataStreamOrBuilder> dataStreamsBuilder_; /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public java.util.List<com.google.analytics.admin.v1alpha.DataStream> getDataStreamsList() { if (dataStreamsBuilder_ == null) { return java.util.Collections.unmodifiableList(dataStreams_); } else { return dataStreamsBuilder_.getMessageList(); } } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public int getDataStreamsCount() { if (dataStreamsBuilder_ == null) { return dataStreams_.size(); } else { return dataStreamsBuilder_.getCount(); } } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public com.google.analytics.admin.v1alpha.DataStream getDataStreams(int index) { if (dataStreamsBuilder_ == null) { return dataStreams_.get(index); } else { return dataStreamsBuilder_.getMessage(index); } } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder setDataStreams(int index, com.google.analytics.admin.v1alpha.DataStream value) { if (dataStreamsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataStreamsIsMutable(); dataStreams_.set(index, value); onChanged(); } else { dataStreamsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder setDataStreams( int index, com.google.analytics.admin.v1alpha.DataStream.Builder builderForValue) { if (dataStreamsBuilder_ == null) { ensureDataStreamsIsMutable(); dataStreams_.set(index, builderForValue.build()); onChanged(); } else { dataStreamsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder addDataStreams(com.google.analytics.admin.v1alpha.DataStream value) { if (dataStreamsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataStreamsIsMutable(); dataStreams_.add(value); onChanged(); } else { dataStreamsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder addDataStreams(int index, com.google.analytics.admin.v1alpha.DataStream value) { if (dataStreamsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataStreamsIsMutable(); dataStreams_.add(index, value); onChanged(); } else { dataStreamsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder addDataStreams( com.google.analytics.admin.v1alpha.DataStream.Builder builderForValue) { if (dataStreamsBuilder_ == null) { ensureDataStreamsIsMutable(); dataStreams_.add(builderForValue.build()); onChanged(); } else { dataStreamsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder addDataStreams( int index, com.google.analytics.admin.v1alpha.DataStream.Builder builderForValue) { if (dataStreamsBuilder_ == null) { ensureDataStreamsIsMutable(); dataStreams_.add(index, builderForValue.build()); onChanged(); } else { dataStreamsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder addAllDataStreams( java.lang.Iterable<? extends com.google.analytics.admin.v1alpha.DataStream> values) { if (dataStreamsBuilder_ == null) { ensureDataStreamsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataStreams_); onChanged(); } else { dataStreamsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder clearDataStreams() { if (dataStreamsBuilder_ == null) { dataStreams_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dataStreamsBuilder_.clear(); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public Builder removeDataStreams(int index) { if (dataStreamsBuilder_ == null) { ensureDataStreamsIsMutable(); dataStreams_.remove(index); onChanged(); } else { dataStreamsBuilder_.remove(index); } return this; } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public com.google.analytics.admin.v1alpha.DataStream.Builder getDataStreamsBuilder(int index) { return getDataStreamsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public com.google.analytics.admin.v1alpha.DataStreamOrBuilder getDataStreamsOrBuilder( int index) { if (dataStreamsBuilder_ == null) { return dataStreams_.get(index); } else { return dataStreamsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public java.util.List<? extends com.google.analytics.admin.v1alpha.DataStreamOrBuilder> getDataStreamsOrBuilderList() { if (dataStreamsBuilder_ != null) { return dataStreamsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dataStreams_); } } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public com.google.analytics.admin.v1alpha.DataStream.Builder addDataStreamsBuilder() { return getDataStreamsFieldBuilder() .addBuilder(com.google.analytics.admin.v1alpha.DataStream.getDefaultInstance()); } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public com.google.analytics.admin.v1alpha.DataStream.Builder addDataStreamsBuilder(int index) { return getDataStreamsFieldBuilder() .addBuilder(index, com.google.analytics.admin.v1alpha.DataStream.getDefaultInstance()); } /** * * * <pre> * List of DataStreams. * </pre> * * <code>repeated .google.analytics.admin.v1alpha.DataStream data_streams = 1;</code> */ public java.util.List<com.google.analytics.admin.v1alpha.DataStream.Builder> getDataStreamsBuilderList() { return getDataStreamsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1alpha.DataStream, com.google.analytics.admin.v1alpha.DataStream.Builder, com.google.analytics.admin.v1alpha.DataStreamOrBuilder> getDataStreamsFieldBuilder() { if (dataStreamsBuilder_ == null) { dataStreamsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1alpha.DataStream, com.google.analytics.admin.v1alpha.DataStream.Builder, com.google.analytics.admin.v1alpha.DataStreamOrBuilder>( dataStreams_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dataStreams_ = null; } return dataStreamsBuilder_; } 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.v1alpha.ListDataStreamsResponse) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.ListDataStreamsResponse) private static final com.google.analytics.admin.v1alpha.ListDataStreamsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.ListDataStreamsResponse(); } public static com.google.analytics.admin.v1alpha.ListDataStreamsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDataStreamsResponse> PARSER = new com.google.protobuf.AbstractParser<ListDataStreamsResponse>() { @java.lang.Override public ListDataStreamsResponse 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<ListDataStreamsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDataStreamsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1alpha.ListDataStreamsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/sis
36,532
endorsed/src/org.apache.sis.metadata/test/org/apache/sis/xml/test/DocumentComparator.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.sis.xml.test; import java.util.Map; import java.util.Set; import java.util.List; import java.util.HashSet; import java.util.ArrayList; import java.io.File; import java.io.FileInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.net.URI; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import static java.lang.StrictMath.*; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.apache.sis.xml.Namespaces; import org.apache.sis.util.ArgumentChecks; import org.apache.sis.util.internal.shared.Strings; import org.apache.sis.xml.internal.shared.LegacyNamespaces; import static org.apache.sis.util.Characters.NO_BREAK_SPACE; // Test dependencies import static org.junit.jupiter.api.Assertions.*; /** * Compares the XML document produced by a test method with the expected XML document. * The two XML documents are specified at construction time. The comparison is performed * by a call to the {@link #compare()} method. The execution is delegated to the various * protected methods defined in this class, which can be overridden. * * <p>By default, this comparator expects the documents to contain the same elements and * the same attributes (but the order of attributes may be different). * However, it is possible to:</p> * * <ul> * <li>Specify whether comments shall be ignored (see {@link #ignoreComments})</li> * <li>Specify attributes to ignore in comparisons (see {@link #ignoredAttributes})</li> * <li>Specify nodes to ignore, including children (see {@link #ignoredNodes})</li> * <li>Specify a tolerance threshold for comparisons of numerical values (see {@link #tolerance})</li> * </ul> * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @author Guilhem Legal (Geomatys) * * @see TestCase * @see org.apache.sis.test.MetadataAssert#assertXmlEquals(Object, Object, String[]) */ public class DocumentComparator { /** * Commonly used prefixes for namespaces. Used as shorthands for calls to * {@link org.apache.sis.test.MetadataAssert#assertXmlEquals(Object, Object, String[])}. * * @see #substitutePrefix(String) */ private static final Map<String, String> PREFIX_URL = Map.of( "xmlns", "http://www.w3.org/2000/xmlns", // No trailing slash. "xlink", Namespaces.XLINK, "xsi", Namespaces.XSI, "gco", Namespaces.GCO, "mdb", Namespaces.MDB, "srv", Namespaces.SRV, "gml", Namespaces.GML, "gmd", LegacyNamespaces.GMD, "gmx", LegacyNamespaces.GMX, "gmi", LegacyNamespaces.GMI); /** * The DOM factory, created when first needed. * * @see #newDocumentBuilder() */ private static DocumentBuilderFactory factory; /** * The expected document. */ private final Node expectedDoc; /** * The document resulting from the test method. */ private final Node actualDoc; /** * {@code true} if the comments shall be ignored. The default value is {@code false}. */ public boolean ignoreComments; /** * The fully-qualified name of attributes to ignore in comparisons. * This collection is initially empty. Users can add or remove elements in this collection as they wish. * The content of this collection will be honored by the default {@link #compareAttributes(Node, Node)} * implementation. * * <p>The elements shall be names in the form {@code "namespace:name"}, or only {@code "name"} if there * is no namespace. In order to ignore everything in a namespace, use {@code "namespace:*"}.</p> * * <p>Whether the namespace is the full URL or only the prefix depends on whether * {@link DocumentBuilderFactory#setNamespaceAware(boolean)} was set to {@code true} * or {@code false} respectively before the XML document has been built. * For example, in order to ignore the standard {@code "schemaLocation"} attribute:</p> * * <ul> * <li>If {@code NamespaceAware} is {@code true}, then this {@code ignoredAttributes} collection * shall contain {@code "http://www.w3.org/2001/XMLSchema-instance:schemaLocation"}.</li> * <li>If {@code NamespaceAware} is {@code false}, then this {@code ignoredAttributes} collection * shall contain {@code "xsi:schemaLocation"}, assuming that {@code "xsi"} is the prefix for * {@code "http://www.w3.org/2001/XMLSchema-instance"}.</li> * </ul> * * <p>{@code DocumentComparator} is namespace aware. The second case in the above-cited choice may happen only * if the user provided {@link Node} instances to the constructor. In such case, {@code DocumentComparator} has * no control on whether the nodes contain namespaces or not.</p> * * <p>For example, in order to ignore the namespace, type and schema location declaration, * the following strings can be added in this set:</p> * * <pre class="text"> * "http://www.w3.org/2000/xmlns:*", * "http://www.w3.org/2001/XMLSchema-instance:schemaLocation", * "http://www.w3.org/2001/XMLSchema-instance:type"</pre> * * Note that for convenience, the {@link org.apache.sis.test.MetadataAssert#assertXmlEquals(Object, Object, String[])} * method automatically replaces some widely used prefixes by their full URL. */ public final Set<String> ignoredAttributes; /** * The fully-qualified name of nodes to ignore in comparisons. The name shall be in the form * {@code "namespace:name"}, or only {@code "name"} if there is no namespace. In order to * ignore everything in a namespace, use {@code "namespace:*"}. * * <p>This set provides a way to ignore a node of the given name <em>and all its children</em>. * In order to ignore a node but still compare its children, override the * {@link #compareNode(Node, Node)} method instead.</p> * * <p>This set is initially empty. Users can add or remove elements in this set as they wish. * The content of this set will be honored by the default {@link #compareChildren(Node, Node)} * implementation.</p> */ public final Set<String> ignoredNodes; /** * The tolerance threshold for comparisons of numerical values, or 0 for strict comparisons. * The default value is 0. */ public double tolerance; /** * Creates a new comparator for the given inputs. * The inputs can be any of the following types: * * <ul> * <li>{@link Node}: used directly without further processing.</li> * <li>{@link InputStream}: parsed as an XML document, then closed.</li> * <li>{@link Path}, {@link File}, {@link URL} or {@link URI}: * the stream is opened and parsed as an XML document, then closed.</li> * <li>{@link String}: The string content is parsed directly as a XML document.</li> * </ul> * * @param expected the expected XML document. * @param actual the XML document to compare. * @throws IOException if the stream cannot be read. * @throws ParserConfigurationException if a {@link DocumentBuilder} cannot be created. * @throws SAXException if an error occurred while parsing the XML document. */ public DocumentComparator(final Object expected, final Object actual) throws IOException, ParserConfigurationException, SAXException { ArgumentChecks.ensureNonNull("expected", expected); ArgumentChecks.ensureNonNull("actual", actual); DocumentBuilder builder = null; if (expected instanceof Node node) { expectedDoc = node; } else { builder = newDocumentBuilder(); try (InputStream stream = toInputStream(expected)) { expectedDoc = builder.parse(stream); } } if (actual instanceof Node node) { actualDoc = node; } else { if (builder == null) { builder = newDocumentBuilder(); } try (InputStream stream = toInputStream(actual)) { actualDoc = builder.parse(stream); } } ignoredAttributes = new HashSet<>(); ignoredNodes = new HashSet<>(); } /** * Creates a new document builder. */ private synchronized static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { if (factory == null) { factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); } return factory.newDocumentBuilder(); } /** * Converts the given object to a stream. * See the constructor Javadoc for the list of allowed input type. */ private static InputStream toInputStream(final Object input) throws IOException { if (input instanceof InputStream t) return t; if (input instanceof File t) return new FileInputStream(t); if (input instanceof URI t) return t.toURL().openStream(); if (input instanceof URL t) return t.openStream(); if (input instanceof Path t) return Files.newInputStream(t); if (input instanceof String t) return new ByteArrayInputStream(t.getBytes("UTF-8")); throw new IOException("Cannot handle input type: " + (input != null ? input.getClass() : input)); } /** * If the given attribute name begins with one of the well known prefixes, * substitutes the prefix by the full URL. Otherwise returns the name unchanged. * * <h4>Example</h4> * If the given attribute is {@code xmlns:gml}, then this method returns * {@code "http://www.w3.org/2000/xmlns:gml"}. * * @param attribute the attribute. * @return the given attribute, possibly with prefix replaced by URL. */ public static String substitutePrefix(final String attribute) { final int s = attribute.lastIndexOf(':'); if (s >= 0) { final String url = PREFIX_URL.get(attribute.substring(0, s)); if (url != null) { return url.concat(attribute.substring(s)); } } return attribute; } /** * Compares the XML document specified at construction time. Before to invoke this * method, users may consider to add some values to the {@link #ignoredAttributes} * set. */ public void compare() { compareNode(expectedDoc, actualDoc); } /** * Compares the two given nodes. This method delegates to one of the given methods depending * on the expected node type: * * <ul> * <li>{@link #compareCDATASectionNode(CDATASection, Node)}</li> * <li>{@link #compareTextNode(Text, Node)}</li> * <li>{@link #compareCommentNode(Comment, Node)}</li> * <li>{@link #compareProcessingInstructionNode(ProcessingInstruction, Node)}</li> * <li>For all other types, {@link #compareNames(Node, Node)} and * {@link #compareAttributes(Node, Node)}</li> * </ul> * * Then this method invokes itself recursively for every children, * by a call to {@link #compareChildren(Node, Node)}. * * @param expected the expected node. * @param actual the node to compare. */ protected void compareNode(final Node expected, final Node actual) { if (expected == null || actual == null) { fail(formatErrorMessage(expected, actual)); return; } /* * Check text value for types: * TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE, PROCESSING_INSTRUCTION_NODE */ if (expected instanceof CDATASection t) { compareCDATASectionNode(t, actual); } else if (expected instanceof Text t) { compareTextNode(t, actual); } else if (expected instanceof Comment t) { compareCommentNode(t, actual); } else if (expected instanceof ProcessingInstruction t) { compareProcessingInstructionNode(t, actual); } else if (expected instanceof Attr t) { compareAttributeNode(t, actual); } else { compareNames(expected, actual); compareAttributes(expected, actual); } /* * Check child nodes recursivly if it's not an attribute. */ if (expected.getNodeType() != Node.ATTRIBUTE_NODE) { compareChildren(expected, actual); } } /** * Compares a node which is expected to be of {@link Text} type. The default implementation * ensures that the given node is an instance of {@link Text}, then ensures that both nodes * have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareTextNode(final Text expected, final Node actual) { assertInstanceOf(Text.class, actual, "Actual node is not of the expected type."); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link CDATASection} type. The default * implementation ensures that the given node is an instance of {@link CDATASection}, * then ensures that both nodes have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareCDATASectionNode(final CDATASection expected, final Node actual) { assertInstanceOf(CDATASection.class, actual, "Actual node is not of the expected type."); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link Comment} type. The default * implementation ensures that the given node is an instance of {@link Comment}, * then ensures that both nodes have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareCommentNode(final Comment expected, final Node actual) { assertInstanceOf(Comment.class, actual, "Actual node is not of the expected type."); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link ProcessingInstruction} type. The default * implementation ensures that the given node is an instance of {@link ProcessingInstruction}, * then ensures that both nodes have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareProcessingInstructionNode(final ProcessingInstruction expected, final Node actual) { assertInstanceOf(ProcessingInstruction.class, actual, "Actual node is not of the expected type."); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link Attr} type. The default * implementation ensures that the given node is an instance of {@link Attr}, * then ensures that both nodes have the same names and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareAttributeNode(final Attr expected, final Node actual) { assertInstanceOf(Attr.class, actual, "Actual node is not of the expected type."); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares the children of the given nodes. The node themselves are not compared. * Children shall appear in the same order. Nodes having a name declared in the * {@link #ignoredNodes} set are ignored. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the node for which to compare children. */ protected void compareChildren(Node expected, Node actual) { expected = firstNonEmptySibling(expected.getFirstChild()); actual = firstNonEmptySibling(actual .getFirstChild()); while (expected != null) { compareNode(expected, actual); expected = firstNonEmptySibling(expected.getNextSibling()); actual = firstNonEmptySibling(actual .getNextSibling()); } if (actual != null) { fail(formatErrorMessage(expected, actual)); } } /** * Compares the names and namespaces of the given node. * Subclasses can override this method if they need a different comparison. * * @param expected the node having the expected name and namespace. * @param actual the node to compare. */ protected void compareNames(final Node expected, final Node actual) { assertPropertyEquals("namespace", expected.getNamespaceURI(), actual.getNamespaceURI(), expected, actual); String expectedName = expected.getLocalName(); String actualName = actual.getLocalName(); if (expectedName == null || actualName == null) { expectedName = expected.getNodeName(); actualName = actual.getNodeName(); } assertPropertyEquals("name", expectedName, actualName, expected, actual); } /** * Compares the attributes of the given nodes. * Subclasses can override this method if they need a different comparison. * * <p><strong>NOTE:</strong> Current implementation requires the number of attributes to be the * same only if the {@link #ignoredAttributes} set is empty. If the {@code ignoredAttributes} * set is not empty, then the actual node could have more attributes than the expected node; * the extra attributes are ignored. This may change in a future version if it appears to be * a problem in practice.</p> * * @param expected the node having the expected attributes. * @param actual the node to compare. */ protected void compareAttributes(final Node expected, final Node actual) { final NamedNodeMap expectedAttributes = expected.getAttributes(); final NamedNodeMap actualAttributes = actual.getAttributes(); final int n = (expectedAttributes != null) ? expectedAttributes.getLength() : 0; if (ignoredAttributes.isEmpty()) { assertPropertyEquals("nbAttributes", n, (actualAttributes != null) ? actualAttributes.getLength() : 0, expected, actual); } for (int i=0; i<n; i++) { final Node expAttr = expectedAttributes.item(i); final String ns = expAttr.getNamespaceURI(); String name = expAttr.getLocalName(); if (name == null) { /* * The above variables may be null if the node has been built from a DOM Level 1 API, * or if the DocumentBuilder was not namespace-aware. In the following table, the first * column shows the usual case for "http://www.w3.org/2000/xmlns/gml". The second column * shows the case if the DocumentBuilder was not aware of namespaces. The last column is * a case sometimes observed. * * ┌───────────────────┬─────────────────────────────────┬──────────────┬─────────────┐ * │ Node method │ Namespace (NS) aware │ Non NS-aware │ Other case │ * ├───────────────────┼─────────────────────────────────┼──────────────┼─────────────┤ * │ getNamespaceURI() │ "http://www.w3.org/2000/xmlns/" │ null │ "xmlns" │ * │ getLocalName() │ "gml" │ null │ "gml" │ * │ getNodeName() │ "xmlns:gml" │ "xmlns:gml" │ │ * └───────────────────┴─────────────────────────────────┴──────────────┴─────────────┘ * * By default, this block is not be executed. However if the user gave us Nodes that are * not namespace aware, then the `isIgnored(…)` method will try to parse the node name. */ name = expAttr.getNodeName(); } if (!isIgnored(ignoredAttributes, ns, name)) { final Node actAttr; if (ns == null) { actAttr = actualAttributes.getNamedItem(name); } else { actAttr = actualAttributes.getNamedItemNS(ns, name); } compareNode(expAttr, actAttr); } } } /** * Returns {@code true} if the given node or attribute shall be ignored. * * @param ignored the set of node or attribute fully qualified names to ignore. * @param ns the node or attribute namespace, or {@code null}. * @param name the node or attribute name. * @return {@code true} if the node or attribute shall be ignored. */ private static boolean isIgnored(final Set<String> ignored, String ns, final String name) { if (!ignored.isEmpty()) { if (ns == null) { /* * If there is no namespace, then the `name` argument should be the qualified name * (with a prefix). Example: "xsi:schemaLocation". We will look first for an exact * name match, then for a match after replacing the local name by "*". */ if (ignored.contains(name)) { return true; } final int s = name.indexOf(':'); if (s >= 1 && ignored.contains(name.substring(0, s+1) + '*')) { return true; } } else { /* * If there is a namespace (which is the usual case), perform the concatenation * with the name before to check in the collection of ignored attributes. */ final StringBuilder buffer = new StringBuilder(ns); int length = buffer.length(); if (length != 0 && buffer.charAt(length - 1) == '/') { buffer.setLength(--length); } /* * Check if the fully qualified attribute name is one of the attributes to ignore. * Typical example: "http://www.w3.org/2001/XMLSchema-instance:schemaLocation" */ buffer.append(':').append(name, name.indexOf(':') + 1, name.length()); if (ignored.contains(buffer.toString())) { return true; } /* * The given attribute does not appear explicitly in the set of attributes to ignore. * But maybe the user asked to ignore all attributes in the namespace. * Typical example: "http://www.w3.org/2000/xmlns:*" */ buffer.setLength(length + 1); if (ignored.contains(buffer.append('*').toString())) { return true; } } } return false; } /** * Returns the first sibling of the given node having a non-empty text content, or {@code null} * if none. This method first check the given node, then check all siblings. Attribute nodes are * ignored. * * @param node the node to check, or {@code null}. * @return the first node having a non-empty text content, or {@code null} if none. */ private Node firstNonEmptySibling(Node node) { for (; node != null; node = node.getNextSibling()) { if (!isIgnored(ignoredNodes, node.getNamespaceURI(), node.getNodeName())) { switch (node.getNodeType()) { // For attribute node, continue the search unconditionally. case Node.ATTRIBUTE_NODE: continue; // For text node, continue the search if the node is empty. case Node.TEXT_NODE: { final String text = Strings.trimOrNull(node.getTextContent()); if (text == null) { continue; } break; } // Ignore comment nodes only if requested. case Node.COMMENT_NODE: { if (ignoreComments) { continue; } break; } } // Found a node: stop the search. break; } } return node; } /** * Verifies that the text content of the given nodes are equal. * * @param expected the node that contains the expected text. * @param actual the node that contains the actual text to verify. */ protected void assertTextContentEquals(final Node expected, final Node actual) { assertPropertyEquals("textContent", expected.getTextContent(), actual.getTextContent(), expected, actual); } /** * Verifies that the given property (text or number) are equal, ignoring spaces. If they are * not equal, then an error message is formatted using the given property name and nodes. * * @param propertyName the name of the property being compared (typically "name", "namespace", etc.). * @param expected the property value from the expected node to compare. * @param actual the property value to compare to the expected one. * @param expectedNode the node from which the expected property has been fetched. * @param actualNode the node being compared to the expected node. */ protected void assertPropertyEquals(final String propertyName, Comparable<?> expected, Comparable<?> actual, final Node expectedNode, final Node actualNode) { expected = trim(expected); actual = trim(actual); if ((expected != actual) && (expected == null || !expected.equals(actual))) { // Before to declare a test failure, compares again as numerical values if possible. if (abs(doubleValue(expected) - doubleValue(actual)) <= tolerance) { return; } final String lineSeparator = System.lineSeparator(); final StringBuilder buffer = new StringBuilder(1024).append("Expected ") .append(propertyName).append(" \"") .append(expected).append("\" but got \"") .append(actual).append("\" for nodes:") .append(lineSeparator); formatErrorMessage(buffer, expectedNode, actualNode, lineSeparator); fail(buffer.toString()); } } /** * Trims the leading and trailing spaces in the given property * if it is actually a {@link String} object. */ private static Comparable<?> trim(final Comparable<?> property) { return (property instanceof String) ? (((String) property)).strip() : property; } /** * Parses the given text as a number. If the given text is null or cannot be parsed, * returns {@code NaN}. This is used only if a {@linkplain #tolerance} threshold greater * than zero has been provided. */ private static double doubleValue(final Comparable<?> property) { if (property instanceof Number n) { return n.doubleValue(); } if (property instanceof CharSequence) try { return Double.parseDouble(property.toString()); } catch (NumberFormatException e) { // Ignore, as specified in method javadoc. } return Double.NaN; } /** * Formats an error message for a node mismatch. The message will contain a string * representation of the expected and actual node. * * @param expected the expected node. * @param result the actual node. * @return an error message containing the expected and actual node. */ protected String formatErrorMessage(final Node expected, final Node result) { final String lineSeparator = System.lineSeparator(); final StringBuilder buffer = new StringBuilder(256).append("Nodes are not equal:").append(lineSeparator); formatErrorMessage(buffer, expected, result, lineSeparator); return buffer.toString(); } /** * Formats in the given buffer an error message for a node mismatch. * * @param lineSeparator the platform-specific line separator. */ private static void formatErrorMessage(final StringBuilder buffer, final Node expected, final Node result, final String lineSeparator) { formatNode(buffer.append("Expected node: "), expected, lineSeparator); formatNode(buffer.append("Actual node: "), result, lineSeparator); buffer.append("Expected hierarchy:").append(lineSeparator); final List<String> hierarchy = formatHierarchy(buffer, expected, null, lineSeparator); buffer.append("Actual hierarchy:").append(lineSeparator); formatHierarchy(buffer, result, hierarchy, lineSeparator); } /** * Appends to the given buffer the string representation of the node hierarchy. * The first line will contain the root of the tree. Other lines will contain * the child down in the hierarchy until the given node, inclusive. * * <p>This method formats only a summary if the hierarchy is equal to the expected one.</p> * * @param buffer the buffer in which to append the formatted hierarchy. * @param node the node for which to format the parents. * @param expected the expected hierarchy, or {@code null} if unknown. * @param lineSeparator the platform-specific line separator. */ private static List<String> formatHierarchy(final StringBuilder buffer, Node node, final List<String> expected, final String lineSeparator) { final List<String> hierarchy = new ArrayList<>(); while (node != null) { hierarchy.add(node.getNodeName()); if (node instanceof Attr t) { node = t.getOwnerElement(); } else { node = node.getParentNode(); } } if (hierarchy.equals(expected)) { buffer.append("└─Same as expected").append(lineSeparator); } else { int indent = 2; for (int i=hierarchy.size(); --i>=0;) { for (int j=indent; --j>=0;) { buffer.append(NO_BREAK_SPACE); } buffer.append("└─").append(hierarchy.get(i)).append(lineSeparator); indent += 4; } } return hierarchy; } /** * Appends to the given buffer a string representation of the given node. * The string representation is terminated by a line feed. * * @param buffer the buffer in which to append the formatted node. * @param node the node to format. * @param lineSeparator the platform-specific line separator. */ private static void formatNode(final StringBuilder buffer, final Node node, final String lineSeparator) { if (node == null) { buffer.append("(no node)").append(lineSeparator); return; } /* * Format the text content, together with the text content of the * child if there is exactly one child. */ final String ns = node.getNamespaceURI(); if (ns != null) { buffer.append('{').append(ns).append('}'); } buffer.append(node.getNodeName()); boolean hasText = appendTextContent(buffer, node); final NodeList children = node.getChildNodes(); int numChildren = 0; if (children != null) { numChildren = children.getLength(); if (numChildren == 1 && !hasText) { hasText = appendTextContent(buffer, children.item(0)); } } /* * Format the number of children and the number of attributes, if any. */ String separator = " ("; if (numChildren != 0) { buffer.append(separator).append("nbChild=").append(numChildren); separator = ", "; } final NamedNodeMap atts = node.getAttributes(); int numAtts = 0; if (atts != null) { numAtts = atts.getLength(); if (numAtts != 0) { buffer.append(separator).append("nbAtt=").append(numAtts); separator = ", "; } } if (!separator.equals(" (")) { buffer.append(')'); } /* * Format all attributes, if any. */ separator = " ["; for (int i=0; i<numAtts; i++) { buffer.append(separator).append(atts.item(i)); separator = ", "; } if (!separator.equals(" [")) { buffer.append(']'); } buffer.append(lineSeparator); } /** * Appends the text content of the given node only if the node is an instance of {@link Text} * or related type ({@link CDATASection}, {@link Comment} or {@link ProcessingInstruction}). * Otherwise this method does nothing. * * @param buffer the buffer in which to append text content. * @param node the node for which to append text content. * @return {@code true} if a text has been formatted. */ private static boolean appendTextContent(final StringBuilder buffer, final Node node) { if (node instanceof Text || node instanceof Comment || node instanceof CDATASection || node instanceof ProcessingInstruction) { buffer.append("=\"").append(node.getTextContent()).append('"'); return true; } return false; } }
googleapis/google-cloud-java
37,027
java-dialogflow-cx/google-cloud-dialogflow-cx/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/DeploymentsClient.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.v3beta1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.dialogflow.cx.v3beta1.stub.DeploymentsStub; import com.google.cloud.dialogflow.cx.v3beta1.stub.DeploymentsStubSettings; 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 for managing * [Deployments][google.cloud.dialogflow.cx.v3beta1.Deployment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * DeploymentName name = * DeploymentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"); * Deployment response = deploymentsClient.getDeployment(name); * } * }</pre> * * <p>Note: close() needs to be called on the DeploymentsClient 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> ListDeployments</td> * <td><p> Returns the list of all deployments in the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment].</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> listDeployments(ListDeploymentsRequest 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> listDeployments(EnvironmentName parent) * <li><p> listDeployments(String parent) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> listDeploymentsPagedCallable() * <li><p> listDeploymentsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GetDeployment</td> * <td><p> Retrieves the specified [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment].</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> getDeployment(GetDeploymentRequest 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> getDeployment(DeploymentName name) * <li><p> getDeployment(String name) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getDeploymentCallable() * </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 DeploymentsSettings 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 * DeploymentsSettings deploymentsSettings = * DeploymentsSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * DeploymentsClient deploymentsClient = DeploymentsClient.create(deploymentsSettings); * }</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 * DeploymentsSettings deploymentsSettings = * DeploymentsSettings.newBuilder().setEndpoint(myEndpoint).build(); * DeploymentsClient deploymentsClient = DeploymentsClient.create(deploymentsSettings); * }</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 * DeploymentsSettings deploymentsSettings = DeploymentsSettings.newHttpJsonBuilder().build(); * DeploymentsClient deploymentsClient = DeploymentsClient.create(deploymentsSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class DeploymentsClient implements BackgroundResource { private final DeploymentsSettings settings; private final DeploymentsStub stub; /** Constructs an instance of DeploymentsClient with default settings. */ public static final DeploymentsClient create() throws IOException { return create(DeploymentsSettings.newBuilder().build()); } /** * Constructs an instance of DeploymentsClient, 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 DeploymentsClient create(DeploymentsSettings settings) throws IOException { return new DeploymentsClient(settings); } /** * Constructs an instance of DeploymentsClient, using the given stub for making calls. This is for * advanced usage - prefer using create(DeploymentsSettings). */ public static final DeploymentsClient create(DeploymentsStub stub) { return new DeploymentsClient(stub); } /** * Constructs an instance of DeploymentsClient, 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 DeploymentsClient(DeploymentsSettings settings) throws IOException { this.settings = settings; this.stub = ((DeploymentsStubSettings) settings.getStubSettings()).createStub(); } protected DeploymentsClient(DeploymentsStub stub) { this.settings = null; this.stub = stub; } public final DeploymentsSettings getSettings() { return settings; } public DeploymentsStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of all deployments in the specified * [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * EnvironmentName parent = * EnvironmentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"); * for (Deployment element : deploymentsClient.listDeployments(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] to * list all environments for. Format: * `projects/&lt;ProjectID&gt;/locations/&lt;LocationID&gt;/agents/&lt;AgentID&gt;/environments/&lt;EnvironmentID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListDeploymentsPagedResponse listDeployments(EnvironmentName parent) { ListDeploymentsRequest request = ListDeploymentsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listDeployments(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of all deployments in the specified * [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * String parent = * EnvironmentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]").toString(); * for (Deployment element : deploymentsClient.listDeployments(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] to * list all environments for. Format: * `projects/&lt;ProjectID&gt;/locations/&lt;LocationID&gt;/agents/&lt;AgentID&gt;/environments/&lt;EnvironmentID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListDeploymentsPagedResponse listDeployments(String parent) { ListDeploymentsRequest request = ListDeploymentsRequest.newBuilder().setParent(parent).build(); return listDeployments(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of all deployments in the specified * [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * ListDeploymentsRequest request = * ListDeploymentsRequest.newBuilder() * .setParent( * EnvironmentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]") * .toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Deployment element : deploymentsClient.listDeployments(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 ListDeploymentsPagedResponse listDeployments(ListDeploymentsRequest request) { return listDeploymentsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of all deployments in the specified * [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * ListDeploymentsRequest request = * ListDeploymentsRequest.newBuilder() * .setParent( * EnvironmentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]") * .toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Deployment> future = * deploymentsClient.listDeploymentsPagedCallable().futureCall(request); * // Do something. * for (Deployment element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListDeploymentsRequest, ListDeploymentsPagedResponse> listDeploymentsPagedCallable() { return stub.listDeploymentsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of all deployments in the specified * [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * ListDeploymentsRequest request = * ListDeploymentsRequest.newBuilder() * .setParent( * EnvironmentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]") * .toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListDeploymentsResponse response = * deploymentsClient.listDeploymentsCallable().call(request); * for (Deployment element : response.getDeploymentsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListDeploymentsRequest, ListDeploymentsResponse> listDeploymentsCallable() { return stub.listDeploymentsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * DeploymentName name = * DeploymentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]"); * Deployment response = deploymentsClient.getDeployment(name); * } * }</pre> * * @param name Required. The name of the * [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. Format: * `projects/&lt;ProjectID&gt;/locations/&lt;LocationID&gt;/agents/&lt;AgentID&gt;/environments/&lt;EnvironmentID&gt;/deployments/&lt;DeploymentID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Deployment getDeployment(DeploymentName name) { GetDeploymentRequest request = GetDeploymentRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getDeployment(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * String name = * DeploymentName.of("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]") * .toString(); * Deployment response = deploymentsClient.getDeployment(name); * } * }</pre> * * @param name Required. The name of the * [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. Format: * `projects/&lt;ProjectID&gt;/locations/&lt;LocationID&gt;/agents/&lt;AgentID&gt;/environments/&lt;EnvironmentID&gt;/deployments/&lt;DeploymentID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Deployment getDeployment(String name) { GetDeploymentRequest request = GetDeploymentRequest.newBuilder().setName(name).build(); return getDeployment(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * GetDeploymentRequest request = * GetDeploymentRequest.newBuilder() * .setName( * DeploymentName.of( * "[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]") * .toString()) * .build(); * Deployment response = deploymentsClient.getDeployment(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 Deployment getDeployment(GetDeploymentRequest request) { return getDeploymentCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified [Deployment][google.cloud.dialogflow.cx.v3beta1.Deployment]. * * <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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * GetDeploymentRequest request = * GetDeploymentRequest.newBuilder() * .setName( * DeploymentName.of( * "[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]", "[DEPLOYMENT]") * .toString()) * .build(); * ApiFuture<Deployment> future = deploymentsClient.getDeploymentCallable().futureCall(request); * // Do something. * Deployment response = future.get(); * } * }</pre> */ public final UnaryCallable<GetDeploymentRequest, Deployment> getDeploymentCallable() { return stub.getDeploymentCallable(); } // 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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Location element : deploymentsClient.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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Location> future = * deploymentsClient.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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListLocationsResponse response = deploymentsClient.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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * Location response = deploymentsClient.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 (DeploymentsClient deploymentsClient = DeploymentsClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * ApiFuture<Location> future = deploymentsClient.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 ListDeploymentsPagedResponse extends AbstractPagedListResponse< ListDeploymentsRequest, ListDeploymentsResponse, Deployment, ListDeploymentsPage, ListDeploymentsFixedSizeCollection> { public static ApiFuture<ListDeploymentsPagedResponse> createAsync( PageContext<ListDeploymentsRequest, ListDeploymentsResponse, Deployment> context, ApiFuture<ListDeploymentsResponse> futureResponse) { ApiFuture<ListDeploymentsPage> futurePage = ListDeploymentsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListDeploymentsPagedResponse(input), MoreExecutors.directExecutor()); } private ListDeploymentsPagedResponse(ListDeploymentsPage page) { super(page, ListDeploymentsFixedSizeCollection.createEmptyCollection()); } } public static class ListDeploymentsPage extends AbstractPage< ListDeploymentsRequest, ListDeploymentsResponse, Deployment, ListDeploymentsPage> { private ListDeploymentsPage( PageContext<ListDeploymentsRequest, ListDeploymentsResponse, Deployment> context, ListDeploymentsResponse response) { super(context, response); } private static ListDeploymentsPage createEmptyPage() { return new ListDeploymentsPage(null, null); } @Override protected ListDeploymentsPage createPage( PageContext<ListDeploymentsRequest, ListDeploymentsResponse, Deployment> context, ListDeploymentsResponse response) { return new ListDeploymentsPage(context, response); } @Override public ApiFuture<ListDeploymentsPage> createPageAsync( PageContext<ListDeploymentsRequest, ListDeploymentsResponse, Deployment> context, ApiFuture<ListDeploymentsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListDeploymentsFixedSizeCollection extends AbstractFixedSizeCollection< ListDeploymentsRequest, ListDeploymentsResponse, Deployment, ListDeploymentsPage, ListDeploymentsFixedSizeCollection> { private ListDeploymentsFixedSizeCollection( List<ListDeploymentsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListDeploymentsFixedSizeCollection createEmptyCollection() { return new ListDeploymentsFixedSizeCollection(null, 0); } @Override protected ListDeploymentsFixedSizeCollection createCollection( List<ListDeploymentsPage> pages, int collectionSize) { return new ListDeploymentsFixedSizeCollection(pages, collectionSize); } } 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
36,869
java-apihub/proto-google-cloud-apihub-v1/src/main/java/com/google/cloud/apihub/v1/ListDependenciesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/apihub/v1/apihub_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.apihub.v1; /** * * * <pre> * The * [ListDependencies][google.cloud.apihub.v1.ApiHubDependencies.ListDependencies] * method's response. * </pre> * * Protobuf type {@code google.cloud.apihub.v1.ListDependenciesResponse} */ public final class ListDependenciesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.apihub.v1.ListDependenciesResponse) ListDependenciesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDependenciesResponse.newBuilder() to construct. private ListDependenciesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDependenciesResponse() { dependencies_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDependenciesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDependenciesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDependenciesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apihub.v1.ListDependenciesResponse.class, com.google.cloud.apihub.v1.ListDependenciesResponse.Builder.class); } public static final int DEPENDENCIES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.apihub.v1.Dependency> dependencies_; /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.apihub.v1.Dependency> getDependenciesList() { return dependencies_; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.apihub.v1.DependencyOrBuilder> getDependenciesOrBuilderList() { return dependencies_; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ @java.lang.Override public int getDependenciesCount() { return dependencies_.size(); } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ @java.lang.Override public com.google.cloud.apihub.v1.Dependency getDependencies(int index) { return dependencies_.get(index); } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ @java.lang.Override public com.google.cloud.apihub.v1.DependencyOrBuilder getDependenciesOrBuilder(int index) { return dependencies_.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 < dependencies_.size(); i++) { output.writeMessage(1, dependencies_.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 < dependencies_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dependencies_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.apihub.v1.ListDependenciesResponse)) { return super.equals(obj); } com.google.cloud.apihub.v1.ListDependenciesResponse other = (com.google.cloud.apihub.v1.ListDependenciesResponse) obj; if (!getDependenciesList().equals(other.getDependenciesList())) 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 (getDependenciesCount() > 0) { hash = (37 * hash) + DEPENDENCIES_FIELD_NUMBER; hash = (53 * hash) + getDependenciesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.ListDependenciesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.apihub.v1.ListDependenciesResponse 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 * [ListDependencies][google.cloud.apihub.v1.ApiHubDependencies.ListDependencies] * method's response. * </pre> * * Protobuf type {@code google.cloud.apihub.v1.ListDependenciesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.apihub.v1.ListDependenciesResponse) com.google.cloud.apihub.v1.ListDependenciesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDependenciesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDependenciesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apihub.v1.ListDependenciesResponse.class, com.google.cloud.apihub.v1.ListDependenciesResponse.Builder.class); } // Construct using com.google.cloud.apihub.v1.ListDependenciesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dependenciesBuilder_ == null) { dependencies_ = java.util.Collections.emptyList(); } else { dependencies_ = null; dependenciesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDependenciesResponse_descriptor; } @java.lang.Override public com.google.cloud.apihub.v1.ListDependenciesResponse getDefaultInstanceForType() { return com.google.cloud.apihub.v1.ListDependenciesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.apihub.v1.ListDependenciesResponse build() { com.google.cloud.apihub.v1.ListDependenciesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.apihub.v1.ListDependenciesResponse buildPartial() { com.google.cloud.apihub.v1.ListDependenciesResponse result = new com.google.cloud.apihub.v1.ListDependenciesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.apihub.v1.ListDependenciesResponse result) { if (dependenciesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dependencies_ = java.util.Collections.unmodifiableList(dependencies_); bitField0_ = (bitField0_ & ~0x00000001); } result.dependencies_ = dependencies_; } else { result.dependencies_ = dependenciesBuilder_.build(); } } private void buildPartial0(com.google.cloud.apihub.v1.ListDependenciesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.apihub.v1.ListDependenciesResponse) { return mergeFrom((com.google.cloud.apihub.v1.ListDependenciesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.apihub.v1.ListDependenciesResponse other) { if (other == com.google.cloud.apihub.v1.ListDependenciesResponse.getDefaultInstance()) return this; if (dependenciesBuilder_ == null) { if (!other.dependencies_.isEmpty()) { if (dependencies_.isEmpty()) { dependencies_ = other.dependencies_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDependenciesIsMutable(); dependencies_.addAll(other.dependencies_); } onChanged(); } } else { if (!other.dependencies_.isEmpty()) { if (dependenciesBuilder_.isEmpty()) { dependenciesBuilder_.dispose(); dependenciesBuilder_ = null; dependencies_ = other.dependencies_; bitField0_ = (bitField0_ & ~0x00000001); dependenciesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDependenciesFieldBuilder() : null; } else { dependenciesBuilder_.addAllMessages(other.dependencies_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.apihub.v1.Dependency m = input.readMessage( com.google.cloud.apihub.v1.Dependency.parser(), extensionRegistry); if (dependenciesBuilder_ == null) { ensureDependenciesIsMutable(); dependencies_.add(m); } else { dependenciesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.apihub.v1.Dependency> dependencies_ = java.util.Collections.emptyList(); private void ensureDependenciesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dependencies_ = new java.util.ArrayList<com.google.cloud.apihub.v1.Dependency>(dependencies_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apihub.v1.Dependency, com.google.cloud.apihub.v1.Dependency.Builder, com.google.cloud.apihub.v1.DependencyOrBuilder> dependenciesBuilder_; /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public java.util.List<com.google.cloud.apihub.v1.Dependency> getDependenciesList() { if (dependenciesBuilder_ == null) { return java.util.Collections.unmodifiableList(dependencies_); } else { return dependenciesBuilder_.getMessageList(); } } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public int getDependenciesCount() { if (dependenciesBuilder_ == null) { return dependencies_.size(); } else { return dependenciesBuilder_.getCount(); } } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public com.google.cloud.apihub.v1.Dependency getDependencies(int index) { if (dependenciesBuilder_ == null) { return dependencies_.get(index); } else { return dependenciesBuilder_.getMessage(index); } } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder setDependencies(int index, com.google.cloud.apihub.v1.Dependency value) { if (dependenciesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDependenciesIsMutable(); dependencies_.set(index, value); onChanged(); } else { dependenciesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder setDependencies( int index, com.google.cloud.apihub.v1.Dependency.Builder builderForValue) { if (dependenciesBuilder_ == null) { ensureDependenciesIsMutable(); dependencies_.set(index, builderForValue.build()); onChanged(); } else { dependenciesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder addDependencies(com.google.cloud.apihub.v1.Dependency value) { if (dependenciesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDependenciesIsMutable(); dependencies_.add(value); onChanged(); } else { dependenciesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder addDependencies(int index, com.google.cloud.apihub.v1.Dependency value) { if (dependenciesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDependenciesIsMutable(); dependencies_.add(index, value); onChanged(); } else { dependenciesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder addDependencies(com.google.cloud.apihub.v1.Dependency.Builder builderForValue) { if (dependenciesBuilder_ == null) { ensureDependenciesIsMutable(); dependencies_.add(builderForValue.build()); onChanged(); } else { dependenciesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder addDependencies( int index, com.google.cloud.apihub.v1.Dependency.Builder builderForValue) { if (dependenciesBuilder_ == null) { ensureDependenciesIsMutable(); dependencies_.add(index, builderForValue.build()); onChanged(); } else { dependenciesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder addAllDependencies( java.lang.Iterable<? extends com.google.cloud.apihub.v1.Dependency> values) { if (dependenciesBuilder_ == null) { ensureDependenciesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dependencies_); onChanged(); } else { dependenciesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder clearDependencies() { if (dependenciesBuilder_ == null) { dependencies_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dependenciesBuilder_.clear(); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public Builder removeDependencies(int index) { if (dependenciesBuilder_ == null) { ensureDependenciesIsMutable(); dependencies_.remove(index); onChanged(); } else { dependenciesBuilder_.remove(index); } return this; } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public com.google.cloud.apihub.v1.Dependency.Builder getDependenciesBuilder(int index) { return getDependenciesFieldBuilder().getBuilder(index); } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public com.google.cloud.apihub.v1.DependencyOrBuilder getDependenciesOrBuilder(int index) { if (dependenciesBuilder_ == null) { return dependencies_.get(index); } else { return dependenciesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public java.util.List<? extends com.google.cloud.apihub.v1.DependencyOrBuilder> getDependenciesOrBuilderList() { if (dependenciesBuilder_ != null) { return dependenciesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dependencies_); } } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public com.google.cloud.apihub.v1.Dependency.Builder addDependenciesBuilder() { return getDependenciesFieldBuilder() .addBuilder(com.google.cloud.apihub.v1.Dependency.getDefaultInstance()); } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public com.google.cloud.apihub.v1.Dependency.Builder addDependenciesBuilder(int index) { return getDependenciesFieldBuilder() .addBuilder(index, com.google.cloud.apihub.v1.Dependency.getDefaultInstance()); } /** * * * <pre> * The dependency resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Dependency dependencies = 1;</code> */ public java.util.List<com.google.cloud.apihub.v1.Dependency.Builder> getDependenciesBuilderList() { return getDependenciesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apihub.v1.Dependency, com.google.cloud.apihub.v1.Dependency.Builder, com.google.cloud.apihub.v1.DependencyOrBuilder> getDependenciesFieldBuilder() { if (dependenciesBuilder_ == null) { dependenciesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apihub.v1.Dependency, com.google.cloud.apihub.v1.Dependency.Builder, com.google.cloud.apihub.v1.DependencyOrBuilder>( dependencies_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dependencies_ = null; } return dependenciesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.apihub.v1.ListDependenciesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.apihub.v1.ListDependenciesResponse) private static final com.google.cloud.apihub.v1.ListDependenciesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.apihub.v1.ListDependenciesResponse(); } public static com.google.cloud.apihub.v1.ListDependenciesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDependenciesResponse> PARSER = new com.google.protobuf.AbstractParser<ListDependenciesResponse>() { @java.lang.Override public ListDependenciesResponse 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<ListDependenciesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDependenciesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.apihub.v1.ListDependenciesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/myfaces
36,876
impl/src/test/java/org/apache/myfaces/view/facelets/tag/composite/CompositeComponentTestCase.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.tag.composite; import java.io.StringWriter; import jakarta.el.MethodExpression; import jakarta.el.ValueExpression; import jakarta.faces.application.Resource; import jakarta.faces.component.UICommand; import jakarta.faces.component.UIComponent; import jakarta.faces.component.UIInput; import jakarta.faces.component.UINamingContainer; import jakarta.faces.component.UIOutput; import jakarta.faces.component.UIViewRoot; import jakarta.faces.component.html.HtmlCommandLink; import jakarta.faces.component.html.HtmlGraphicImage; import jakarta.faces.component.html.HtmlOutputText; import jakarta.faces.event.PostRenderViewEvent; import jakarta.faces.event.PreRenderViewEvent; import org.apache.myfaces.config.NamedEventManager; import org.apache.myfaces.config.RuntimeConfig; import org.apache.myfaces.config.webparameters.MyfacesConfig; import org.apache.myfaces.test.mock.MockResponseWriter; import org.apache.myfaces.test.utils.HtmlCheckAttributesUtil; import org.apache.myfaces.test.utils.HtmlRenderedAttr; import org.apache.myfaces.view.facelets.AbstractFaceletTestCase; import org.apache.myfaces.view.facelets.bean.HelloWorld; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class CompositeComponentTestCase extends AbstractFaceletTestCase { @Override protected void setupComponents() throws Exception { super.setupComponents(); application.addComponent(CompositeTestComponent.class.getName(), CompositeTestComponent.class.getName()); } @Override protected void setUpServletObjects() throws Exception { super.setUpServletObjects(); servletContext.addInitParameter("jakarta.faces.FACELETS_LIBRARIES", "/test-facelet.taglib.xml"); } @Override protected void setUpExternalContext() throws Exception { super.setUpExternalContext(); RuntimeConfig.getCurrentInstance(externalContext).setNamedEventManager(new NamedEventManager()); } /** * Test if a child component inside composite component template is * rendered. * * @throws Exception */ @Test public void testSimpleCompositeComponent() throws Exception { UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleComposite.xhtml"); UIComponent panelGroup = root.findComponent("testGroup"); Assertions.assertNotNull(panelGroup); UINamingContainer compositeComponent = (UINamingContainer) panelGroup.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UIOutput text = (UIOutput) compositeComponent.getFacet(UIComponent.COMPOSITE_FACET_NAME).findComponent("text"); Assertions.assertNotNull(text); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent.encodeAll(facesContext); sw.flush(); HtmlRenderedAttr[] attrs = new HtmlRenderedAttr[]{ new HtmlRenderedAttr("value") }; HtmlCheckAttributesUtil.checkRenderedAttributes(attrs, sw.toString()); } /** * Test simple attribute resolution (not set, default, normal use case). * * @throws Exception */ @Test public void testSimpleCompositeAttribute() throws Exception { UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleAttribute.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); HtmlOutputText text1 = (HtmlOutputText) facet1.findComponent("text"); Assertions.assertNotNull(text1); compositeComponent1.pushComponentToEL(facesContext, compositeComponent1); facet1.pushComponentToEL(facesContext, facet1); text1.pushComponentToEL(facesContext, text1); //set on tag Assertions.assertEquals("class1", text1.getStyleClass()); //set as default Assertions.assertEquals("background:red", text1.getStyle()); //Check coercion of attribute using type value Assertions.assertEquals(5, compositeComponent1.getAttributes().get("index")); //Check default coercion ValueExpression ve = facesContext.getApplication().getExpressionFactory().createValueExpression( facesContext.getELContext(), "#{cc.attrs.cols}", Object.class); Assertions.assertEquals(1, (int) ve.getValue(facesContext.getELContext())); text1.popComponentFromEL(facesContext); facet1.popComponentFromEL(facesContext); compositeComponent1.popComponentFromEL(facesContext); UIComponent panelGroup2 = root.findComponent("testGroup2"); Assertions.assertNotNull(panelGroup2); UINamingContainer compositeComponent2 = (UINamingContainer) panelGroup2.getChildren().get(0); Assertions.assertNotNull(compositeComponent2); UIComponent facet2 = compositeComponent2.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet2); HtmlOutputText text2 = (HtmlOutputText) facet2.findComponent("text"); Assertions.assertNotNull(text2); compositeComponent2.pushComponentToEL(facesContext, compositeComponent2); facet2.pushComponentToEL(facesContext, facet2); text2.pushComponentToEL(facesContext, text2); //set on tag Assertions.assertEquals("background:green", text2.getStyle()); // not set, should return null, but since there is a ValueExpression indirection, // coercing rules apply here, so null is converted as "" Assertions.assertEquals("", text2.getStyleClass()); text2.popComponentFromEL(facesContext); facet2.popComponentFromEL(facesContext); compositeComponent2.popComponentFromEL(facesContext); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent1.encodeAll(facesContext); sw.flush(); HtmlRenderedAttr[] attrs = new HtmlRenderedAttr[]{ new HtmlRenderedAttr("style") }; HtmlCheckAttributesUtil.checkRenderedAttributes(attrs, sw.toString()); } @Test public void testSimpleCompositeAttributeMethodExpression() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleAttributeMethodExpression.xhtml"); UIComponent form = root.findComponent("testForm1"); Assertions.assertNotNull(form); UINamingContainer compositeComponent = (UINamingContainer) form.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UICommand button = (UICommand) compositeComponent.findComponent("button"); Assertions.assertNotNull(button); Assertions.assertEquals("#{helloWorldBean.send}", button.getActionExpression().getExpressionString()); Assertions.assertEquals("#{helloWorldBean.send}", ((MethodExpression)compositeComponent.getAttributes().get("metodo")).getExpressionString()); Assertions.assertNull(button.getAttributes().get("metodo")); UICommand link = (UICommand) compositeComponent.findComponent("link"); Assertions.assertNotNull(link); Assertions.assertEquals(1, link.getActionListeners().length); UIInput input = (UIInput) compositeComponent.findComponent("input"); Assertions.assertNotNull(input); Assertions.assertEquals(1, input.getValidators().length); Assertions.assertEquals(1, input.getValueChangeListeners().length); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); //root.encodeAll(facesContext); //compositeComponent.encodeAll(facesContext); //sw.flush(); //System.out.print(sw.toString()); } @Test public void testSimpleActionSource() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleActionSource.xhtml"); UIComponent form = root.findComponent("testForm1"); Assertions.assertNotNull(form); UINamingContainer compositeComponent = (UINamingContainer) form.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UICommand button = (UICommand) compositeComponent.findComponent("button"); Assertions.assertNotNull(button); Assertions.assertEquals(3, button.getActionListeners().length); //StringWriter sw = new StringWriter(); //MockResponseWriter mrw = new MockResponseWriter(sw); //facesContext.setResponseWriter(mrw); //root.encodeAll(facesContext); //sw.flush(); //System.out.print(sw.toString()); } @Test public void testSimpleValueHolder() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleValueHolder.xhtml"); UIComponent form = root.findComponent("testForm1"); Assertions.assertNotNull(form); UINamingContainer compositeComponent = (UINamingContainer) form.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UIOutput text = (UIOutput) compositeComponent.findComponent("text"); Assertions.assertNotNull(text); Assertions.assertNotNull(text.getConverter()); //Assertions.assertEquals(2, button.getActionListeners().length); //StringWriter sw = new StringWriter(); //MockResponseWriter mrw = new MockResponseWriter(sw); //facesContext.setResponseWriter(mrw); //root.encodeAll(facesContext); //sw.flush(); //System.out.print(sw.toString()); } @Test public void testCompositeActionSource() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeActionSource.xhtml"); UIComponent form = root.findComponent("testForm1"); Assertions.assertNotNull(form); UINamingContainer compositeComponent = (UINamingContainer) form.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UINamingContainer compositeComponent2 = (UINamingContainer) compositeComponent.findComponent("button3"); Assertions.assertNotNull(compositeComponent2); UICommand button = (UICommand) compositeComponent2.findComponent("button"); Assertions.assertNotNull(button); //One added in testCompositeActionSource, the other one //inside compositeActionSource.xhtml Assertions.assertEquals(2, button.getActionListeners().length); //StringWriter sw = new StringWriter(); //MockResponseWriter mrw = new MockResponseWriter(sw); //facesContext.setResponseWriter(mrw); //root.encodeAll(facesContext); //sw.flush(); //System.out.print(sw.toString()); } @Test public void testSimpleInsertChildren() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleInsertChildren.xhtml"); /* UIComponent form = root.findComponent("testForm1"); Assertions.assertNotNull(form); UINamingContainer compositeComponent = (UINamingContainer) form.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UINamingContainer compositeComponent2 = (UINamingContainer) compositeComponent.findComponent("button3"); Assertions.assertNotNull(compositeComponent2); UICommand button = (UICommand) compositeComponent2.findComponent("button"); Assertions.assertNotNull(button); */ StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); root.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("Hello")); Assertions.assertTrue(resp.contains("Leonardo")); Assertions.assertTrue(resp.contains("Alfredo")); Assertions.assertTrue(resp.contains("Uribe")); Assertions.assertTrue(resp.contains("Sayonara")); //System.out.print(sw.toString()); } @Test public void testSimpleInsertChildrenAjax() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleInsertChildrenAjax.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); HtmlCommandLink link = (HtmlCommandLink) facet1.findComponent("link"); Assertions.assertNotNull(link); Assertions.assertEquals(1, link.getClientBehaviors().size()); Assertions.assertEquals(1, link.getClientBehaviors().get(link.getDefaultEventName()).size()); /* StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); root.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); */ //System.out.print(sw.toString()); } @Test public void testSimpleInsertChildrenAjax2() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleInsertChildrenAjax2.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); HtmlCommandLink link = (HtmlCommandLink) compositeComponent1.findComponent("link"); Assertions.assertNotNull(link); Assertions.assertEquals(1, link.getClientBehaviors().size()); Assertions.assertEquals(1, link.getClientBehaviors().get(link.getDefaultEventName()).size()); /* StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); root.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); */ //System.out.print(sw.toString()); } @Test public void testSimpleInsertChildrenNoAjax() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleInsertChildrenNoAjax.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); HtmlCommandLink link = (HtmlCommandLink) facet1.findComponent("link"); Assertions.assertNotNull(link); Assertions.assertEquals(0, link.getClientBehaviors().size()); /* StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); root.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); */ //System.out.print(sw.toString()); } @Test public void testCompositeInsertChildren() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertChildren.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); facet1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("ALFA")); Assertions.assertTrue(resp.contains("BETA")); Assertions.assertTrue(resp.contains("GAMMA")); Assertions.assertTrue(resp.contains("OMEGA")); } @Test public void testCompositeInsertChildrenPreserveTemplateSlot() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertChildren2.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); facet1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("ALFA")); Assertions.assertTrue(resp.contains("BETA")); Assertions.assertTrue(resp.contains("GAMMA")); Assertions.assertTrue(resp.contains("OMEGA")); } @Test public void testCompositeInsertChildren3() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertChildren3.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); panelGroup1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("ALFA")); Assertions.assertTrue(resp.contains("BETA")); Assertions.assertTrue(resp.contains("GAMMA")); Assertions.assertTrue(resp.contains("OMEGA")); } @Test public void testCompositeInsertChildren4() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertChildren4.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); //UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); //Assertions.assertNotNull(compositeComponent1); //UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); //Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); panelGroup1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("ALFA")); Assertions.assertTrue(resp.contains("BETA")); Assertions.assertTrue(resp.contains("GAMMA")); Assertions.assertTrue(resp.contains("OMEGA")); } @Test public void testCompositeInsertChildren5() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertChildren5.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); //UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); //Assertions.assertNotNull(compositeComponent1); //UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); //Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); panelGroup1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("ALFA")); Assertions.assertTrue(resp.contains("BETA")); Assertions.assertTrue(resp.contains("GAMMA")); Assertions.assertTrue(resp.contains("OMEGA")); } @Test public void testCompositeInsertChildren6() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertChildren6.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); //UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); //Assertions.assertNotNull(compositeComponent1); //UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); //Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); panelGroup1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("ALFA")); Assertions.assertTrue(resp.contains("BETA")); Assertions.assertTrue(resp.contains("GAMMA")); Assertions.assertTrue(resp.contains("OMEGA")); } @Test public void testCompositeInsertFacet() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertFacet.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); UINamingContainer compositeComponent2 = (UINamingContainer) facet1.getChildren().get(0); Assertions.assertNotNull(compositeComponent2); UIComponent facet2 = compositeComponent2.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet2); Assertions.assertEquals(1,facet2.getChildCount()); UIOutput targetComp = (UIOutput) facet2.getChildren().get(0); UIComponent insertedFacet = targetComp.getFacet("header"); Assertions.assertNotNull(insertedFacet); } @Test public void testCompositeInsertFacetChildren() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeInsertFacetChildren.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); UINamingContainer compositeComponent2 = (UINamingContainer) facet1.getChildren().get(0); Assertions.assertNotNull(compositeComponent2); UIComponent facet2 = compositeComponent2.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet2); Assertions.assertEquals(3,facet2.getChildCount()); UIComponent insertedFacet = facet2.getChildren().get(1).getFacet("header"); Assertions.assertNotNull(insertedFacet); } @Test public void testSimpleRenderFacet() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleRenderFacet.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("HELLO")); Assertions.assertTrue(resp.contains("WORLD")); } @Test public void testSimpleFEvent() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleFEvent.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); CompositeTestComponent compositeComponent1 = (CompositeTestComponent) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); Assertions.assertTrue((Boolean) compositeComponent1.getAttributes().get("postAddToViewCallback"), "postAddToViewCallback should be called"); /* StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("HELLO")); Assertions.assertTrue(resp.contains("WORLD")); */ } @Test public void testSimpleFEvent2() throws Exception { HelloWorld helloWorld = new HelloWorld(); facesContext.getExternalContext().getRequestMap().put("helloWorldBean", helloWorld); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleFEvent2.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); CompositeTestComponent compositeComponent1 = (CompositeTestComponent) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); application.publishEvent(facesContext, PreRenderViewEvent.class, root); Assertions.assertTrue((Boolean) compositeComponent1.getAttributes().get("preRenderViewCallback"), "preRenderViewCallback should be called"); application.publishEvent(facesContext, PostRenderViewEvent.class, root); Assertions.assertTrue((Boolean) compositeComponent1.getAttributes().get("postRenderViewCallback"), "postRenderViewCallback should be called"); /* StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent1.encodeAll(facesContext); sw.flush(); String resp = sw.toString(); Assertions.assertTrue(resp.contains("HELLO")); Assertions.assertTrue(resp.contains("WORLD")); */ } @Test public void testsCompositeRefVE() throws Exception { servletContext.addInitParameter( MyfacesConfig.CACHE_EL_EXPRESSIONS, "always"); UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testCompositeRefVE.xhtml"); UIComponent panelGroup1 = root.findComponent("testGroup1"); Assertions.assertNotNull(panelGroup1); UINamingContainer compositeComponent1 = (UINamingContainer) panelGroup1.getChildren().get(0); Assertions.assertNotNull(compositeComponent1); UIComponent facet1 = compositeComponent1.getFacet(UIComponent.COMPOSITE_FACET_NAME); Assertions.assertNotNull(facet1); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent1.encodeAll(facesContext); sw.flush(); Assertions.assertTrue(sw.toString().contains("success"), "Error when rendering" + sw.toString()); } @Test public void testSimpleThisResourceReference() throws Exception { UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testSimpleThisResourceReference.xhtml"); UINamingContainer compositeComponent = (UINamingContainer) root.findComponent("cc1"); Assertions.assertNotNull(compositeComponent); HtmlGraphicImage gi = (HtmlGraphicImage) compositeComponent.getFacet(UIComponent.COMPOSITE_FACET_NAME).findComponent("gi"); Assertions.assertNotNull(gi); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent.encodeAll(facesContext); sw.flush(); String result = sw.toString(); Resource resource = facesContext.getApplication().getResourceHandler().createResource("logo_mini.jpg", "testComposite"); Assertions.assertNotNull(resource); Assertions.assertTrue(result.contains(resource.getRequestPath())); } @Test public void testComponentFromResourceId() throws Exception { UIViewRoot root = facesContext.getViewRoot(); vdl.buildView(facesContext, root, "testComponentFromResourceId.xhtml"); UIComponent panelGroup = root.findComponent("testGroup"); Assertions.assertNotNull(panelGroup); UINamingContainer compositeComponent = (UINamingContainer) panelGroup.getChildren().get(0); Assertions.assertNotNull(compositeComponent); UIOutput text = (UIOutput) compositeComponent.getFacet(UIComponent.COMPOSITE_FACET_NAME).findComponent("text"); Assertions.assertNotNull(text); StringWriter sw = new StringWriter(); MockResponseWriter mrw = new MockResponseWriter(sw); facesContext.setResponseWriter(mrw); compositeComponent.encodeAll(facesContext); sw.flush(); HtmlRenderedAttr[] attrs = new HtmlRenderedAttr[]{ new HtmlRenderedAttr("value") }; HtmlCheckAttributesUtil.checkRenderedAttributes(attrs, sw.toString()); } }
openjdk/jmc
34,903
application/org.openjdk.jmc.flightrecorder.flamegraph/src/main/java/org/openjdk/jmc/flightrecorder/flamegraph/views/FlamegraphSwingView.java
/* * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2023, 2025, Datadog, Inc. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at https://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.flightrecorder.flamegraph.views; import static java.util.Collections.emptySet; import static java.util.Collections.reverseOrder; import static java.util.Map.Entry.comparingByValue; import static java.util.stream.Collectors.toMap; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_FLAME_GRAPH; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_ICICLE_GRAPH; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_JPEG_IMAGE; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_PNG_IMAGE; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_PRINT; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_RESET_ZOOM; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_SAVE_AS; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_SAVE_FLAME_GRAPH_AS; import static org.openjdk.jmc.flightrecorder.flamegraph.Messages.FLAMEVIEW_TOGGLE_MINIMAP; import static org.openjdk.jmc.flightrecorder.flamegraph.MessagesUtils.getFlamegraphMessage; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.BufferedOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.imageio.ImageIO; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ResourceLocator; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.DefaultToolTip; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IMemento; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.openjdk.jmc.common.item.IAttribute; import org.openjdk.jmc.common.item.IItemCollection; import org.openjdk.jmc.common.item.ItemCollectionToolkit; import org.openjdk.jmc.common.item.ItemFilters; import org.openjdk.jmc.common.unit.IQuantity; import org.openjdk.jmc.common.util.FormatToolkit; import org.openjdk.jmc.common.util.Pair; import org.openjdk.jmc.flightrecorder.flamegraph.FlamegraphImages; import org.openjdk.jmc.flightrecorder.stacktrace.FrameSeparator; import org.openjdk.jmc.flightrecorder.stacktrace.tree.Node; import org.openjdk.jmc.flightrecorder.stacktrace.tree.StacktraceTreeModel; import org.openjdk.jmc.flightrecorder.ui.FlightRecorderUI; import org.openjdk.jmc.flightrecorder.ui.common.AttributeSelection; import org.openjdk.jmc.flightrecorder.ui.messages.internal.Messages; import org.openjdk.jmc.ui.CoreImages; import org.openjdk.jmc.ui.common.util.AdapterUtil; import org.openjdk.jmc.ui.handlers.MCContextMenuManager; import org.openjdk.jmc.ui.misc.DisplayToolkit; import io.github.bric3.fireplace.core.ui.Colors; import io.github.bric3.fireplace.flamegraph.ColorMapper; import io.github.bric3.fireplace.flamegraph.DimmingFrameColorProvider; import io.github.bric3.fireplace.flamegraph.FlamegraphImage; import io.github.bric3.fireplace.flamegraph.FlamegraphView; import io.github.bric3.fireplace.flamegraph.FlamegraphView.HoverListener; import io.github.bric3.fireplace.flamegraph.FrameBox; import io.github.bric3.fireplace.flamegraph.FrameFontProvider; import io.github.bric3.fireplace.flamegraph.FrameModel; import io.github.bric3.fireplace.flamegraph.FrameTextsProvider; import io.github.bric3.fireplace.flamegraph.animation.ZoomAnimation; import io.github.bric3.fireplace.swt_awt.EmbeddingComposite; import io.github.bric3.fireplace.swt_awt.SWT_AWTBridge; public class FlamegraphSwingView extends ViewPart implements ISelectionListener { private static final String DIR_ICONS = "icons/"; //$NON-NLS-1$ private static final String PLUGIN_ID = "org.openjdk.jmc.flightrecorder.flamegraph"; //$NON-NLS-1$ private static final String ATTRIBUTE_SELECTION_SEPARATOR_ID = "AttrSelectionSep"; //$NON-NLS-1$ private static final int MODEL_EXECUTOR_THREADS_NUMBER = 3; private static final ExecutorService MODEL_EXECUTOR = Executors.newFixedThreadPool(MODEL_EXECUTOR_THREADS_NUMBER, new ThreadFactory() { private final ThreadGroup group = new ThreadGroup("FlamegraphModelCalculationGroup"); //$NON-NLS-1$ private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { var t = new Thread(group, r, "FlamegraphModelCalculation-" + counter.getAndIncrement()); //$NON-NLS-1$ t.setDaemon(true); return t; } }); private static final String OUTLINE_VIEW_ID = "org.eclipse.ui.views.ContentOutline"; private static final String JVM_BROWSER_VIEW_ID = "org.openjdk.jmc.browser.views.JVMBrowserView"; private FrameSeparator frameSeparator; private EmbeddingComposite embeddingComposite; private FlamegraphView<Node> flamegraphView; private ExportAction[] exportActions; private boolean threadRootAtTop = true; private boolean icicleViewActive = true; private IItemCollection currentItems; private volatile ModelState modelState = ModelState.NONE; private ModelRebuildRunnable modelRebuildRunnable; private IAttribute<IQuantity> currentAttribute; private AttributeSelection attributeSelection; private IToolBarManager toolBar; private boolean traverseAlready = false; private enum GroupActionType { THREAD_ROOT(Messages.STACKTRACE_VIEW_THREAD_ROOT, IAction.AS_RADIO_BUTTON, CoreImages.THREAD), LAST_FRAME(Messages.STACKTRACE_VIEW_LAST_FRAME, IAction.AS_RADIO_BUTTON, CoreImages.METHOD_NON_OPTIMIZED), ICICLE_GRAPH(getFlamegraphMessage(FLAMEVIEW_ICICLE_GRAPH), IAction.AS_RADIO_BUTTON, flamegraphImageDescriptor( FlamegraphImages.ICON_ICICLE_FLIP)), FLAME_GRAPH(getFlamegraphMessage(FLAMEVIEW_FLAME_GRAPH), IAction.AS_RADIO_BUTTON, flamegraphImageDescriptor( FlamegraphImages.ICON_FLAME_FLIP)); private final String message; private final int action; private final ImageDescriptor imageDescriptor; private GroupActionType(String message, int action, ImageDescriptor imageDescriptor) { this.message = message; this.action = action; this.imageDescriptor = imageDescriptor; } } private enum ModelState { NOT_STARTED, STARTED, FINISHED, NONE; } private class GroupByAction extends Action { private final GroupActionType actionType; GroupByAction(GroupActionType actionType) { super(actionType.message, actionType.action); this.actionType = actionType; setToolTipText(actionType.message); setImageDescriptor(actionType.imageDescriptor); setChecked(GroupActionType.THREAD_ROOT.equals(actionType) == threadRootAtTop); } @Override public void run() { boolean newValue = isChecked() == GroupActionType.THREAD_ROOT.equals(actionType); if (newValue != threadRootAtTop) { threadRootAtTop = newValue; triggerRebuildTask(currentItems); } } } private class ViewModeAction extends Action { private final GroupActionType actionType; ViewModeAction(GroupActionType actionType) { super(actionType.message, actionType.action); this.actionType = actionType; setToolTipText(actionType.message); setImageDescriptor(actionType.imageDescriptor); setChecked(GroupActionType.ICICLE_GRAPH.equals(actionType) == icicleViewActive); } @Override public void run() { icicleViewActive = GroupActionType.ICICLE_GRAPH.equals(actionType); SwingUtilities.invokeLater(() -> flamegraphView .setMode(icicleViewActive ? FlamegraphView.Mode.ICICLEGRAPH : FlamegraphView.Mode.FLAMEGRAPH)); } } private class ToggleMinimapAction extends Action { private ToggleMinimapAction() { super(getFlamegraphMessage(FLAMEVIEW_TOGGLE_MINIMAP), IAction.AS_CHECK_BOX); setToolTipText(getFlamegraphMessage(FLAMEVIEW_TOGGLE_MINIMAP)); setImageDescriptor(flamegraphImageDescriptor(FlamegraphImages.ICON_MINIMAP)); setChecked(false); } @Override public void run() { boolean toggleMinimap = !flamegraphView.isShowMinimap(); SwingUtilities.invokeLater(() -> flamegraphView.setShowMinimap(toggleMinimap)); setChecked(toggleMinimap); } } private class ResetZoomAction extends Action { private ResetZoomAction() { super(getFlamegraphMessage(FLAMEVIEW_RESET_ZOOM), IAction.AS_PUSH_BUTTON); setToolTipText(getFlamegraphMessage(FLAMEVIEW_RESET_ZOOM)); setImageDescriptor(flamegraphImageDescriptor(FlamegraphImages.ICON_RESET_ZOOM)); } @Override public void run() { SwingUtilities.invokeLater(() -> flamegraphView.resetZoom()); } } private enum ExportActionType { SAVE_AS(getFlamegraphMessage(FLAMEVIEW_SAVE_AS), IAction.AS_PUSH_BUTTON, PlatformUI.getWorkbench() .getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_SAVEAS_EDIT), PlatformUI.getWorkbench() .getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_SAVEAS_EDIT_DISABLED)), PRINT(getFlamegraphMessage(FLAMEVIEW_PRINT), IAction.AS_PUSH_BUTTON, PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT), PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT_DISABLED)); private final String message; private final int action; private final ImageDescriptor imageDescriptor; private final ImageDescriptor disabledImageDescriptor; private ExportActionType(String message, int action, ImageDescriptor imageDescriptor, ImageDescriptor disabledImageDescriptor) { this.message = message; this.action = action; this.imageDescriptor = imageDescriptor; this.disabledImageDescriptor = disabledImageDescriptor; } } private class ExportAction extends Action { private final ExportActionType actionType; private ExportAction(ExportActionType actionType) { super(actionType.message, actionType.action); this.actionType = actionType; setToolTipText(actionType.message); setImageDescriptor(actionType.imageDescriptor); setDisabledImageDescriptor(actionType.disabledImageDescriptor); } @Override public void run() { switch (actionType) { case SAVE_AS: Executors.newSingleThreadExecutor().execute(FlamegraphSwingView.this::saveFlamegraph); break; case PRINT: // not supported break; } } } private static class ModelRebuildRunnable implements Runnable { private final FlamegraphSwingView view; private final IItemCollection items; private final IAttribute<IQuantity> attribute; private volatile boolean isInvalid; private ModelRebuildRunnable(FlamegraphSwingView view, IItemCollection items, IAttribute<IQuantity> attribute) { this.view = view; this.items = items; this.attribute = attribute; } private void setInvalid() { this.isInvalid = true; } @Override public void run() { final var start = System.currentTimeMillis(); try { view.modelState = ModelState.STARTED; if (isInvalid) { return; } var filteredItems = items; if (attribute != null) { filteredItems = filteredItems.apply(ItemFilters.hasAttribute(attribute)); } var treeModel = new StacktraceTreeModel(filteredItems, view.frameSeparator, !view.threadRootAtTop, attribute, () -> isInvalid); if (isInvalid) { return; } var rootFrameDescription = createRootNodeDescription(items); var frameBoxList = convert(treeModel); if (!isInvalid) { view.modelState = ModelState.FINISHED; view.setModel(items, frameBoxList, rootFrameDescription); DisplayToolkit.inDisplayThread().execute(() -> { var attributeList = AttributeSelection.extractAttributes(items); String attrName = attribute != null ? attribute.getName() : null; view.createAttributeSelection(attrName, attributeList); }); } } finally { final var duration = Duration.ofMillis(System.currentTimeMillis() - start); FlightRecorderUI.getDefault().getLogger() .info("model rebuild with isInvalid:" + isInvalid + " in " + duration); } } private static List<FrameBox<Node>> convert(StacktraceTreeModel model) { var nodes = new ArrayList<FrameBox<Node>>(); FrameBox.flattenAndCalculateCoordinate(nodes, model.getRoot(), Node::getChildren, Node::getCumulativeWeight, node -> node.getChildren().stream().mapToDouble(Node::getCumulativeWeight).sum(), 0.0d, 1.0d, 0); return nodes; } private static String createRootNodeDescription(IItemCollection items) { var freq = eventTypeFrequency(items); // root => 51917 events of 1 type: Method Profiling Sample[51917], long totalEvents = freq.values().stream().mapToLong(Long::longValue).sum(); if (totalEvents == 0) { return "Stack Trace not available"; } var description = new StringBuilder(totalEvents + " event(s) of " + freq.size() + " type(s): "); int i = 0; for (var e : freq.entrySet()) { description.append(e.getKey()).append("[").append(e.getValue()).append("]"); if (i < freq.size() - 1 && i < 3) { description.append(", "); } if (i >= 3) { description.append(", ..."); break; } i++; } return description.toString(); } private static Map<String, Long> eventTypeFrequency(IItemCollection items) { var eventCountByType = new HashMap<String, Long>(); for (var eventIterable : items) { if (eventIterable.getItemCount() == 0) { continue; } eventCountByType.compute(eventIterable.getType().getName(), (k, v) -> (v == null ? 0 : v) + eventIterable.getItemCount()); } // sort the map in ascending order of values return eventCountByType.entrySet().stream().sorted(reverseOrder(comparingByValue())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); } } private void createAttributeSelection(String attrName, Collection<Pair<String, IAttribute<IQuantity>>> items) { if (attributeSelection != null) { toolBar.remove(attributeSelection.getId()); } attributeSelection = new AttributeSelection(items, attrName, this::getCurrentAttribute, this::setCurrentAttribute, () -> triggerRebuildTask(currentItems)); toolBar.insertAfter(ATTRIBUTE_SELECTION_SEPARATOR_ID, attributeSelection); toolBar.update(true); } @Override public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); frameSeparator = new FrameSeparator(FrameSeparator.FrameCategorization.METHOD, false); var siteMenu = site.getActionBars().getMenuManager(); { siteMenu.add(new Separator(MCContextMenuManager.GROUP_TOP)); siteMenu.add(new Separator(MCContextMenuManager.GROUP_VIEWER_SETUP)); } toolBar = site.getActionBars().getToolBarManager(); { toolBar.add(new ResetZoomAction()); toolBar.add(new ToggleMinimapAction()); toolBar.add(new Separator()); var groupByFlamegraphActions = new ViewModeAction[] {new ViewModeAction(GroupActionType.FLAME_GRAPH), new ViewModeAction(GroupActionType.ICICLE_GRAPH)}; Stream.of(groupByFlamegraphActions).forEach(toolBar::add); toolBar.add(new Separator()); var groupByActions = new GroupByAction[] {new GroupByAction(GroupActionType.LAST_FRAME), new GroupByAction(GroupActionType.THREAD_ROOT)}; Stream.of(groupByActions).forEach(toolBar::add); toolBar.add(new Separator()); exportActions = new ExportAction[] {new ExportAction(ExportActionType.SAVE_AS)}; Stream.of(exportActions).forEach((action) -> action.setEnabled(false)); Stream.of(exportActions).forEach(toolBar::add); toolBar.add(new Separator(ATTRIBUTE_SELECTION_SEPARATOR_ID)); createAttributeSelection(null, Collections.emptyList()); } getSite().getPage().addSelectionListener(this); } @Override public void dispose() { getSite().getPage().removeSelectionListener(this); super.dispose(); } @Override public void createPartControl(Composite parent) { var container = new SashForm(parent, SWT.HORIZONTAL); embeddingComposite = new EmbeddingComposite(container); container.setMaximizedControl(embeddingComposite); // done here to avoid SWT complain about wrong thread var bgColorAwtColor = SWT_AWTBridge.toAWTColor(container.getBackground()); var tooltip = new StyledToolTip(embeddingComposite, ToolTip.NO_RECREATE, true); { tooltip.setPopupDelay(500); tooltip.setShift(new Point(10, 5)); } embeddingComposite.init(() -> { var panel = new JPanel(new BorderLayout()); { var searchControl = createSearchControl(); searchControl.setBackground(bgColorAwtColor); panel.add(searchControl, BorderLayout.NORTH); } { flamegraphView = createFlameGraph(embeddingComposite, tooltip); new ZoomAnimation().install(flamegraphView); JComponent flamegraphComponent = flamegraphView.component; flamegraphComponent.setBackground(bgColorAwtColor); // Adding focus traversal and key listener for flamegraph component setFocusTraversalProperties(flamegraphComponent); addKeyListenerForFwdFocusToSWT(flamegraphComponent); panel.add(flamegraphComponent, BorderLayout.CENTER); } panel.setBackground(bgColorAwtColor); // Adding focus traversal and key listener for main panel setFocusTraversalProperties(panel); addKeyListenerForBkwdFocusToSWT(panel); return panel; }); } @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection instanceof IStructuredSelection) { var first = ((IStructuredSelection) selection).getFirstElement(); var items = AdapterUtil.getAdapter(first, IItemCollection.class); if (items == null) { triggerRebuildTask(ItemCollectionToolkit.build(Stream.empty())); } else if (!items.equals(currentItems)) { triggerRebuildTask(items); } } } @Override public void setFocus() { embeddingComposite.setFocus(); } private JComponent createSearchControl() { var searchField = new JTextField("", 60); searchField.addActionListener(e -> { var searched = searchField.getText(); if (searched.isBlank() && flamegraphView != null) { flamegraphView.highlightFrames(emptySet(), searched); return; } CompletableFuture.runAsync(() -> { try { if (flamegraphView == null) { return; } var matches = flamegraphView.getFrames().stream().filter(frame -> { var method = frame.actualNode.getFrame().getMethod(); return (method.getMethodName().contains(searched) || method.getType().getTypeName().contains(searched) || method.getType().getPackage().getName() != null && method.getType().getPackage().getName().contains(searched)) || method.getType().getPackage().getModule() != null && method.getType().getPackage().getModule().getName() != null && method.getType().getPackage().getModule().getName().contains(searched) || method.getFormalDescriptor().replace('/', '.').contains(searched); }).collect(Collectors.toCollection(() -> Collections.newSetFromMap(new IdentityHashMap<>()))); flamegraphView.highlightFrames(matches, searched); } catch (Exception ex) { ex.printStackTrace(); } }); }); // Adding focus traversal and key listener for search field setFocusTraversalProperties(searchField); addKeyListener(searchField); var panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel.add(new JLabel(getFlamegraphMessage("FLAMEVIEW_SEARCH"))); // Adding focus traversal and key listener for panel setFocusTraversalProperties(panel); addKeyListener(panel); panel.add(searchField); return panel; } /** * This method sets the focus from swing to SWT. If outline page is active focus will be set to * outline view else to JVM Browser */ private void setFocusBackToSWT() { Display.getDefault().syncExec(new Runnable() { public void run() { IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IViewPart outlineView = activePage.showView(OUTLINE_VIEW_ID); if (activePage.getActiveEditor() != null) { outlineView.setFocus(); } else { IViewPart showView = activePage.showView(JVM_BROWSER_VIEW_ID); showView.setFocus(); } } catch (PartInitException e) { FlightRecorderUI.getDefault().getLogger().log(Level.INFO, "Failed to set focus", e); //$NON-NLS-1$ } } }); } /** * Adding key listener to transfer focus forward or backward based on 'TAB' or 'Shift + TAB' */ private void addKeyListener(JComponent comp) { comp.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_TAB) { if ((e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0) { e.getComponent().transferFocusBackward(); } else { e.getComponent().transferFocus(); } e.consume(); } } }); } /** * Adding key listener and checking if all the swing components are already cycled (Fwd) once. * On completion of swing component cycle transferring focus back to SWT. */ private void addKeyListenerForFwdFocusToSWT(JComponent comp) { comp.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_TAB) { if ((e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0) { e.getComponent().transferFocusBackward(); } else { traverseAlready = !traverseAlready; // If already cycled (Fwd) within swing component then transfer the focus back to SWT if (traverseAlready) { setFocusBackToSWT(); } else { e.getComponent().transferFocus(); } } e.consume(); } } }); } /** * Adding key listener and checking if all the swing components are already cycled (Bkwd) once. * On completion of swing component cycle transferring focus back to SWT. */ private void addKeyListenerForBkwdFocusToSWT(JComponent comp) { comp.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_TAB) { if ((e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0) { traverseAlready = !traverseAlready; // If already cycled (Bkwd) within swing component then transfer the focus back to SWT if (traverseAlready) { setFocusBackToSWT(); } else { e.getComponent().transferFocusBackward(); } } else { e.getComponent().transferFocus(); } e.consume(); } } }); } /** * Setting the focus traversal properties. */ private void setFocusTraversalProperties(JComponent comp) { comp.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.emptySet()); comp.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.emptySet()); comp.setFocusable(true); comp.setFocusTraversalKeysEnabled(true); } private FlamegraphView<Node> createFlameGraph(Composite owner, DefaultToolTip tooltip) { var fg = new FlamegraphView<Node>(); fg.putClientProperty(FlamegraphView.SHOW_STATS, false); fg.setShowMinimap(false); fg.setRenderConfiguration( FrameTextsProvider.of( frame -> frame.isRoot() ? "" : frame.actualNode.getFrame().getHumanReadableShortString(), frame -> frame.isRoot() ? "" : FormatToolkit.getHumanReadable(frame.actualNode.getFrame().getMethod(), false, false, false, false, true, false), frame -> frame.isRoot() ? "" : frame.actualNode.getFrame().getMethod().getMethodName()), new DimmingFrameColorProvider<>(frame -> ColorMapper.ofObjectHashUsing(Colors.Palette.DATADOG.colors()) .apply(frame.actualNode.getFrame().getMethod().getType().getPackage())), FrameFontProvider.defaultFontProvider()); fg.setHoverListener(new HoverListener<Node>() { @Override public void onStopHover(FrameBox<Node> frameBox, Rectangle frameRect, MouseEvent mouseEvent) { Display.getDefault().asyncExec(tooltip::hide); } @Override public void onFrameHover(FrameBox<Node> frameBox, Rectangle frameRect, MouseEvent mouseEvent) { // This code knows too much about Flamegraph but given tooltips // will probably evolve it may be too early to refactor it var scrollPane = (JScrollPane) mouseEvent.getComponent(); var canvas = scrollPane.getViewport().getView(); var pointOnCanvas = SwingUtilities.convertPoint(scrollPane, mouseEvent.getPoint(), canvas); pointOnCanvas.y = frameRect.y + frameRect.height; var componentPoint = SwingUtilities.convertPoint(canvas, pointOnCanvas, flamegraphView.component); if (frameBox.isRoot()) { return; } var method = frameBox.actualNode.getFrame().getMethod(); var escapedMethod = frameBox.actualNode.getFrame().getHumanReadableShortString().replace("<", "&lt;") .replace(">", "&gt;"); var sb = new StringBuilder().append("<form><p>").append("<b>").append(escapedMethod) .append("</b><br/>"); var packageName = method.getType().getPackage(); if (packageName != null) { sb.append(packageName).append("<br/>"); } sb.append("<hr/>Weight: ").append(frameBox.actualNode.getCumulativeWeight()).append("<br/>") .append("Type: ").append(frameBox.actualNode.getFrame().getType()).append("<br/>"); var bci = frameBox.actualNode.getFrame().getBCI(); if (bci != null) { sb.append("BCI: ").append(bci).append("<br/>"); } var frameLineNumber = frameBox.actualNode.getFrame().getFrameLineNumber(); if (frameLineNumber != null) { sb.append("Line number: ").append(frameLineNumber).append("<br/>"); } sb.append("</p></form>"); var text = sb.toString(); Display.getDefault().asyncExec(() -> { var control = Display.getDefault().getCursorControl(); if (Objects.equals(owner, control)) { tooltip.setText(text); tooltip.hide(); tooltip.show(SWT_AWTBridge.toSWTPoint(componentPoint)); } }); } }); return fg; } private void triggerRebuildTask(IItemCollection items) { // Release old model calculation before building a new if (modelRebuildRunnable != null) { modelRebuildRunnable.setInvalid(); } currentItems = items; modelState = ModelState.NOT_STARTED; modelRebuildRunnable = new ModelRebuildRunnable(this, items, currentAttribute); if (!modelRebuildRunnable.isInvalid) { MODEL_EXECUTOR.execute(modelRebuildRunnable); } } private IAttribute<IQuantity> getCurrentAttribute() { return currentAttribute; } private void setCurrentAttribute(IAttribute<IQuantity> attr) { currentAttribute = attr; } private void setModel( final IItemCollection items, final List<FrameBox<Node>> flatFrameList, String rootFrameDescription) { if (ModelState.FINISHED.equals(modelState) && items.equals(currentItems)) { SwingUtilities.invokeLater(() -> { flamegraphView.setModel(new FrameModel<>(rootFrameDescription, (frameA, frameB) -> Objects.equals(frameA.actualNode.getFrame(), frameB.actualNode.getFrame()), flatFrameList)); Display.getDefault().asyncExec(() -> { if (embeddingComposite.isDisposed()) { return; } Stream.of(exportActions).forEach((action) -> action.setEnabled(!flatFrameList.isEmpty())); }); }); } } private void saveFlamegraph() { var future = new CompletableFuture<Path>(); DisplayToolkit.inDisplayThread().execute(() -> { var fd = new FileDialog(embeddingComposite.getShell(), SWT.SAVE); fd.setText(getFlamegraphMessage(FLAMEVIEW_SAVE_FLAME_GRAPH_AS)); fd.setFilterNames(new String[] { getFlamegraphMessage(FLAMEVIEW_PNG_IMAGE), getFlamegraphMessage(FLAMEVIEW_JPEG_IMAGE) }); fd.setFilterExtensions(new String[] { "*.png", "*.jpg" }); //$NON-NLS-1$ //$NON-NLS-2$ fd.setFileName("flame_graph"); //$NON-NLS-1$ fd.setOverwrite(true); if (fd.open() == null) { future.cancel(true); return; } var fileName = fd.getFileName().toLowerCase(); // FIXME: FileDialog filterIndex returns -1 // (https://bugs.eclipse.org/bugs/show_bug.cgi?id=546256) if (!fileName.endsWith(".jpg") && !fileName.endsWith(".jpeg") && !fileName.endsWith(".png")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ future.completeExceptionally(new UnsupportedOperationException("Unsupported image format")); //$NON-NLS-1$ return; } future.complete(Paths.get(fd.getFilterPath(), fd.getFileName())); }); Supplier<RenderedImage> generator = () -> { var fgImage = new FlamegraphImage<>( FrameTextsProvider.of( frame -> frame.isRoot() ? "" : frame.actualNode.getFrame().getHumanReadableShortString(), //$NON-NLS-1$ frame -> frame.isRoot() ? "" //$NON-NLS-1$ : FormatToolkit.getHumanReadable(frame.actualNode.getFrame().getMethod(), false, false, false, false, true, false), frame -> frame.isRoot() ? "" : frame.actualNode.getFrame().getMethod().getMethodName()), //$NON-NLS-1$ new DimmingFrameColorProvider<Node>( frame -> ColorMapper.ofObjectHashUsing(Colors.Palette.DATADOG.colors()) .apply(frame.actualNode.getFrame().getMethod().getType().getPackage())), FrameFontProvider.defaultFontProvider()); return fgImage.generate(flamegraphView.getFrameModel(), flamegraphView.getMode(), 2000); }; Optional.of(future).map(f -> { try { return f.get(); } catch (CancellationException e) { // noop : model calculation is canceled when is still running } catch (InterruptedException | ExecutionException e) { FlightRecorderUI.getDefault().getLogger().log(Level.SEVERE, "Failed to save flame graph", e); //$NON-NLS-1$ } return null; }).ifPresent(destinationPath -> { // make spotbugs happy about NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE var type = Optional.ofNullable(destinationPath.getFileName()).map(p -> p.toString().toLowerCase()) .map(f -> switch (f.substring(f.lastIndexOf('.') + 1)) { // $NON-NLS-1$ case "jpeg", "jpg" -> //$NON-NLS-1$ //$NON-NLS-2$ "jpg"; //$NON-NLS-1$ case "png" -> //$NON-NLS-1$ "png"; //$NON-NLS-1$ default -> null; }).orElseThrow(() -> new IllegalStateException("Unhandled type for " + destinationPath)); try (var os = new BufferedOutputStream(Files.newOutputStream(destinationPath))) { var renderImg = generator.get(); var img = switch (type) { case "png" -> renderImg; case "jpg" -> { // JPG does not have an alpha channel, and ImageIO.write will simply write a 0 // byte file // to workaround this it is required to copy the image to a BufferedImage // without alpha channel var newBufferedImage = new BufferedImage(renderImg.getWidth(), renderImg.getHeight(), BufferedImage.TYPE_INT_RGB); renderImg.copyData(newBufferedImage.getRaster()); yield newBufferedImage; } default -> throw new IllegalStateException("Type is checked above"); }; ImageIO.write(img, type, os); } catch (IOException e) { FlightRecorderUI.getDefault().getLogger().log(Level.SEVERE, "Failed to save flame graph", e); //$NON-NLS-1$ } }); } private static ImageDescriptor flamegraphImageDescriptor(String iconName) { return ResourceLocator.imageDescriptorFromBundle(PLUGIN_ID, DIR_ICONS + iconName).orElse(null); // $NON-NLS-1$ } }
oracle/graal
37,271
substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/classinitialization/SimulateClassInitializerGraphDecoder.java
/* * Copyright (c) 2023, 2023, 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. */ /* * Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.classinitialization; import java.util.List; import org.graalvm.collections.EconomicMap; import org.graalvm.collections.EconomicSet; import org.graalvm.nativeimage.ImageSingletons; import com.oracle.graal.pointsto.BigBang; import com.oracle.graal.pointsto.heap.ImageHeapArray; import com.oracle.graal.pointsto.heap.ImageHeapConstant; import com.oracle.graal.pointsto.heap.ImageHeapInstance; import com.oracle.graal.pointsto.meta.AnalysisField; import com.oracle.graal.pointsto.meta.AnalysisType; import com.oracle.graal.pointsto.phases.InlineBeforeAnalysisGraphDecoder; import com.oracle.svm.core.classinitialization.EnsureClassInitializedNode; import com.oracle.svm.core.config.ObjectLayout; import com.oracle.svm.core.util.VMError; import com.oracle.svm.hosted.ameta.AnalysisConstantReflectionProvider; import com.oracle.svm.hosted.classinitialization.SimulateClassInitializerPolicy.SimulateClassInitializerInlineScope; import com.oracle.svm.hosted.fieldfolding.IsStaticFinalFieldInitializedNode; import com.oracle.svm.hosted.fieldfolding.MarkStaticFinalFieldInitializedNode; import jdk.graal.compiler.debug.DebugContext; import jdk.graal.compiler.graph.Node; import jdk.graal.compiler.nodes.AbstractBeginNode; import jdk.graal.compiler.nodes.ConstantNode; import jdk.graal.compiler.nodes.ControlSplitNode; import jdk.graal.compiler.nodes.StructuredGraph; import jdk.graal.compiler.nodes.ValueNode; import jdk.graal.compiler.nodes.extended.BoxNode; import jdk.graal.compiler.nodes.graphbuilderconf.LoopExplosionPlugin.LoopExplosionKind; import jdk.graal.compiler.nodes.java.AccessMonitorNode; import jdk.graal.compiler.nodes.java.LoadFieldNode; import jdk.graal.compiler.nodes.java.LoadIndexedNode; import jdk.graal.compiler.nodes.java.NewArrayNode; import jdk.graal.compiler.nodes.java.NewInstanceNode; import jdk.graal.compiler.nodes.java.NewMultiArrayNode; import jdk.graal.compiler.nodes.java.StoreFieldNode; import jdk.graal.compiler.nodes.java.StoreIndexedNode; import jdk.graal.compiler.nodes.virtual.AllocatedObjectNode; import jdk.graal.compiler.nodes.virtual.CommitAllocationNode; import jdk.graal.compiler.nodes.virtual.VirtualArrayNode; import jdk.graal.compiler.nodes.virtual.VirtualBoxingNode; import jdk.graal.compiler.nodes.virtual.VirtualInstanceNode; import jdk.graal.compiler.nodes.virtual.VirtualObjectNode; import jdk.graal.compiler.replacements.arraycopy.ArrayCopyNode; import jdk.graal.compiler.replacements.nodes.ObjectClone; import jdk.vm.ci.meta.JavaConstant; import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.MetaAccessProvider; import jdk.vm.ci.meta.PrimitiveConstant; import jdk.vm.ci.meta.ResolvedJavaMethod; /** * The graph decoder that performs the partial evaluation of a single class initializer and all * methods invoked by that class initializer. * * See {@link SimulateClassInitializerSupport} for an overview of class initializer simulation. */ public class SimulateClassInitializerGraphDecoder extends InlineBeforeAnalysisGraphDecoder { protected final SimulateClassInitializerSupport support; protected final SimulateClassInitializerClusterMember clusterMember; /** * Stored in a separate field because it is frequently accessed, so having a separate field * makes the code more readable. */ protected final MetaAccessProvider metaAccess; protected final EconomicMap<VirtualObjectNode, ImageHeapConstant> allVirtualObjects = EconomicMap.create(); protected final EconomicMap<AnalysisField, Object> currentStaticFields = EconomicMap.create(); protected final EconomicSet<ImageHeapConstant> currentActiveObjects = EconomicSet.create(); protected final EconomicMap<AnalysisField, Boolean> isStaticFinalFieldInitializedStates = EconomicMap.create(); protected SimulateClassInitializerGraphDecoder(BigBang bb, SimulateClassInitializerPolicy policy, SimulateClassInitializerClusterMember clusterMember, StructuredGraph graph) { super(bb, policy, graph, clusterMember.cluster.providers, _ -> LoopExplosionKind.FULL_UNROLL); this.support = clusterMember.cluster.support; this.clusterMember = clusterMember; this.metaAccess = providers.getMetaAccess(); } @Override public void decode(ResolvedJavaMethod classInitializer) { for (var f : classInitializer.getDeclaringClass().getStaticFields()) { var field = (AnalysisField) f; /* * The initial value (before any field store) of a static field in our own class is the * value coming from the constant pool attribute. */ var initialValue = field.getConstantValue(); if (initialValue == null) { initialValue = JavaConstant.defaultForKind(field.getStorageKind()); } currentStaticFields.put(field, initialValue); isStaticFinalFieldInitializedStates.put(field, Boolean.FALSE); } super.decode(classInitializer); } @Override protected void maybeAbortInlining(MethodScope ms, LoopScope loopScope, Node node) { InlineBeforeAnalysisMethodScope methodScope = cast(ms); if (node instanceof ControlSplitNode || node instanceof AccessMonitorNode) { if (support.collectAllReasons) { if (methodScope.isInlinedMethod()) { /* * We want to collect more reasons in the class initializer itself, so we abort * inlining of too complex methods. */ abortInlining(methodScope); return; } else if (loopScope.loopDepth == 0) { /* * We are in the class initializer itself, so we just continue decoding. Unless * we are in an unrolled loop, in which case we need to abort because otherwise * decoding can quickly explode the graph size. */ return; } } /* * Any control flow split means that our resulting class initializer cannot be * simulated, so we can do an early abort of the analysis. */ throw SimulateClassInitializerAbortException.doAbort(clusterMember, graph, node); } } @Override protected void checkLoopExplosionIteration(MethodScope methodScope, LoopScope loopScope) { if (loopScope.loopIteration > support.maxLoopIterations) { /* * Most loops that are not unrollable bail out of loop unrolling earlier when a * ControlSplitNode is appended. But for example an empty endless loop triggers this * check. */ throw SimulateClassInitializerAbortException.doAbort(clusterMember, graph, "Loop iteration count exceeding unrolling limit"); } } @Override protected Node handleFloatingNodeBeforeAdd(MethodScope methodScope, LoopScope loopScope, Node n) { Node node = n; if (node instanceof AllocatedObjectNode allocatedObjectNode) { node = handleAllocatedObjectNode(allocatedObjectNode); } return super.handleFloatingNodeBeforeAdd(methodScope, loopScope, node); } @Override protected Node doCanonicalizeFixedNode(InlineBeforeAnalysisMethodScope methodScope, LoopScope loopScope, Node initialNode) { Node node = super.doCanonicalizeFixedNode(methodScope, loopScope, initialNode); var countersScope = (SimulateClassInitializerInlineScope) methodScope.policyScope; if (node instanceof StoreFieldNode storeFieldNode) { node = handleStoreFieldNode(storeFieldNode); } else if (node instanceof LoadFieldNode loadFieldNode) { node = handleLoadFieldNode(loadFieldNode); } else if (node instanceof StoreIndexedNode storeIndexedNode) { node = handleStoreIndexedNode(storeIndexedNode); } else if (node instanceof LoadIndexedNode loadIndexedNode) { node = handleLoadIndexedNode(loadIndexedNode); } else if (node instanceof ArrayCopyNode arrayCopyNode) { node = handleArrayCopyNode(arrayCopyNode); } else if (node instanceof EnsureClassInitializedNode ensureClassInitializedNode) { node = handleEnsureClassInitializedNode(ensureClassInitializedNode); } else if (node instanceof IsStaticFinalFieldInitializedNode isStaticFinalFieldInitializedNode) { node = handleIsStaticFinalFieldInitializedNode(isStaticFinalFieldInitializedNode); } else if (node instanceof MarkStaticFinalFieldInitializedNode markStaticFinalFieldInitializedNode) { node = handleMarkStaticFinalFieldInitializedNode(markStaticFinalFieldInitializedNode); } else if (node instanceof AccessMonitorNode accessMonitorNode) { node = handleAccessMonitorNode(accessMonitorNode); } else if (node instanceof CommitAllocationNode commitAllocationNode) { handleCommitAllocationNode(countersScope, commitAllocationNode); } else if (node instanceof NewInstanceNode newInstanceNode) { node = handleNewInstanceNode(countersScope, newInstanceNode); } else if (node instanceof NewArrayNode newArrayNode) { node = handleNewArrayNode(countersScope, newArrayNode); } else if (node instanceof NewMultiArrayNode newMultiArrayNode) { node = handleNewMultiArrayNode(countersScope, newMultiArrayNode); } else if (node instanceof BoxNode boxNode) { node = handleBoxNode(boxNode); } else if (node instanceof ObjectClone objectClone) { node = handleObjectClone(countersScope, objectClone); } if (node instanceof AbstractBeginNode && node.predecessor() instanceof ControlSplitNode) { /* * It is not possible to do a flow-sensitive analysis during partial evaluation, so * after every control flow split we need to re-set our information about fields and * objects. But this is only necessary in the "collect all reasons" mode, i.e., normally * we abort the analysis. */ if (!support.collectAllReasons) { throw SimulateClassInitializerAbortException.doAbort(clusterMember, graph, node.predecessor()); } currentActiveObjects.clear(); currentStaticFields.clear(); isStaticFinalFieldInitializedStates.clear(); } return node; } private Node handleStoreFieldNode(StoreFieldNode node) { var field = (AnalysisField) node.field(); if (field.isStatic()) { currentStaticFields.put(field, node.value()); } else { var object = asActiveImageHeapInstance(node.object()); var value = node.value().asJavaConstant(); if (object != null && value != null) { object.setFieldValue(field, adaptForImageHeap(value, field.getStorageKind())); return null; } } return node; } private Node handleLoadFieldNode(LoadFieldNode node) { var field = (AnalysisField) node.field(); if (field.isStatic()) { var currentValue = currentStaticFields.get(field); if (currentValue instanceof ValueNode currentValueNode) { return currentValueNode; } else if (currentValue instanceof JavaConstant currentConstant) { return ConstantNode.forConstant(currentConstant, metaAccess); } assert currentValue == null : "Unexpected static field value: " + currentValue; ConstantNode canonicalized = support.tryCanonicalize(bb, node); if (canonicalized != null) { return canonicalized; } } else { var object = asActiveImageHeapInstance(node.object()); if (object != null) { var currentValue = (JavaConstant) object.getFieldValue(field); return ConstantNode.forConstant(currentValue, metaAccess); } } var intrinsified = support.fieldValueInterceptionSupport.tryIntrinsifyFieldLoad(providers, node); if (intrinsified != null) { return intrinsified; } return node; } private Node handleStoreIndexedNode(StoreIndexedNode node) { var array = asActiveImageHeapArray(node.array()); var value = node.value().asJavaConstant(); int idx = asIntegerOrMinusOne(node.index()); if (array != null && value != null && idx >= 0 && idx < array.getLength()) { var componentType = array.getType().getComponentType(); if (node.elementKind().isPrimitive() || value.isNull() || componentType.isAssignableFrom(((ImageHeapConstant) value).getType())) { array.setElement(idx, adaptForImageHeap(value, componentType.getStorageKind())); return null; } } return node; } private Node handleLoadIndexedNode(LoadIndexedNode node) { var array = asActiveImageHeapArray(node.array()); int idx = asIntegerOrMinusOne(node.index()); if (array != null && idx >= 0 && idx < array.getLength()) { var currentValue = (JavaConstant) array.getElement(idx); return ConstantNode.forConstant(currentValue, metaAccess); } return node; } private Node handleArrayCopyNode(ArrayCopyNode node) { if (handleArrayCopy(asActiveImageHeapArray(node.getSource()), asIntegerOrMinusOne(node.getSourcePosition()), asActiveImageHeapArray(node.getDestination()), asIntegerOrMinusOne(node.getDestinationPosition()), asIntegerOrMinusOne(node.getLength()))) { return null; } return node; } protected boolean handleArrayCopy(ImageHeapArray source, int sourcePos, ImageHeapArray dest, int destPos, int length) { if (source == null || sourcePos < 0 || sourcePos >= source.getLength() || dest == null || destPos < 0 || destPos >= dest.getLength() || length < 0 || sourcePos > source.getLength() - length || destPos > dest.getLength() - length) { return false; } var sourceComponentType = source.getType().getComponentType(); var destComponentType = dest.getType().getComponentType(); if (sourceComponentType.getJavaKind() != destComponentType.getJavaKind()) { return false; } if (destComponentType.getJavaKind() == JavaKind.Object && !destComponentType.isJavaLangObject() && !sourceComponentType.equals(destComponentType)) { for (int i = 0; i < length; i++) { var elementValue = (JavaConstant) source.getElement(sourcePos + i); if (elementValue.isNonNull()) { var elementValueType = ((ImageHeapConstant) elementValue).getType(); if (!destComponentType.isAssignableFrom(elementValueType)) { return false; } } } } /* All checks passed, we can now copy array elements. */ if (source == dest && sourcePos < destPos) { /* Must copy backwards to avoid losing elements. */ for (int i = length - 1; i >= 0; i--) { dest.setElement(destPos + i, (JavaConstant) source.getElement(sourcePos + i)); } } else { for (int i = 0; i < length; i++) { dest.setElement(destPos + i, (JavaConstant) source.getElement(sourcePos + i)); } } return true; } private Node handleEnsureClassInitializedNode(EnsureClassInitializedNode node) { var aConstantReflection = (AnalysisConstantReflectionProvider) providers.getConstantReflection(); var classInitType = (AnalysisType) node.constantTypeOrNull(aConstantReflection); if (classInitType != null) { if (support.trySimulateClassInitializer(graph.getDebug(), classInitType, clusterMember) && !aConstantReflection.initializationCheckRequired(classInitType)) { /* Class is already simulated initialized, no need for a run-time check. */ return null; } var classInitTypeMember = clusterMember.cluster.clusterMembers.get(classInitType); if (classInitTypeMember != null && !classInitTypeMember.status.published) { /* * The class is part of the same cycle as our class. We optimistically remove the * initialization check, which is correct if the whole cycle can be simulated. If * the cycle cannot be simulated, then this graph with the optimistic assumption * will be discarded. */ clusterMember.dependencies.add(classInitTypeMember); return null; } } return node; } private Node handleIsStaticFinalFieldInitializedNode(IsStaticFinalFieldInitializedNode node) { var field = (AnalysisField) node.getField(); var isStaticFinalFieldInitialized = isStaticFinalFieldInitializedStates.get(field); if (isStaticFinalFieldInitialized != null) { return ConstantNode.forBoolean(isStaticFinalFieldInitialized); } if (support.trySimulateClassInitializer(graph.getDebug(), field.getDeclaringClass(), clusterMember)) { return ConstantNode.forBoolean(true); } return node; } private Node handleMarkStaticFinalFieldInitializedNode(MarkStaticFinalFieldInitializedNode node) { var field = (AnalysisField) node.getField(); isStaticFinalFieldInitializedStates.put(field, Boolean.TRUE); return node; } private Node handleAccessMonitorNode(AccessMonitorNode node) { var object = asActiveImageHeapConstant(node.object()); if (object != null) { /* * Objects allocated within the class initializer are similar to escape analyzed * objects, so we can eliminate such synchronization. * * Note that we cannot eliminate all synchronization in general: an object that was * present before class initialization started could be permanently locked by another * thread, in which case the class initializer must never complete. We cannot detect * such cases during simulation. */ return null; } return node; } private Node handleAllocatedObjectNode(AllocatedObjectNode node) { var imageHeapConstant = allVirtualObjects.get(node.getVirtualObject()); if (imageHeapConstant != null) { return ConstantNode.forConstant(imageHeapConstant, metaAccess); } return node; } private ValueNode handleNewInstanceNode(SimulateClassInitializerInlineScope countersScope, NewInstanceNode node) { var type = (AnalysisType) node.instanceClass(); if (accumulateNewInstanceSize(countersScope, type, node)) { var instance = new ImageHeapInstance(type); for (var field : type.getInstanceFields(true)) { var aField = (AnalysisField) field; instance.setFieldValue(aField, JavaConstant.defaultForKind(aField.getStorageKind())); } currentActiveObjects.add(instance); return ConstantNode.forConstant(instance, metaAccess); } return node; } private ValueNode handleNewArrayNode(SimulateClassInitializerInlineScope countersScope, NewArrayNode node) { var arrayType = (AnalysisType) node.elementType().getArrayClass(); int length = asIntegerOrMinusOne(node.length()); if (accumulateNewArraySize(countersScope, arrayType, length, node)) { var array = createNewArray(arrayType, length); return ConstantNode.forConstant(array, metaAccess); } return node; } protected ImageHeapArray createNewArray(AnalysisType arrayType, int length) { var array = ImageHeapArray.create(arrayType, length); var defaultValue = JavaConstant.defaultForKind(arrayType.getComponentType().getStorageKind()); for (int i = 0; i < length; i++) { array.setElement(i, defaultValue); } currentActiveObjects.add(array); return array; } private ValueNode handleNewMultiArrayNode(SimulateClassInitializerInlineScope countersScope, NewMultiArrayNode node) { int[] dimensions = new int[node.dimensionCount()]; /* * Check first that all array dimensions are valid and that the sum of all resulting array * sizes is not too large. */ long totalLength = 1; var curArrayType = (AnalysisType) node.type(); for (int i = 0; i < dimensions.length; i++) { int length = asIntegerOrMinusOne(node.dimension(i)); totalLength = totalLength * length; if (!accumulateNewArraySize(countersScope, curArrayType, totalLength, node)) { return node; } dimensions[i] = length; curArrayType = curArrayType.getComponentType(); } var array = createNewMultiArray((AnalysisType) node.type(), 0, dimensions); return ConstantNode.forConstant(array, metaAccess); } private ImageHeapArray createNewMultiArray(AnalysisType curArrayType, int curDimension, int[] dimensions) { int curLength = dimensions[curDimension]; int nextDimension = curDimension + 1; if (nextDimension == dimensions.length) { return createNewArray(curArrayType, curLength); } var nextArrayType = curArrayType.getComponentType(); var array = ImageHeapArray.create(curArrayType, dimensions[curDimension]); for (int i = 0; i < curLength; i++) { array.setElement(i, createNewMultiArray(nextArrayType, nextDimension, dimensions)); } currentActiveObjects.add(array); return array; } private ValueNode handleBoxNode(BoxNode node) { var value = node.getValue().asJavaConstant(); if (value == null || node.hasIdentity()) { return node; } /* * No need to produce a ImageHeapConstant, because we know all the boxing classes are always * initialized at image build time. */ var boxedValue = switch (node.getBoxingKind()) { case Byte -> Byte.valueOf((byte) value.asInt()); case Boolean -> Boolean.valueOf(value.asInt() != 0); case Short -> Short.valueOf((short) value.asInt()); case Char -> Character.valueOf((char) value.asInt()); case Int -> Integer.valueOf(value.asInt()); case Long -> Long.valueOf(value.asLong()); case Float -> Float.valueOf(value.asFloat()); case Double -> Double.valueOf(value.asDouble()); default -> throw VMError.shouldNotReachHere("Unexpected kind", node.getBoxingKind()); }; return ConstantNode.forConstant(providers.getSnippetReflection().forObject(boxedValue), metaAccess); } private ValueNode handleObjectClone(SimulateClassInitializerInlineScope countersScope, ObjectClone node) { var originalImageHeapConstant = asActiveImageHeapConstant(node.getObject()); if (originalImageHeapConstant != null) { var type = originalImageHeapConstant.getType(); if ((originalImageHeapConstant instanceof ImageHeapArray originalArray && accumulateNewArraySize(countersScope, type, originalArray.getLength(), node.asNode())) || (type.isCloneableWithAllocation() && accumulateNewInstanceSize(countersScope, type, node.asNode()))) { var cloned = originalImageHeapConstant.forObjectClone(); currentActiveObjects.add(cloned); return ConstantNode.forConstant(cloned, metaAccess); } } var original = node.getObject().asJavaConstant(); if (original != null && ((ConstantNode) node.getObject()).getStableDimension() > 0) { /* * Cloning of an array with stable elements produces a new image heap array with all * elements copied from the stable array. But the new array is not stable anymore. */ var arrayType = (AnalysisType) metaAccess.lookupJavaType(original); Integer length = providers.getConstantReflection().readArrayLength(original); if (length != null && accumulateNewArraySize(countersScope, arrayType, length, node.asNode())) { var array = ImageHeapArray.create(arrayType, length); for (int i = 0; i < length; i++) { array.setElement(i, adaptForImageHeap(providers.getConstantReflection().readArrayElement(original, i), arrayType.getComponentType().getStorageKind())); } currentActiveObjects.add(array); return ConstantNode.forConstant(array, metaAccess); } } return node.asNode(); } private void handleCommitAllocationNode(SimulateClassInitializerInlineScope countersScope, CommitAllocationNode node) { boolean progress; do { /* * To handle multi-dimensional arrays, we process the virtual objects multiple times as * long as we make any progress: In the first iteration, the "inner" arrays are * processed and put into the allVirtualObjects map. In the second iteration, these * virtual objects can be put into the outer array. */ progress = false; int pos = 0; for (int i = 0; i < node.getVirtualObjects().size(); i++) { VirtualObjectNode virtualObject = node.getVirtualObjects().get(i); int entryCount = virtualObject.entryCount(); List<ValueNode> entries = node.getValues().subList(pos, pos + entryCount); pos += entryCount; if (!node.getLocks(i).isEmpty() || node.getEnsureVirtual().get(i)) { /* * Ignore unnecessary corner cases: we do not expect to see objects that are * locked because constructors are not inlined when escape analysis runs, i.e., * objects are always materialized before the constructor when they are also * unlocked. Similarly, we do not see virtual objects that were already passed * into a EnsureVirtualizedNode. */ } else if (allVirtualObjects.containsKey(virtualObject)) { /* Already processed in previous round. */ } else if (virtualObject instanceof VirtualBoxingNode) { VMError.shouldNotReachHere("For testing: check if this is reachable"); /* * Could be handled the same way as a BoxNode, but does not occur in practice * because escape analysis does not seem to materialize boxed objects as part of * a CommitAllocationNode. */ } else if (virtualObject instanceof VirtualInstanceNode virtualInstance) { progress |= handleVirtualInstance(countersScope, virtualInstance, entries, node); } else if (virtualObject instanceof VirtualArrayNode virtualArray) { progress |= handleVirtualArray(countersScope, virtualArray, entries, node); } else { throw VMError.shouldNotReachHere(virtualObject.toString()); } } } while (progress); } private boolean handleVirtualInstance(SimulateClassInitializerInlineScope countersScope, VirtualInstanceNode virtualInstance, List<ValueNode> entries, Node reason) { var type = (AnalysisType) virtualInstance.type(); if (!accumulateNewInstanceSize(countersScope, type, reason)) { return false; } var instance = new ImageHeapInstance(type); for (int j = 0; j < virtualInstance.entryCount(); j++) { var entry = lookupConstantEntry(j, entries); if (entry == null) { /* * That happens only in corner cases since constructors are not inlined when escape * analysis runs. */ return false; } var field = (AnalysisField) virtualInstance.field(j); instance.setFieldValue(field, adaptForImageHeap(entry, field.getStorageKind())); } allVirtualObjects.put(virtualInstance, instance); currentActiveObjects.add(instance); return true; } private boolean handleVirtualArray(SimulateClassInitializerInlineScope countersScope, VirtualArrayNode virtualArray, List<ValueNode> entries, Node reason) { var arrayType = (AnalysisType) virtualArray.type(); int length = virtualArray.entryCount(); if (!accumulateNewArraySize(countersScope, arrayType, length, reason)) { return false; } var array = ImageHeapArray.create(arrayType, length); for (int j = 0; j < length; j++) { var entry = lookupConstantEntry(j, entries); if (entry == null) { /* * Handling this would require emitting multiple StoreIndexed node, which is not * possible as part of a canonicalization during partial evaluation. */ return false; } array.setElement(j, adaptForImageHeap(entry, arrayType.getComponentType().getStorageKind())); } allVirtualObjects.put(virtualArray, array); currentActiveObjects.add(array); return true; } private JavaConstant lookupConstantEntry(int index, List<ValueNode> entries) { var entry = entries.get(index); if (entry instanceof VirtualObjectNode virtualObjectNode) { return allVirtualObjects.get(virtualObjectNode); } else { return entry.asJavaConstant(); } } protected boolean accumulateNewInstanceSize(SimulateClassInitializerInlineScope countersScope, AnalysisType type, Node reason) { assert type.isInstanceClass() : type; /* * We do not know yet how large the object really will be, because we do not know yet which * fields are reachable. So we estimate by just summing up field sizes. */ var objectLayout = ImageSingletons.lookup(ObjectLayout.class); long allocationSize = objectLayout.getFirstFieldOffset(); for (var field : type.getInstanceFields(true)) { allocationSize += objectLayout.sizeInBytes(((AnalysisField) field).getStorageKind()); } return accumulatedNewObjectSize(countersScope, allocationSize, reason); } protected boolean accumulateNewArraySize(SimulateClassInitializerInlineScope countersScope, AnalysisType arrayType, long length, Node reason) { if (length < 0) { return false; } var objectLayout = ImageSingletons.lookup(ObjectLayout.class); long allocationSize = objectLayout.getArraySize(arrayType.getComponentType().getStorageKind(), (int) length, true); return accumulatedNewObjectSize(countersScope, allocationSize, reason); } private boolean accumulatedNewObjectSize(SimulateClassInitializerInlineScope countersScope, long allocationSize, Node reason) { if (countersScope.accumulativeCounters.allocatedBytes + allocationSize > support.maxAllocatedBytes) { if (debug.isLogEnabled(DebugContext.BASIC_LEVEL)) { debug.log("object size %s too large since already %s allocated: %s %s", allocationSize, countersScope.accumulativeCounters.allocatedBytes, reason, reason.getNodeSourcePosition()); } if (support.collectAllReasons) { return false; } else { throw SimulateClassInitializerAbortException.doAbort(clusterMember, graph, reason); } } countersScope.accumulativeCounters.allocatedBytes += allocationSize; countersScope.allocatedBytes += allocationSize; return true; } protected ImageHeapConstant asActiveImageHeapConstant(ValueNode node) { var constant = node.asJavaConstant(); if (constant instanceof ImageHeapConstant imageHeapConstant && currentActiveObjects.contains(imageHeapConstant)) { return imageHeapConstant; } return null; } protected ImageHeapInstance asActiveImageHeapInstance(ValueNode node) { var constant = node.asJavaConstant(); if (constant instanceof ImageHeapInstance imageHeapInstance && currentActiveObjects.contains(imageHeapInstance)) { return imageHeapInstance; } return null; } protected ImageHeapArray asActiveImageHeapArray(ValueNode node) { var constant = node.asJavaConstant(); if (constant instanceof ImageHeapArray imageHeapArray && currentActiveObjects.contains(imageHeapArray)) { return imageHeapArray; } return null; } protected static int asIntegerOrMinusOne(ValueNode node) { var constant = node.asJavaConstant(); if (constant != null) { return constant.asInt(); } return -1; } /** * Make sure that constants added into the image heap have the correct kind. Constants for * sub-integer types are often just integer constants in the Graal IR, i.e., we cannot rely on * the JavaKind of the constant to match the type of the field or array. */ static JavaConstant adaptForImageHeap(JavaConstant value, JavaKind storageKind) { if (value.getJavaKind() != storageKind) { assert value instanceof PrimitiveConstant && value.getJavaKind().getStackKind() == storageKind.getStackKind() : "only sub-int values can have a mismatch of the JavaKind: " + value.getJavaKind() + ", " + storageKind; return JavaConstant.forPrimitive(storageKind, value.asLong()); } else { assert !storageKind.isObject() || value.isNull() || value instanceof ImageHeapConstant : "Expected ImageHeapConstant, found: " + value; return value; } } }
googleads/google-ads-java
37,026
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/CustomerManagerLink.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/resources/customer_manager_link.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.resources; /** * <pre> * Represents customer-manager link relationship. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.CustomerManagerLink} */ public final class CustomerManagerLink extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.resources.CustomerManagerLink) CustomerManagerLinkOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerManagerLink.newBuilder() to construct. private CustomerManagerLink(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerManagerLink() { resourceName_ = ""; managerCustomer_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerManagerLink(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v19_resources_CustomerManagerLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v19_resources_CustomerManagerLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.CustomerManagerLink.class, com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder.class); } private int bitField0_; public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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 MANAGER_CUSTOMER_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object managerCustomer_ = ""; /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the managerCustomer field is set. */ @java.lang.Override public boolean hasManagerCustomer() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The managerCustomer. */ @java.lang.Override public java.lang.String getManagerCustomer() { java.lang.Object ref = managerCustomer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); managerCustomer_ = s; return s; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for managerCustomer. */ @java.lang.Override public com.google.protobuf.ByteString getManagerCustomerBytes() { java.lang.Object ref = managerCustomer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); managerCustomer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MANAGER_LINK_ID_FIELD_NUMBER = 7; private long managerLinkId_ = 0L; /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the managerLinkId field is set. */ @java.lang.Override public boolean hasManagerLinkId() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The managerLinkId. */ @java.lang.Override public long getManagerLinkId() { return managerLinkId_; } public static final int STATUS_FIELD_NUMBER = 5; private int status_ = 0; /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus getStatus() { com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus result = com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus.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 (status_ != com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(5, status_); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, managerCustomer_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeInt64(7, managerLinkId_); } 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 (status_ != com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, status_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, managerCustomer_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, managerLinkId_); } 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.CustomerManagerLink)) { return super.equals(obj); } com.google.ads.googleads.v19.resources.CustomerManagerLink other = (com.google.ads.googleads.v19.resources.CustomerManagerLink) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (hasManagerCustomer() != other.hasManagerCustomer()) return false; if (hasManagerCustomer()) { if (!getManagerCustomer() .equals(other.getManagerCustomer())) return false; } if (hasManagerLinkId() != other.hasManagerLinkId()) return false; if (hasManagerLinkId()) { if (getManagerLinkId() != other.getManagerLinkId()) 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(); if (hasManagerCustomer()) { hash = (37 * hash) + MANAGER_CUSTOMER_FIELD_NUMBER; hash = (53 * hash) + getManagerCustomer().hashCode(); } if (hasManagerLinkId()) { hash = (37 * hash) + MANAGER_LINK_ID_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getManagerLinkId()); } 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.CustomerManagerLink parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CustomerManagerLink 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.CustomerManagerLink parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CustomerManagerLink 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.CustomerManagerLink parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Represents customer-manager link relationship. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.CustomerManagerLink} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.resources.CustomerManagerLink) com.google.ads.googleads.v19.resources.CustomerManagerLinkOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v19_resources_CustomerManagerLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v19_resources_CustomerManagerLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.CustomerManagerLink.class, com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder.class); } // Construct using com.google.ads.googleads.v19.resources.CustomerManagerLink.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; managerCustomer_ = ""; managerLinkId_ = 0L; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v19_resources_CustomerManagerLink_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerManagerLink getDefaultInstanceForType() { return com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerManagerLink build() { com.google.ads.googleads.v19.resources.CustomerManagerLink result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerManagerLink buildPartial() { com.google.ads.googleads.v19.resources.CustomerManagerLink result = new com.google.ads.googleads.v19.resources.CustomerManagerLink(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.resources.CustomerManagerLink result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.managerCustomer_ = managerCustomer_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.managerLinkId_ = managerLinkId_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v19.resources.CustomerManagerLink) { return mergeFrom((com.google.ads.googleads.v19.resources.CustomerManagerLink)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.resources.CustomerManagerLink other) { if (other == com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasManagerCustomer()) { managerCustomer_ = other.managerCustomer_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasManagerLinkId()) { setManagerLinkId(other.getManagerLinkId()); } 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 40: { status_ = input.readEnum(); bitField0_ |= 0x00000008; break; } // case 40 case 50: { managerCustomer_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 50 case 56: { managerLinkId_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 56 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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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 managerCustomer_ = ""; /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the managerCustomer field is set. */ public boolean hasManagerCustomer() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The managerCustomer. */ public java.lang.String getManagerCustomer() { java.lang.Object ref = managerCustomer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); managerCustomer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for managerCustomer. */ public com.google.protobuf.ByteString getManagerCustomerBytes() { java.lang.Object ref = managerCustomer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); managerCustomer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The managerCustomer to set. * @return This builder for chaining. */ public Builder setManagerCustomer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } managerCustomer_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearManagerCustomer() { managerCustomer_ = getDefaultInstance().getManagerCustomer(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for managerCustomer to set. * @return This builder for chaining. */ public Builder setManagerCustomerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); managerCustomer_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long managerLinkId_ ; /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the managerLinkId field is set. */ @java.lang.Override public boolean hasManagerLinkId() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The managerLinkId. */ @java.lang.Override public long getManagerLinkId() { return managerLinkId_; } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The managerLinkId to set. * @return This builder for chaining. */ public Builder setManagerLinkId(long value) { managerLinkId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearManagerLinkId() { bitField0_ = (bitField0_ & ~0x00000004); managerLinkId_ = 0L; onChanged(); return this; } private int status_ = 0; /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</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> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus getStatus() { com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus result = com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v19.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</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.CustomerManagerLink) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.resources.CustomerManagerLink) private static final com.google.ads.googleads.v19.resources.CustomerManagerLink DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.resources.CustomerManagerLink(); } public static com.google.ads.googleads.v19.resources.CustomerManagerLink getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerManagerLink> PARSER = new com.google.protobuf.AbstractParser<CustomerManagerLink>() { @java.lang.Override public CustomerManagerLink 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<CustomerManagerLink> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerManagerLink> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerManagerLink getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,026
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/CustomerManagerLink.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/resources/customer_manager_link.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.resources; /** * <pre> * Represents customer-manager link relationship. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.CustomerManagerLink} */ public final class CustomerManagerLink extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.resources.CustomerManagerLink) CustomerManagerLinkOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerManagerLink.newBuilder() to construct. private CustomerManagerLink(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerManagerLink() { resourceName_ = ""; managerCustomer_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerManagerLink(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v20_resources_CustomerManagerLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v20_resources_CustomerManagerLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.CustomerManagerLink.class, com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder.class); } private int bitField0_; public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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 MANAGER_CUSTOMER_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object managerCustomer_ = ""; /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the managerCustomer field is set. */ @java.lang.Override public boolean hasManagerCustomer() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The managerCustomer. */ @java.lang.Override public java.lang.String getManagerCustomer() { java.lang.Object ref = managerCustomer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); managerCustomer_ = s; return s; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for managerCustomer. */ @java.lang.Override public com.google.protobuf.ByteString getManagerCustomerBytes() { java.lang.Object ref = managerCustomer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); managerCustomer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MANAGER_LINK_ID_FIELD_NUMBER = 7; private long managerLinkId_ = 0L; /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the managerLinkId field is set. */ @java.lang.Override public boolean hasManagerLinkId() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The managerLinkId. */ @java.lang.Override public long getManagerLinkId() { return managerLinkId_; } public static final int STATUS_FIELD_NUMBER = 5; private int status_ = 0; /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus getStatus() { com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus result = com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus.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 (status_ != com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(5, status_); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, managerCustomer_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeInt64(7, managerLinkId_); } 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 (status_ != com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, status_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, managerCustomer_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, managerLinkId_); } 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.CustomerManagerLink)) { return super.equals(obj); } com.google.ads.googleads.v20.resources.CustomerManagerLink other = (com.google.ads.googleads.v20.resources.CustomerManagerLink) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (hasManagerCustomer() != other.hasManagerCustomer()) return false; if (hasManagerCustomer()) { if (!getManagerCustomer() .equals(other.getManagerCustomer())) return false; } if (hasManagerLinkId() != other.hasManagerLinkId()) return false; if (hasManagerLinkId()) { if (getManagerLinkId() != other.getManagerLinkId()) 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(); if (hasManagerCustomer()) { hash = (37 * hash) + MANAGER_CUSTOMER_FIELD_NUMBER; hash = (53 * hash) + getManagerCustomer().hashCode(); } if (hasManagerLinkId()) { hash = (37 * hash) + MANAGER_LINK_ID_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getManagerLinkId()); } 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.CustomerManagerLink parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CustomerManagerLink 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.CustomerManagerLink parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CustomerManagerLink 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.CustomerManagerLink parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Represents customer-manager link relationship. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.CustomerManagerLink} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.resources.CustomerManagerLink) com.google.ads.googleads.v20.resources.CustomerManagerLinkOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v20_resources_CustomerManagerLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v20_resources_CustomerManagerLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.CustomerManagerLink.class, com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder.class); } // Construct using com.google.ads.googleads.v20.resources.CustomerManagerLink.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; managerCustomer_ = ""; managerLinkId_ = 0L; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v20_resources_CustomerManagerLink_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerManagerLink getDefaultInstanceForType() { return com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerManagerLink build() { com.google.ads.googleads.v20.resources.CustomerManagerLink result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerManagerLink buildPartial() { com.google.ads.googleads.v20.resources.CustomerManagerLink result = new com.google.ads.googleads.v20.resources.CustomerManagerLink(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.resources.CustomerManagerLink result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.managerCustomer_ = managerCustomer_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.managerLinkId_ = managerLinkId_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v20.resources.CustomerManagerLink) { return mergeFrom((com.google.ads.googleads.v20.resources.CustomerManagerLink)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.resources.CustomerManagerLink other) { if (other == com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasManagerCustomer()) { managerCustomer_ = other.managerCustomer_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasManagerLinkId()) { setManagerLinkId(other.getManagerLinkId()); } 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 40: { status_ = input.readEnum(); bitField0_ |= 0x00000008; break; } // case 40 case 50: { managerCustomer_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 50 case 56: { managerLinkId_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 56 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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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 managerCustomer_ = ""; /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the managerCustomer field is set. */ public boolean hasManagerCustomer() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The managerCustomer. */ public java.lang.String getManagerCustomer() { java.lang.Object ref = managerCustomer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); managerCustomer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for managerCustomer. */ public com.google.protobuf.ByteString getManagerCustomerBytes() { java.lang.Object ref = managerCustomer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); managerCustomer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The managerCustomer to set. * @return This builder for chaining. */ public Builder setManagerCustomer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } managerCustomer_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearManagerCustomer() { managerCustomer_ = getDefaultInstance().getManagerCustomer(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for managerCustomer to set. * @return This builder for chaining. */ public Builder setManagerCustomerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); managerCustomer_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long managerLinkId_ ; /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the managerLinkId field is set. */ @java.lang.Override public boolean hasManagerLinkId() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The managerLinkId. */ @java.lang.Override public long getManagerLinkId() { return managerLinkId_; } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The managerLinkId to set. * @return This builder for chaining. */ public Builder setManagerLinkId(long value) { managerLinkId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearManagerLinkId() { bitField0_ = (bitField0_ & ~0x00000004); managerLinkId_ = 0L; onChanged(); return this; } private int status_ = 0; /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</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> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus getStatus() { com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus result = com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v20.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</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.CustomerManagerLink) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.resources.CustomerManagerLink) private static final com.google.ads.googleads.v20.resources.CustomerManagerLink DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.resources.CustomerManagerLink(); } public static com.google.ads.googleads.v20.resources.CustomerManagerLink getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerManagerLink> PARSER = new com.google.protobuf.AbstractParser<CustomerManagerLink>() { @java.lang.Override public CustomerManagerLink 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<CustomerManagerLink> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerManagerLink> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerManagerLink getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,026
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/CustomerManagerLink.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/resources/customer_manager_link.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.resources; /** * <pre> * Represents customer-manager link relationship. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.CustomerManagerLink} */ public final class CustomerManagerLink extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.CustomerManagerLink) CustomerManagerLinkOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerManagerLink.newBuilder() to construct. private CustomerManagerLink(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerManagerLink() { resourceName_ = ""; managerCustomer_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerManagerLink(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v21_resources_CustomerManagerLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v21_resources_CustomerManagerLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.CustomerManagerLink.class, com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder.class); } private int bitField0_; public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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 MANAGER_CUSTOMER_FIELD_NUMBER = 6; @SuppressWarnings("serial") private volatile java.lang.Object managerCustomer_ = ""; /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the managerCustomer field is set. */ @java.lang.Override public boolean hasManagerCustomer() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The managerCustomer. */ @java.lang.Override public java.lang.String getManagerCustomer() { java.lang.Object ref = managerCustomer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); managerCustomer_ = s; return s; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for managerCustomer. */ @java.lang.Override public com.google.protobuf.ByteString getManagerCustomerBytes() { java.lang.Object ref = managerCustomer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); managerCustomer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MANAGER_LINK_ID_FIELD_NUMBER = 7; private long managerLinkId_ = 0L; /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the managerLinkId field is set. */ @java.lang.Override public boolean hasManagerLinkId() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The managerLinkId. */ @java.lang.Override public long getManagerLinkId() { return managerLinkId_; } public static final int STATUS_FIELD_NUMBER = 5; private int status_ = 0; /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus getStatus() { com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus result = com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus.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 (status_ != com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(5, status_); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, managerCustomer_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeInt64(7, managerLinkId_); } 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 (status_ != com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, status_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, managerCustomer_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, managerLinkId_); } 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.CustomerManagerLink)) { return super.equals(obj); } com.google.ads.googleads.v21.resources.CustomerManagerLink other = (com.google.ads.googleads.v21.resources.CustomerManagerLink) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (hasManagerCustomer() != other.hasManagerCustomer()) return false; if (hasManagerCustomer()) { if (!getManagerCustomer() .equals(other.getManagerCustomer())) return false; } if (hasManagerLinkId() != other.hasManagerLinkId()) return false; if (hasManagerLinkId()) { if (getManagerLinkId() != other.getManagerLinkId()) 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(); if (hasManagerCustomer()) { hash = (37 * hash) + MANAGER_CUSTOMER_FIELD_NUMBER; hash = (53 * hash) + getManagerCustomer().hashCode(); } if (hasManagerLinkId()) { hash = (37 * hash) + MANAGER_LINK_ID_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getManagerLinkId()); } 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.CustomerManagerLink parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CustomerManagerLink 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.CustomerManagerLink parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CustomerManagerLink 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.CustomerManagerLink parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink 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.CustomerManagerLink prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Represents customer-manager link relationship. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.CustomerManagerLink} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.CustomerManagerLink) com.google.ads.googleads.v21.resources.CustomerManagerLinkOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v21_resources_CustomerManagerLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v21_resources_CustomerManagerLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.CustomerManagerLink.class, com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder.class); } // Construct using com.google.ads.googleads.v21.resources.CustomerManagerLink.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; managerCustomer_ = ""; managerLinkId_ = 0L; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.resources.CustomerManagerLinkProto.internal_static_google_ads_googleads_v21_resources_CustomerManagerLink_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerManagerLink getDefaultInstanceForType() { return com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerManagerLink build() { com.google.ads.googleads.v21.resources.CustomerManagerLink result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerManagerLink buildPartial() { com.google.ads.googleads.v21.resources.CustomerManagerLink result = new com.google.ads.googleads.v21.resources.CustomerManagerLink(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.resources.CustomerManagerLink result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.managerCustomer_ = managerCustomer_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.managerLinkId_ = managerLinkId_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v21.resources.CustomerManagerLink) { return mergeFrom((com.google.ads.googleads.v21.resources.CustomerManagerLink)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.resources.CustomerManagerLink other) { if (other == com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasManagerCustomer()) { managerCustomer_ = other.managerCustomer_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasManagerLinkId()) { setManagerLinkId(other.getManagerLinkId()); } 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 40: { status_ = input.readEnum(); bitField0_ |= 0x00000008; break; } // case 40 case 50: { managerCustomer_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 50 case 56: { managerLinkId_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 56 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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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. Name of the resource. * CustomerManagerLink resource names have the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_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 managerCustomer_ = ""; /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the managerCustomer field is set. */ public boolean hasManagerCustomer() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The managerCustomer. */ public java.lang.String getManagerCustomer() { java.lang.Object ref = managerCustomer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); managerCustomer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for managerCustomer. */ public com.google.protobuf.ByteString getManagerCustomerBytes() { java.lang.Object ref = managerCustomer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); managerCustomer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The managerCustomer to set. * @return This builder for chaining. */ public Builder setManagerCustomer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } managerCustomer_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearManagerCustomer() { managerCustomer_ = getDefaultInstance().getManagerCustomer(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Output only. The manager customer linked to the customer. * </pre> * * <code>optional string manager_customer = 6 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for managerCustomer to set. * @return This builder for chaining. */ public Builder setManagerCustomerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); managerCustomer_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private long managerLinkId_ ; /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the managerLinkId field is set. */ @java.lang.Override public boolean hasManagerLinkId() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The managerLinkId. */ @java.lang.Override public long getManagerLinkId() { return managerLinkId_; } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The managerLinkId to set. * @return This builder for chaining. */ public Builder setManagerLinkId(long value) { managerLinkId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Output only. ID of the customer-manager link. This field is read only. * </pre> * * <code>optional int64 manager_link_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearManagerLinkId() { bitField0_ = (bitField0_ & ~0x00000004); managerLinkId_ = 0L; onChanged(); return this; } private int status_ = 0; /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</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> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus getStatus() { com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus result = com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Status of the link between the customer and the manager. * </pre> * * <code>.google.ads.googleads.v21.enums.ManagerLinkStatusEnum.ManagerLinkStatus status = 5;</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.CustomerManagerLink) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.CustomerManagerLink) private static final com.google.ads.googleads.v21.resources.CustomerManagerLink DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.CustomerManagerLink(); } public static com.google.ads.googleads.v21.resources.CustomerManagerLink getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerManagerLink> PARSER = new com.google.protobuf.AbstractParser<CustomerManagerLink>() { @java.lang.Override public CustomerManagerLink 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<CustomerManagerLink> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerManagerLink> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerManagerLink getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,824
java-tasks/proto-google-cloud-tasks-v2beta2/src/main/java/com/google/cloud/tasks/v2beta2/ListQueuesResponse.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/tasks/v2beta2/cloudtasks.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.tasks.v2beta2; /** * * * <pre> * Response message for * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues]. * </pre> * * Protobuf type {@code google.cloud.tasks.v2beta2.ListQueuesResponse} */ public final class ListQueuesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.tasks.v2beta2.ListQueuesResponse) ListQueuesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListQueuesResponse.newBuilder() to construct. private ListQueuesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListQueuesResponse() { queues_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListQueuesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.tasks.v2beta2.CloudTasksProto .internal_static_google_cloud_tasks_v2beta2_ListQueuesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.tasks.v2beta2.CloudTasksProto .internal_static_google_cloud_tasks_v2beta2_ListQueuesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.tasks.v2beta2.ListQueuesResponse.class, com.google.cloud.tasks.v2beta2.ListQueuesResponse.Builder.class); } public static final int QUEUES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.tasks.v2beta2.Queue> queues_; /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.tasks.v2beta2.Queue> getQueuesList() { return queues_; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.tasks.v2beta2.QueueOrBuilder> getQueuesOrBuilderList() { return queues_; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ @java.lang.Override public int getQueuesCount() { return queues_.size(); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ @java.lang.Override public com.google.cloud.tasks.v2beta2.Queue getQueues(int index) { return queues_.get(index); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ @java.lang.Override public com.google.cloud.tasks.v2beta2.QueueOrBuilder getQueuesOrBuilder(int index) { return queues_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < queues_.size(); i++) { output.writeMessage(1, queues_.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 < queues_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, queues_.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.tasks.v2beta2.ListQueuesResponse)) { return super.equals(obj); } com.google.cloud.tasks.v2beta2.ListQueuesResponse other = (com.google.cloud.tasks.v2beta2.ListQueuesResponse) obj; if (!getQueuesList().equals(other.getQueuesList())) 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 (getQueuesCount() > 0) { hash = (37 * hash) + QUEUES_FIELD_NUMBER; hash = (53 * hash) + getQueuesList().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.tasks.v2beta2.ListQueuesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse 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.tasks.v2beta2.ListQueuesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse 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.tasks.v2beta2.ListQueuesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse 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.tasks.v2beta2.ListQueuesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse 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.tasks.v2beta2.ListQueuesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse 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.tasks.v2beta2.ListQueuesResponse 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 * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues]. * </pre> * * Protobuf type {@code google.cloud.tasks.v2beta2.ListQueuesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.tasks.v2beta2.ListQueuesResponse) com.google.cloud.tasks.v2beta2.ListQueuesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.tasks.v2beta2.CloudTasksProto .internal_static_google_cloud_tasks_v2beta2_ListQueuesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.tasks.v2beta2.CloudTasksProto .internal_static_google_cloud_tasks_v2beta2_ListQueuesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.tasks.v2beta2.ListQueuesResponse.class, com.google.cloud.tasks.v2beta2.ListQueuesResponse.Builder.class); } // Construct using com.google.cloud.tasks.v2beta2.ListQueuesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (queuesBuilder_ == null) { queues_ = java.util.Collections.emptyList(); } else { queues_ = null; queuesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.tasks.v2beta2.CloudTasksProto .internal_static_google_cloud_tasks_v2beta2_ListQueuesResponse_descriptor; } @java.lang.Override public com.google.cloud.tasks.v2beta2.ListQueuesResponse getDefaultInstanceForType() { return com.google.cloud.tasks.v2beta2.ListQueuesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.tasks.v2beta2.ListQueuesResponse build() { com.google.cloud.tasks.v2beta2.ListQueuesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.tasks.v2beta2.ListQueuesResponse buildPartial() { com.google.cloud.tasks.v2beta2.ListQueuesResponse result = new com.google.cloud.tasks.v2beta2.ListQueuesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.tasks.v2beta2.ListQueuesResponse result) { if (queuesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { queues_ = java.util.Collections.unmodifiableList(queues_); bitField0_ = (bitField0_ & ~0x00000001); } result.queues_ = queues_; } else { result.queues_ = queuesBuilder_.build(); } } private void buildPartial0(com.google.cloud.tasks.v2beta2.ListQueuesResponse 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.tasks.v2beta2.ListQueuesResponse) { return mergeFrom((com.google.cloud.tasks.v2beta2.ListQueuesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.tasks.v2beta2.ListQueuesResponse other) { if (other == com.google.cloud.tasks.v2beta2.ListQueuesResponse.getDefaultInstance()) return this; if (queuesBuilder_ == null) { if (!other.queues_.isEmpty()) { if (queues_.isEmpty()) { queues_ = other.queues_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureQueuesIsMutable(); queues_.addAll(other.queues_); } onChanged(); } } else { if (!other.queues_.isEmpty()) { if (queuesBuilder_.isEmpty()) { queuesBuilder_.dispose(); queuesBuilder_ = null; queues_ = other.queues_; bitField0_ = (bitField0_ & ~0x00000001); queuesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getQueuesFieldBuilder() : null; } else { queuesBuilder_.addAllMessages(other.queues_); } } } 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.tasks.v2beta2.Queue m = input.readMessage( com.google.cloud.tasks.v2beta2.Queue.parser(), extensionRegistry); if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.add(m); } else { queuesBuilder_.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.tasks.v2beta2.Queue> queues_ = java.util.Collections.emptyList(); private void ensureQueuesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { queues_ = new java.util.ArrayList<com.google.cloud.tasks.v2beta2.Queue>(queues_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.tasks.v2beta2.Queue, com.google.cloud.tasks.v2beta2.Queue.Builder, com.google.cloud.tasks.v2beta2.QueueOrBuilder> queuesBuilder_; /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public java.util.List<com.google.cloud.tasks.v2beta2.Queue> getQueuesList() { if (queuesBuilder_ == null) { return java.util.Collections.unmodifiableList(queues_); } else { return queuesBuilder_.getMessageList(); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public int getQueuesCount() { if (queuesBuilder_ == null) { return queues_.size(); } else { return queuesBuilder_.getCount(); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta2.Queue getQueues(int index) { if (queuesBuilder_ == null) { return queues_.get(index); } else { return queuesBuilder_.getMessage(index); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder setQueues(int index, com.google.cloud.tasks.v2beta2.Queue value) { if (queuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQueuesIsMutable(); queues_.set(index, value); onChanged(); } else { queuesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder setQueues( int index, com.google.cloud.tasks.v2beta2.Queue.Builder builderForValue) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.set(index, builderForValue.build()); onChanged(); } else { queuesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder addQueues(com.google.cloud.tasks.v2beta2.Queue value) { if (queuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQueuesIsMutable(); queues_.add(value); onChanged(); } else { queuesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder addQueues(int index, com.google.cloud.tasks.v2beta2.Queue value) { if (queuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQueuesIsMutable(); queues_.add(index, value); onChanged(); } else { queuesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder addQueues(com.google.cloud.tasks.v2beta2.Queue.Builder builderForValue) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.add(builderForValue.build()); onChanged(); } else { queuesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder addQueues( int index, com.google.cloud.tasks.v2beta2.Queue.Builder builderForValue) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.add(index, builderForValue.build()); onChanged(); } else { queuesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder addAllQueues( java.lang.Iterable<? extends com.google.cloud.tasks.v2beta2.Queue> values) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, queues_); onChanged(); } else { queuesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder clearQueues() { if (queuesBuilder_ == null) { queues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { queuesBuilder_.clear(); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public Builder removeQueues(int index) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.remove(index); onChanged(); } else { queuesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta2.Queue.Builder getQueuesBuilder(int index) { return getQueuesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta2.QueueOrBuilder getQueuesOrBuilder(int index) { if (queuesBuilder_ == null) { return queues_.get(index); } else { return queuesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public java.util.List<? extends com.google.cloud.tasks.v2beta2.QueueOrBuilder> getQueuesOrBuilderList() { if (queuesBuilder_ != null) { return queuesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(queues_); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta2.Queue.Builder addQueuesBuilder() { return getQueuesFieldBuilder() .addBuilder(com.google.cloud.tasks.v2beta2.Queue.getDefaultInstance()); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta2.Queue.Builder addQueuesBuilder(int index) { return getQueuesFieldBuilder() .addBuilder(index, com.google.cloud.tasks.v2beta2.Queue.getDefaultInstance()); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta2.Queue queues = 1;</code> */ public java.util.List<com.google.cloud.tasks.v2beta2.Queue.Builder> getQueuesBuilderList() { return getQueuesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.tasks.v2beta2.Queue, com.google.cloud.tasks.v2beta2.Queue.Builder, com.google.cloud.tasks.v2beta2.QueueOrBuilder> getQueuesFieldBuilder() { if (queuesBuilder_ == null) { queuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.tasks.v2beta2.Queue, com.google.cloud.tasks.v2beta2.Queue.Builder, com.google.cloud.tasks.v2beta2.QueueOrBuilder>( queues_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); queues_ = null; } return queuesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta2.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta2.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.tasks.v2beta2.ListQueuesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.tasks.v2beta2.ListQueuesResponse) private static final com.google.cloud.tasks.v2beta2.ListQueuesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.tasks.v2beta2.ListQueuesResponse(); } public static com.google.cloud.tasks.v2beta2.ListQueuesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListQueuesResponse> PARSER = new com.google.protobuf.AbstractParser<ListQueuesResponse>() { @java.lang.Override public ListQueuesResponse 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<ListQueuesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListQueuesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.tasks.v2beta2.ListQueuesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,824
java-tasks/proto-google-cloud-tasks-v2beta3/src/main/java/com/google/cloud/tasks/v2beta3/ListQueuesResponse.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/tasks/v2beta3/cloudtasks.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.tasks.v2beta3; /** * * * <pre> * Response message for * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues]. * </pre> * * Protobuf type {@code google.cloud.tasks.v2beta3.ListQueuesResponse} */ public final class ListQueuesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.tasks.v2beta3.ListQueuesResponse) ListQueuesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListQueuesResponse.newBuilder() to construct. private ListQueuesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListQueuesResponse() { queues_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListQueuesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.tasks.v2beta3.CloudTasksProto .internal_static_google_cloud_tasks_v2beta3_ListQueuesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.tasks.v2beta3.CloudTasksProto .internal_static_google_cloud_tasks_v2beta3_ListQueuesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.tasks.v2beta3.ListQueuesResponse.class, com.google.cloud.tasks.v2beta3.ListQueuesResponse.Builder.class); } public static final int QUEUES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.tasks.v2beta3.Queue> queues_; /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.tasks.v2beta3.Queue> getQueuesList() { return queues_; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.tasks.v2beta3.QueueOrBuilder> getQueuesOrBuilderList() { return queues_; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ @java.lang.Override public int getQueuesCount() { return queues_.size(); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ @java.lang.Override public com.google.cloud.tasks.v2beta3.Queue getQueues(int index) { return queues_.get(index); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ @java.lang.Override public com.google.cloud.tasks.v2beta3.QueueOrBuilder getQueuesOrBuilder(int index) { return queues_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < queues_.size(); i++) { output.writeMessage(1, queues_.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 < queues_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, queues_.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.tasks.v2beta3.ListQueuesResponse)) { return super.equals(obj); } com.google.cloud.tasks.v2beta3.ListQueuesResponse other = (com.google.cloud.tasks.v2beta3.ListQueuesResponse) obj; if (!getQueuesList().equals(other.getQueuesList())) 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 (getQueuesCount() > 0) { hash = (37 * hash) + QUEUES_FIELD_NUMBER; hash = (53 * hash) + getQueuesList().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.tasks.v2beta3.ListQueuesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse 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.tasks.v2beta3.ListQueuesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse 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.tasks.v2beta3.ListQueuesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse 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.tasks.v2beta3.ListQueuesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse 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.tasks.v2beta3.ListQueuesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse 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.tasks.v2beta3.ListQueuesResponse 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 * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues]. * </pre> * * Protobuf type {@code google.cloud.tasks.v2beta3.ListQueuesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.tasks.v2beta3.ListQueuesResponse) com.google.cloud.tasks.v2beta3.ListQueuesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.tasks.v2beta3.CloudTasksProto .internal_static_google_cloud_tasks_v2beta3_ListQueuesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.tasks.v2beta3.CloudTasksProto .internal_static_google_cloud_tasks_v2beta3_ListQueuesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.tasks.v2beta3.ListQueuesResponse.class, com.google.cloud.tasks.v2beta3.ListQueuesResponse.Builder.class); } // Construct using com.google.cloud.tasks.v2beta3.ListQueuesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (queuesBuilder_ == null) { queues_ = java.util.Collections.emptyList(); } else { queues_ = null; queuesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.tasks.v2beta3.CloudTasksProto .internal_static_google_cloud_tasks_v2beta3_ListQueuesResponse_descriptor; } @java.lang.Override public com.google.cloud.tasks.v2beta3.ListQueuesResponse getDefaultInstanceForType() { return com.google.cloud.tasks.v2beta3.ListQueuesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.tasks.v2beta3.ListQueuesResponse build() { com.google.cloud.tasks.v2beta3.ListQueuesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.tasks.v2beta3.ListQueuesResponse buildPartial() { com.google.cloud.tasks.v2beta3.ListQueuesResponse result = new com.google.cloud.tasks.v2beta3.ListQueuesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.tasks.v2beta3.ListQueuesResponse result) { if (queuesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { queues_ = java.util.Collections.unmodifiableList(queues_); bitField0_ = (bitField0_ & ~0x00000001); } result.queues_ = queues_; } else { result.queues_ = queuesBuilder_.build(); } } private void buildPartial0(com.google.cloud.tasks.v2beta3.ListQueuesResponse 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.tasks.v2beta3.ListQueuesResponse) { return mergeFrom((com.google.cloud.tasks.v2beta3.ListQueuesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.tasks.v2beta3.ListQueuesResponse other) { if (other == com.google.cloud.tasks.v2beta3.ListQueuesResponse.getDefaultInstance()) return this; if (queuesBuilder_ == null) { if (!other.queues_.isEmpty()) { if (queues_.isEmpty()) { queues_ = other.queues_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureQueuesIsMutable(); queues_.addAll(other.queues_); } onChanged(); } } else { if (!other.queues_.isEmpty()) { if (queuesBuilder_.isEmpty()) { queuesBuilder_.dispose(); queuesBuilder_ = null; queues_ = other.queues_; bitField0_ = (bitField0_ & ~0x00000001); queuesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getQueuesFieldBuilder() : null; } else { queuesBuilder_.addAllMessages(other.queues_); } } } 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.tasks.v2beta3.Queue m = input.readMessage( com.google.cloud.tasks.v2beta3.Queue.parser(), extensionRegistry); if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.add(m); } else { queuesBuilder_.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.tasks.v2beta3.Queue> queues_ = java.util.Collections.emptyList(); private void ensureQueuesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { queues_ = new java.util.ArrayList<com.google.cloud.tasks.v2beta3.Queue>(queues_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.tasks.v2beta3.Queue, com.google.cloud.tasks.v2beta3.Queue.Builder, com.google.cloud.tasks.v2beta3.QueueOrBuilder> queuesBuilder_; /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public java.util.List<com.google.cloud.tasks.v2beta3.Queue> getQueuesList() { if (queuesBuilder_ == null) { return java.util.Collections.unmodifiableList(queues_); } else { return queuesBuilder_.getMessageList(); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public int getQueuesCount() { if (queuesBuilder_ == null) { return queues_.size(); } else { return queuesBuilder_.getCount(); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta3.Queue getQueues(int index) { if (queuesBuilder_ == null) { return queues_.get(index); } else { return queuesBuilder_.getMessage(index); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder setQueues(int index, com.google.cloud.tasks.v2beta3.Queue value) { if (queuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQueuesIsMutable(); queues_.set(index, value); onChanged(); } else { queuesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder setQueues( int index, com.google.cloud.tasks.v2beta3.Queue.Builder builderForValue) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.set(index, builderForValue.build()); onChanged(); } else { queuesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder addQueues(com.google.cloud.tasks.v2beta3.Queue value) { if (queuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQueuesIsMutable(); queues_.add(value); onChanged(); } else { queuesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder addQueues(int index, com.google.cloud.tasks.v2beta3.Queue value) { if (queuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQueuesIsMutable(); queues_.add(index, value); onChanged(); } else { queuesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder addQueues(com.google.cloud.tasks.v2beta3.Queue.Builder builderForValue) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.add(builderForValue.build()); onChanged(); } else { queuesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder addQueues( int index, com.google.cloud.tasks.v2beta3.Queue.Builder builderForValue) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.add(index, builderForValue.build()); onChanged(); } else { queuesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder addAllQueues( java.lang.Iterable<? extends com.google.cloud.tasks.v2beta3.Queue> values) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, queues_); onChanged(); } else { queuesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder clearQueues() { if (queuesBuilder_ == null) { queues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { queuesBuilder_.clear(); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public Builder removeQueues(int index) { if (queuesBuilder_ == null) { ensureQueuesIsMutable(); queues_.remove(index); onChanged(); } else { queuesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta3.Queue.Builder getQueuesBuilder(int index) { return getQueuesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta3.QueueOrBuilder getQueuesOrBuilder(int index) { if (queuesBuilder_ == null) { return queues_.get(index); } else { return queuesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public java.util.List<? extends com.google.cloud.tasks.v2beta3.QueueOrBuilder> getQueuesOrBuilderList() { if (queuesBuilder_ != null) { return queuesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(queues_); } } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta3.Queue.Builder addQueuesBuilder() { return getQueuesFieldBuilder() .addBuilder(com.google.cloud.tasks.v2beta3.Queue.getDefaultInstance()); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public com.google.cloud.tasks.v2beta3.Queue.Builder addQueuesBuilder(int index) { return getQueuesFieldBuilder() .addBuilder(index, com.google.cloud.tasks.v2beta3.Queue.getDefaultInstance()); } /** * * * <pre> * The list of queues. * </pre> * * <code>repeated .google.cloud.tasks.v2beta3.Queue queues = 1;</code> */ public java.util.List<com.google.cloud.tasks.v2beta3.Queue.Builder> getQueuesBuilderList() { return getQueuesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.tasks.v2beta3.Queue, com.google.cloud.tasks.v2beta3.Queue.Builder, com.google.cloud.tasks.v2beta3.QueueOrBuilder> getQueuesFieldBuilder() { if (queuesBuilder_ == null) { queuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.tasks.v2beta3.Queue, com.google.cloud.tasks.v2beta3.Queue.Builder, com.google.cloud.tasks.v2beta3.QueueOrBuilder>( queues_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); queues_ = null; } return queuesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * * To return the next page of results, call * [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues] with this * value as the * [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token]. * * If the next_page_token is empty, there are no more results. * * The page token is valid for only 2 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.tasks.v2beta3.ListQueuesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.tasks.v2beta3.ListQueuesResponse) private static final com.google.cloud.tasks.v2beta3.ListQueuesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.tasks.v2beta3.ListQueuesResponse(); } public static com.google.cloud.tasks.v2beta3.ListQueuesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListQueuesResponse> PARSER = new com.google.protobuf.AbstractParser<ListQueuesResponse>() { @java.lang.Override public ListQueuesResponse 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<ListQueuesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListQueuesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.tasks.v2beta3.ListQueuesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,193
java-iam/google-iam-policy/src/main/java/com/google/iam/v3beta/stub/HttpJsonPrincipalAccessBoundaryPoliciesStub.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.iam.v3beta.stub; import static com.google.iam.v3beta.PrincipalAccessBoundaryPoliciesClient.ListPrincipalAccessBoundaryPoliciesPagedResponse; import static com.google.iam.v3beta.PrincipalAccessBoundaryPoliciesClient.SearchPrincipalAccessBoundaryPolicyBindingsPagedResponse; import com.google.api.HttpRule; import com.google.api.core.BetaApi; 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.common.collect.ImmutableMap; import com.google.iam.v3beta.CreatePrincipalAccessBoundaryPolicyRequest; import com.google.iam.v3beta.DeletePrincipalAccessBoundaryPolicyRequest; import com.google.iam.v3beta.GetPrincipalAccessBoundaryPolicyRequest; import com.google.iam.v3beta.ListPrincipalAccessBoundaryPoliciesRequest; import com.google.iam.v3beta.ListPrincipalAccessBoundaryPoliciesResponse; import com.google.iam.v3beta.OperationMetadata; import com.google.iam.v3beta.PrincipalAccessBoundaryPolicy; import com.google.iam.v3beta.SearchPrincipalAccessBoundaryPolicyBindingsRequest; import com.google.iam.v3beta.SearchPrincipalAccessBoundaryPolicyBindingsResponse; import com.google.iam.v3beta.UpdatePrincipalAccessBoundaryPolicyRequest; import com.google.longrunning.Operation; import com.google.protobuf.Empty; 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 PrincipalAccessBoundaryPolicies service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @BetaApi @Generated("by gapic-generator-java") public class HttpJsonPrincipalAccessBoundaryPoliciesStub extends PrincipalAccessBoundaryPoliciesStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder() .add(Empty.getDescriptor()) .add(OperationMetadata.getDescriptor()) .add(PrincipalAccessBoundaryPolicy.getDescriptor()) .build(); private static final ApiMethodDescriptor<CreatePrincipalAccessBoundaryPolicyRequest, Operation> createPrincipalAccessBoundaryPolicyMethodDescriptor = ApiMethodDescriptor.<CreatePrincipalAccessBoundaryPolicyRequest, Operation>newBuilder() .setFullMethodName( "google.iam.v3beta.PrincipalAccessBoundaryPolicies/CreatePrincipalAccessBoundaryPolicy") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter .<CreatePrincipalAccessBoundaryPolicyRequest>newBuilder() .setPath( "/v3beta/{parent=organizations/*/locations/*}/principalAccessBoundaryPolicies", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CreatePrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CreatePrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam( fields, "principalAccessBoundaryPolicyId", request.getPrincipalAccessBoundaryPolicyId()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "principalAccessBoundaryPolicy", request.getPrincipalAccessBoundaryPolicy(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (CreatePrincipalAccessBoundaryPolicyRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor< GetPrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy> getPrincipalAccessBoundaryPolicyMethodDescriptor = ApiMethodDescriptor .<GetPrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy>newBuilder() .setFullMethodName( "google.iam.v3beta.PrincipalAccessBoundaryPolicies/GetPrincipalAccessBoundaryPolicy") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetPrincipalAccessBoundaryPolicyRequest>newBuilder() .setPath( "/v3beta/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetPrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetPrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<PrincipalAccessBoundaryPolicy>newBuilder() .setDefaultInstance(PrincipalAccessBoundaryPolicy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<UpdatePrincipalAccessBoundaryPolicyRequest, Operation> updatePrincipalAccessBoundaryPolicyMethodDescriptor = ApiMethodDescriptor.<UpdatePrincipalAccessBoundaryPolicyRequest, Operation>newBuilder() .setFullMethodName( "google.iam.v3beta.PrincipalAccessBoundaryPolicies/UpdatePrincipalAccessBoundaryPolicy") .setHttpMethod("PATCH") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter .<UpdatePrincipalAccessBoundaryPolicyRequest>newBuilder() .setPath( "/v3beta/{principalAccessBoundaryPolicy.name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<UpdatePrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "principalAccessBoundaryPolicy.name", request.getPrincipalAccessBoundaryPolicy().getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<UpdatePrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "updateMask", request.getUpdateMask()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "principalAccessBoundaryPolicy", request.getPrincipalAccessBoundaryPolicy(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (UpdatePrincipalAccessBoundaryPolicyRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<DeletePrincipalAccessBoundaryPolicyRequest, Operation> deletePrincipalAccessBoundaryPolicyMethodDescriptor = ApiMethodDescriptor.<DeletePrincipalAccessBoundaryPolicyRequest, Operation>newBuilder() .setFullMethodName( "google.iam.v3beta.PrincipalAccessBoundaryPolicies/DeletePrincipalAccessBoundaryPolicy") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter .<DeletePrincipalAccessBoundaryPolicyRequest>newBuilder() .setPath( "/v3beta/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeletePrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeletePrincipalAccessBoundaryPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "etag", request.getEtag()); serializer.putQueryParam(fields, "force", request.getForce()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeletePrincipalAccessBoundaryPolicyRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor< ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesResponse> listPrincipalAccessBoundaryPoliciesMethodDescriptor = ApiMethodDescriptor .<ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesResponse> newBuilder() .setFullMethodName( "google.iam.v3beta.PrincipalAccessBoundaryPolicies/ListPrincipalAccessBoundaryPolicies") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter .<ListPrincipalAccessBoundaryPoliciesRequest>newBuilder() .setPath( "/v3beta/{parent=organizations/*/locations/*}/principalAccessBoundaryPolicies", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListPrincipalAccessBoundaryPoliciesRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListPrincipalAccessBoundaryPoliciesRequest> 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 .<ListPrincipalAccessBoundaryPoliciesResponse>newBuilder() .setDefaultInstance( ListPrincipalAccessBoundaryPoliciesResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor< SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsResponse> searchPrincipalAccessBoundaryPolicyBindingsMethodDescriptor = ApiMethodDescriptor .<SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsResponse> newBuilder() .setFullMethodName( "google.iam.v3beta.PrincipalAccessBoundaryPolicies/SearchPrincipalAccessBoundaryPolicyBindings") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter .<SearchPrincipalAccessBoundaryPolicyBindingsRequest>newBuilder() .setPath( "/v3beta/{name=organizations/*/locations/*/principalAccessBoundaryPolicies/*}:searchPolicyBindings", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<SearchPrincipalAccessBoundaryPolicyBindingsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<SearchPrincipalAccessBoundaryPolicyBindingsRequest> 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 .<SearchPrincipalAccessBoundaryPolicyBindingsResponse>newBuilder() .setDefaultInstance( SearchPrincipalAccessBoundaryPolicyBindingsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<CreatePrincipalAccessBoundaryPolicyRequest, Operation> createPrincipalAccessBoundaryPolicyCallable; private final OperationCallable< CreatePrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy, OperationMetadata> createPrincipalAccessBoundaryPolicyOperationCallable; private final UnaryCallable< GetPrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy> getPrincipalAccessBoundaryPolicyCallable; private final UnaryCallable<UpdatePrincipalAccessBoundaryPolicyRequest, Operation> updatePrincipalAccessBoundaryPolicyCallable; private final OperationCallable< UpdatePrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy, OperationMetadata> updatePrincipalAccessBoundaryPolicyOperationCallable; private final UnaryCallable<DeletePrincipalAccessBoundaryPolicyRequest, Operation> deletePrincipalAccessBoundaryPolicyCallable; private final OperationCallable< DeletePrincipalAccessBoundaryPolicyRequest, Empty, OperationMetadata> deletePrincipalAccessBoundaryPolicyOperationCallable; private final UnaryCallable< ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesResponse> listPrincipalAccessBoundaryPoliciesCallable; private final UnaryCallable< ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesPagedResponse> listPrincipalAccessBoundaryPoliciesPagedCallable; private final UnaryCallable< SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsResponse> searchPrincipalAccessBoundaryPolicyBindingsCallable; private final UnaryCallable< SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsPagedResponse> searchPrincipalAccessBoundaryPolicyBindingsPagedCallable; private final BackgroundResource backgroundResources; private final HttpJsonOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonPrincipalAccessBoundaryPoliciesStub create( PrincipalAccessBoundaryPoliciesStubSettings settings) throws IOException { return new HttpJsonPrincipalAccessBoundaryPoliciesStub( settings, ClientContext.create(settings)); } public static final HttpJsonPrincipalAccessBoundaryPoliciesStub create( ClientContext clientContext) throws IOException { return new HttpJsonPrincipalAccessBoundaryPoliciesStub( PrincipalAccessBoundaryPoliciesStubSettings.newHttpJsonBuilder().build(), clientContext); } public static final HttpJsonPrincipalAccessBoundaryPoliciesStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonPrincipalAccessBoundaryPoliciesStub( PrincipalAccessBoundaryPoliciesStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonPrincipalAccessBoundaryPoliciesStub, 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 HttpJsonPrincipalAccessBoundaryPoliciesStub( PrincipalAccessBoundaryPoliciesStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonPrincipalAccessBoundaryPoliciesCallableFactory()); } /** * Constructs an instance of HttpJsonPrincipalAccessBoundaryPoliciesStub, 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 HttpJsonPrincipalAccessBoundaryPoliciesStub( PrincipalAccessBoundaryPoliciesStubSettings 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.GetOperation", HttpRule.newBuilder() .setGet("/v3beta/{name=projects/*/locations/*/operations/*}") .addAdditionalBindings( HttpRule.newBuilder() .setGet("/v3beta/{name=folders/*/locations/*/operations/*}") .build()) .addAdditionalBindings( HttpRule.newBuilder() .setGet("/v3beta/{name=organizations/*/locations/*/operations/*}") .build()) .build()) .build()); HttpJsonCallSettings<CreatePrincipalAccessBoundaryPolicyRequest, Operation> createPrincipalAccessBoundaryPolicyTransportSettings = HttpJsonCallSettings.<CreatePrincipalAccessBoundaryPolicyRequest, Operation>newBuilder() .setMethodDescriptor(createPrincipalAccessBoundaryPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<GetPrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy> getPrincipalAccessBoundaryPolicyTransportSettings = HttpJsonCallSettings .<GetPrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy> newBuilder() .setMethodDescriptor(getPrincipalAccessBoundaryPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<UpdatePrincipalAccessBoundaryPolicyRequest, Operation> updatePrincipalAccessBoundaryPolicyTransportSettings = HttpJsonCallSettings.<UpdatePrincipalAccessBoundaryPolicyRequest, Operation>newBuilder() .setMethodDescriptor(updatePrincipalAccessBoundaryPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add( "principal_access_boundary_policy.name", String.valueOf(request.getPrincipalAccessBoundaryPolicy().getName())); return builder.build(); }) .build(); HttpJsonCallSettings<DeletePrincipalAccessBoundaryPolicyRequest, Operation> deletePrincipalAccessBoundaryPolicyTransportSettings = HttpJsonCallSettings.<DeletePrincipalAccessBoundaryPolicyRequest, Operation>newBuilder() .setMethodDescriptor(deletePrincipalAccessBoundaryPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings< ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesResponse> listPrincipalAccessBoundaryPoliciesTransportSettings = HttpJsonCallSettings .<ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesResponse> newBuilder() .setMethodDescriptor(listPrincipalAccessBoundaryPoliciesMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings< SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsResponse> searchPrincipalAccessBoundaryPolicyBindingsTransportSettings = HttpJsonCallSettings .<SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsResponse> newBuilder() .setMethodDescriptor(searchPrincipalAccessBoundaryPolicyBindingsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); this.createPrincipalAccessBoundaryPolicyCallable = callableFactory.createUnaryCallable( createPrincipalAccessBoundaryPolicyTransportSettings, settings.createPrincipalAccessBoundaryPolicySettings(), clientContext); this.createPrincipalAccessBoundaryPolicyOperationCallable = callableFactory.createOperationCallable( createPrincipalAccessBoundaryPolicyTransportSettings, settings.createPrincipalAccessBoundaryPolicyOperationSettings(), clientContext, httpJsonOperationsStub); this.getPrincipalAccessBoundaryPolicyCallable = callableFactory.createUnaryCallable( getPrincipalAccessBoundaryPolicyTransportSettings, settings.getPrincipalAccessBoundaryPolicySettings(), clientContext); this.updatePrincipalAccessBoundaryPolicyCallable = callableFactory.createUnaryCallable( updatePrincipalAccessBoundaryPolicyTransportSettings, settings.updatePrincipalAccessBoundaryPolicySettings(), clientContext); this.updatePrincipalAccessBoundaryPolicyOperationCallable = callableFactory.createOperationCallable( updatePrincipalAccessBoundaryPolicyTransportSettings, settings.updatePrincipalAccessBoundaryPolicyOperationSettings(), clientContext, httpJsonOperationsStub); this.deletePrincipalAccessBoundaryPolicyCallable = callableFactory.createUnaryCallable( deletePrincipalAccessBoundaryPolicyTransportSettings, settings.deletePrincipalAccessBoundaryPolicySettings(), clientContext); this.deletePrincipalAccessBoundaryPolicyOperationCallable = callableFactory.createOperationCallable( deletePrincipalAccessBoundaryPolicyTransportSettings, settings.deletePrincipalAccessBoundaryPolicyOperationSettings(), clientContext, httpJsonOperationsStub); this.listPrincipalAccessBoundaryPoliciesCallable = callableFactory.createUnaryCallable( listPrincipalAccessBoundaryPoliciesTransportSettings, settings.listPrincipalAccessBoundaryPoliciesSettings(), clientContext); this.listPrincipalAccessBoundaryPoliciesPagedCallable = callableFactory.createPagedCallable( listPrincipalAccessBoundaryPoliciesTransportSettings, settings.listPrincipalAccessBoundaryPoliciesSettings(), clientContext); this.searchPrincipalAccessBoundaryPolicyBindingsCallable = callableFactory.createUnaryCallable( searchPrincipalAccessBoundaryPolicyBindingsTransportSettings, settings.searchPrincipalAccessBoundaryPolicyBindingsSettings(), clientContext); this.searchPrincipalAccessBoundaryPolicyBindingsPagedCallable = callableFactory.createPagedCallable( searchPrincipalAccessBoundaryPolicyBindingsTransportSettings, settings.searchPrincipalAccessBoundaryPolicyBindingsSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(createPrincipalAccessBoundaryPolicyMethodDescriptor); methodDescriptors.add(getPrincipalAccessBoundaryPolicyMethodDescriptor); methodDescriptors.add(updatePrincipalAccessBoundaryPolicyMethodDescriptor); methodDescriptors.add(deletePrincipalAccessBoundaryPolicyMethodDescriptor); methodDescriptors.add(listPrincipalAccessBoundaryPoliciesMethodDescriptor); methodDescriptors.add(searchPrincipalAccessBoundaryPolicyBindingsMethodDescriptor); return methodDescriptors; } public HttpJsonOperationsStub getHttpJsonOperationsStub() { return httpJsonOperationsStub; } @Override public UnaryCallable<CreatePrincipalAccessBoundaryPolicyRequest, Operation> createPrincipalAccessBoundaryPolicyCallable() { return createPrincipalAccessBoundaryPolicyCallable; } @Override public OperationCallable< CreatePrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy, OperationMetadata> createPrincipalAccessBoundaryPolicyOperationCallable() { return createPrincipalAccessBoundaryPolicyOperationCallable; } @Override public UnaryCallable<GetPrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy> getPrincipalAccessBoundaryPolicyCallable() { return getPrincipalAccessBoundaryPolicyCallable; } @Override public UnaryCallable<UpdatePrincipalAccessBoundaryPolicyRequest, Operation> updatePrincipalAccessBoundaryPolicyCallable() { return updatePrincipalAccessBoundaryPolicyCallable; } @Override public OperationCallable< UpdatePrincipalAccessBoundaryPolicyRequest, PrincipalAccessBoundaryPolicy, OperationMetadata> updatePrincipalAccessBoundaryPolicyOperationCallable() { return updatePrincipalAccessBoundaryPolicyOperationCallable; } @Override public UnaryCallable<DeletePrincipalAccessBoundaryPolicyRequest, Operation> deletePrincipalAccessBoundaryPolicyCallable() { return deletePrincipalAccessBoundaryPolicyCallable; } @Override public OperationCallable<DeletePrincipalAccessBoundaryPolicyRequest, Empty, OperationMetadata> deletePrincipalAccessBoundaryPolicyOperationCallable() { return deletePrincipalAccessBoundaryPolicyOperationCallable; } @Override public UnaryCallable< ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesResponse> listPrincipalAccessBoundaryPoliciesCallable() { return listPrincipalAccessBoundaryPoliciesCallable; } @Override public UnaryCallable< ListPrincipalAccessBoundaryPoliciesRequest, ListPrincipalAccessBoundaryPoliciesPagedResponse> listPrincipalAccessBoundaryPoliciesPagedCallable() { return listPrincipalAccessBoundaryPoliciesPagedCallable; } @Override public UnaryCallable< SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsResponse> searchPrincipalAccessBoundaryPolicyBindingsCallable() { return searchPrincipalAccessBoundaryPolicyBindingsCallable; } @Override public UnaryCallable< SearchPrincipalAccessBoundaryPolicyBindingsRequest, SearchPrincipalAccessBoundaryPolicyBindingsPagedResponse> searchPrincipalAccessBoundaryPolicyBindingsPagedCallable() { return searchPrincipalAccessBoundaryPolicyBindingsPagedCallable; } @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/jdk8
37,251
jdk/src/share/classes/com/sun/nio/sctp/SctpChannel.java
/* * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.nio.sctp; import java.net.SocketAddress; import java.net.InetAddress; import java.io.IOException; import java.util.Set; import java.nio.ByteBuffer; import java.nio.channels.spi.AbstractSelectableChannel; import java.nio.channels.spi.SelectorProvider; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; /** * A selectable channel for message-oriented connected SCTP sockets. * * <P> An SCTP channel can only control one SCTP association. * An {@code SCTPChannel} is created by invoking one of the * {@link #open open} methods of this class. A newly-created channel is open but * not yet connected, that is, there is no association setup with a remote peer. * An attempt to invoke an I/O operation upon an unconnected * channel will cause a {@link java.nio.channels.NotYetConnectedException} to be * thrown. An association can be setup by connecting the channel using one of * its {@link #connect connect} methods. Once connected, the channel remains * connected until it is closed. Whether or not a channel is connected may be * determined by invoking {@link #getRemoteAddresses getRemoteAddresses}. * * <p> SCTP channels support <i>non-blocking connection:</i>&nbsp;A * channel may be created and the process of establishing the link to * the remote socket may be initiated via the {@link #connect connect} method * for later completion by the {@link #finishConnect finishConnect} method. * Whether or not a connection operation is in progress may be determined by * invoking the {@link #isConnectionPending isConnectionPending} method. * * <p> Socket options are configured using the * {@link #setOption(SctpSocketOption,Object) setOption} method. An SCTP * channel support the following options: * <blockquote> * <table border summary="Socket options"> * <tr> * <th>Option Name</th> * <th>Description</th> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_DISABLE_FRAGMENTS * SCTP_DISABLE_FRAGMENTS} </td> * <td> Enables or disables message fragmentation </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_EXPLICIT_COMPLETE * SCTP_EXPLICIT_COMPLETE} </td> * <td> Enables or disables explicit message completion </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_FRAGMENT_INTERLEAVE * SCTP_FRAGMENT_INTERLEAVE} </td> * <td> Controls how the presentation of messages occur for the message * receiver </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_INIT_MAXSTREAMS * SCTP_INIT_MAXSTREAMS} </td> * <td> The maximum number of streams requested by the local endpoint during * association initialization </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_NODELAY SCTP_NODELAY} </td> * <td> Enables or disable a Nagle-like algorithm </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_PRIMARY_ADDR * SCTP_PRIMARY_ADDR} </td> * <td> Requests that the local SCTP stack use the given peer address as the * association primary </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SCTP_SET_PEER_PRIMARY_ADDR * SCTP_SET_PEER_PRIMARY_ADDR} </td> * <td> Requests that the peer mark the enclosed address as the association * primary </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SO_SNDBUF * SO_SNDBUF} </td> * <td> The size of the socket send buffer </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SO_RCVBUF * SO_RCVBUF} </td> * <td> The size of the socket receive buffer </td> * </tr> * <tr> * <td> {@link SctpStandardSocketOptions#SO_LINGER * SO_LINGER} </td> * <td> Linger on close if data is present (when configured in blocking mode * only) </td> * </tr> * </table> * </blockquote> * Additional (implementation specific) options may also be supported. The list * of options supported is obtained by invoking the {@link #supportedOptions() * supportedOptions} method. * * <p> SCTP channels are safe for use by multiple concurrent threads. * They support concurrent reading and writing, though at most one thread may be * reading and at most one thread may be writing at any given time. The * {@link #connect connect} and {@link #finishConnect * finishConnect} methods are mutually synchronized against each other, and * an attempt to initiate a send or receive operation while an invocation of one * of these methods is in progress will block until that invocation is complete. * * @since 1.7 */ @jdk.Exported public abstract class SctpChannel extends AbstractSelectableChannel { /** * Initializes a new instance of this class. * * @param provider * The selector provider for this channel */ protected SctpChannel(SelectorProvider provider) { super(provider); } /** * Opens an SCTP channel. * * <P> The new channel is unbound and unconnected. * * @return A new SCTP channel * * @throws UnsupportedOperationException * If the SCTP protocol is not supported * * @throws IOException * If an I/O error occurs */ public static SctpChannel open() throws IOException { return new sun.nio.ch.sctp.SctpChannelImpl((SelectorProvider)null); } /** * Opens an SCTP channel and connects it to a remote address. * * <P> This is a convenience method and is equivalent to evaluating the * following expression: * <blockquote><pre> * open().connect(remote, maxOutStreams, maxInStreams); * </pre></blockquote> * * @param remote * The remote address to which the new channel is to be connected * * @param maxOutStreams * The number of streams that the application wishes to be able * to send to. Must be non negative and no larger than {@code 65536}. * {@code 0} to use the endpoints default value. * * @param maxInStreams * The maximum number of inbound streams the application is prepared * to support. Must be non negative and no larger than {@code 65536}. * {@code 0} to use the endpoints default value. * * @return A new SCTP channel connected to the given address * * @throws java.nio.channels.AsynchronousCloseException * If another thread closes this channel * while the connect operation is in progress * * @throws java.nio.channels.ClosedByInterruptException * If another thread interrupts the current thread * while the connect operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws java.nio.channels.UnresolvedAddressException * If the given remote address is not fully resolved * * @throws java.nio.channels.UnsupportedAddressTypeException * If the type of the given remote address is not supported * * @throws SecurityException * If a security manager has been installed * and it does not permit access to the given remote peer * * @throws UnsupportedOperationException * If the SCTP protocol is not supported * * @throws IOException * If some other I/O error occurs */ public static SctpChannel open(SocketAddress remote, int maxOutStreams, int maxInStreams) throws IOException { SctpChannel ssc = SctpChannel.open(); ssc.connect(remote, maxOutStreams, maxInStreams); return ssc; } /** * Returns the association on this channel's socket. * * @return the association, or {@code null} if the channel's socket is not * connected. * * @throws ClosedChannelException * If the channel is closed * * @throws IOException * If some other I/O error occurs */ public abstract Association association() throws IOException; /** * Binds the channel's socket to a local address. * * <P> This method is used to establish a relationship between the socket * and the local addresses. Once a relationship is established then * the socket remains bound until the channel is closed. This relationship * may not necesssarily be with the address {@code local} as it may be removed * by {@link #unbindAddress unbindAddress}, but there will always be at least * one local address bound to the channel's socket once an invocation of * this method successfully completes. * * <P> Once the channel's socket has been successfully bound to a specific * address, that is not automatically assigned, more addresses * may be bound to it using {@link #bindAddress bindAddress}, or removed * using {@link #unbindAddress unbindAddress}. * * @param local * The local address to bind the socket, or {@code null} to * bind the socket to an automatically assigned socket address * * @return This channel * * @throws java.nio.channels.AlreadyConnectedException * If this channel is already connected * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.ConnectionPendingException * If a non-blocking connection operation is already in progress on this channel * * @throws java.nio.channels.AlreadyBoundException * If this channel is already bound * * @throws java.nio.channels.UnsupportedAddressTypeException * If the type of the given address is not supported * * @throws IOException * If some other I/O error occurs * * @throws SecurityException * If a security manager has been installed and its * {@link SecurityManager#checkListen checkListen} method denies * the operation */ public abstract SctpChannel bind(SocketAddress local) throws IOException; /** * Adds the given address to the bound addresses for the channel's * socket. * * <P> The given address must not be the {@link * java.net.InetAddress#isAnyLocalAddress wildcard} address. * The channel must be first bound using {@link #bind bind} before * invoking this method, otherwise {@link * java.nio.channels.NotYetBoundException} is thrown. The {@link #bind bind} * method takes a {@code SocketAddress} as its argument which typically * contains a port number as well as an address. Addresses subquently bound * using this method are simply addresses as the SCTP port number remains * the same for the lifetime of the channel. * * <P> Adding addresses to a connected association is optional functionality. * If the endpoint supports dynamic address reconfiguration then it may * send the appropriate message to the peer to change the peers address * lists. * * @param address * The address to add to the bound addresses for the socket * * @return This channel * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.ConnectionPendingException * If a non-blocking connection operation is already in progress on * this channel * * @throws java.nio.channels.NotYetBoundException * If this channel is not yet bound * * @throws java.nio.channels.AlreadyBoundException * If this channel is already bound to the given address * * @throws IllegalArgumentException * If address is {@code null} or the {@link * java.net.InetAddress#isAnyLocalAddress wildcard} address * * @throws IOException * If some other I/O error occurs */ public abstract SctpChannel bindAddress(InetAddress address) throws IOException; /** * Removes the given address from the bound addresses for the channel's * socket. * * <P> The given address must not be the {@link * java.net.InetAddress#isAnyLocalAddress wildcard} address. * The channel must be first bound using {@link #bind bind} before * invoking this method, otherwise {@link java.nio.channels.NotYetBoundException} * is thrown. If this method is invoked on a channel that does not have * {@code address} as one of its bound addresses or that has only one * local address bound to it, then this method throws * {@link IllegalUnbindException}. * The initial address that the channel's socket is bound to using {@link * #bind bind} may be removed from the bound addresses for the channel's socket. * * <P> Removing addresses from a connected association is optional * functionality. If the endpoint supports dynamic address reconfiguration * then it may send the appropriate message to the peer to change the peers * address lists. * * @param address * The address to remove from the bound addresses for the socket * * @return This channel * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.ConnectionPendingException * If a non-blocking connection operation is already in progress on * this channel * * @throws java.nio.channels.NotYetBoundException * If this channel is not yet bound * * @throws IllegalArgumentException * If address is {@code null} or the {@link * java.net.InetAddress#isAnyLocalAddress wildcard} address * * @throws IllegalUnbindException * If {@code address} is not bound to the channel's socket. or * the channel has only one address bound to it * * @throws IOException * If some other I/O error occurs */ public abstract SctpChannel unbindAddress(InetAddress address) throws IOException; /** * Connects this channel's socket. * * <P> If this channel is in non-blocking mode then an invocation of this * method initiates a non-blocking connection operation. If the connection * is established immediately, as can happen with a local connection, then * this method returns {@code true}. Otherwise this method returns * {@code false} and the connection operation must later be completed by * invoking the {@link #finishConnect finishConnect} method. * * <P> If this channel is in blocking mode then an invocation of this * method will block until the connection is established or an I/O error * occurs. * * <P> If a security manager has been installed then this method verifies * that its {@link java.lang.SecurityManager#checkConnect checkConnect} * method permits connecting to the address and port number of the given * remote peer. * * <p> This method may be invoked at any time. If a {@link #send send} or * {@link #receive receive} operation upon this channel is invoked while an * invocation of this method is in progress then that operation will first * block until this invocation is complete. If a connection attempt is * initiated but fails, that is, if an invocation of this method throws a * checked exception, then the channel will be closed. * * @param remote * The remote peer to which this channel is to be connected * * @return {@code true} if a connection was established, {@code false} if * this channel is in non-blocking mode and the connection * operation is in progress * * @throws java.nio.channels.AlreadyConnectedException * If this channel is already connected * * @throws java.nio.channels.ConnectionPendingException * If a non-blocking connection operation is already in progress on * this channel * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.AsynchronousCloseException * If another thread closes this channel * while the connect operation is in progress * * @throws java.nio.channels.ClosedByInterruptException * If another thread interrupts the current thread * while the connect operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws java.nio.channels.UnresolvedAddressException * If the given remote address is not fully resolved * * @throws java.nio.channels.UnsupportedAddressTypeException * If the type of the given remote address is not supported * * @throws SecurityException * If a security manager has been installed * and it does not permit access to the given remote peer * * @throws IOException * If some other I/O error occurs */ public abstract boolean connect(SocketAddress remote) throws IOException; /** * Connects this channel's socket. * * <P> This is a convience method and is equivalent to evaluating the * following expression: * <blockquote><pre> * setOption(SctpStandardSocketOptions.SCTP_INIT_MAXSTREAMS, SctpStandardSocketOption.InitMaxStreams.create(maxInStreams, maxOutStreams)) * .connect(remote); * </pre></blockquote> * * <P> The {@code maxOutStreams} and {@code maxInStreams} parameters * represent the maximum number of streams that the application wishes to be * able to send to and receive from. They are negotiated with the remote * peer and may be limited by the operating system. * * @param remote * The remote peer to which this channel is to be connected * * @param maxOutStreams * Must be non negative and no larger than {@code 65536}. * {@code 0} to use the endpoints default value. * * @param maxInStreams * Must be non negative and no larger than {@code 65536}. * {@code 0} to use the endpoints default value. * * @return {@code true} if a connection was established, {@code false} if * this channel is in non-blocking mode and the connection operation * is in progress * * @throws java.nio.channels.AlreadyConnectedException * If this channel is already connected * * @throws java.nio.channels.ConnectionPendingException * If a non-blocking connection operation is already in progress on * this channel * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.AsynchronousCloseException * If another thread closes this channel * while the connect operation is in progress * * @throws java.nio.channels.ClosedByInterruptException * If another thread interrupts the current thread * while the connect operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws java.nio.channels.UnresolvedAddressException * If the given remote address is not fully resolved * * @throws java.nio.channels.UnsupportedAddressTypeException * If the type of the given remote address is not supported * * @throws SecurityException * If a security manager has been installed * and it does not permit access to the given remote peer * * @throws IOException * If some other I/O error occurs */ public abstract boolean connect(SocketAddress remote, int maxOutStreams, int maxInStreams) throws IOException; /** * Tells whether or not a connection operation is in progress on this channel. * * @return {@code true} if, and only if, a connection operation has been initiated * on this channel but not yet completed by invoking the * {@link #finishConnect} method */ public abstract boolean isConnectionPending(); /** * Finishes the process of connecting an SCTP channel. * * <P> A non-blocking connection operation is initiated by placing a socket * channel in non-blocking mode and then invoking one of its {@link #connect * connect} methods. Once the connection is established, or the attempt has * failed, the channel will become connectable and this method may * be invoked to complete the connection sequence. If the connection * operation failed then invoking this method will cause an appropriate * {@link java.io.IOException} to be thrown. * * <P> If this channel is already connected then this method will not block * and will immediately return <tt>true</tt>. If this channel is in * non-blocking mode then this method will return <tt>false</tt> if the * connection process is not yet complete. If this channel is in blocking * mode then this method will block until the connection either completes * or fails, and will always either return <tt>true</tt> or throw a checked * exception describing the failure. * * <P> This method may be invoked at any time. If a {@link #send send} or {@link #receive receive} * operation upon this channel is invoked while an invocation of this * method is in progress then that operation will first block until this * invocation is complete. If a connection attempt fails, that is, if an * invocation of this method throws a checked exception, then the channel * will be closed. * * @return {@code true} if, and only if, this channel's socket is now * connected * * @throws java.nio.channels.NoConnectionPendingException * If this channel is not connected and a connection operation * has not been initiated * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.AsynchronousCloseException * If another thread closes this channel * while the connect operation is in progress * * @throws java.nio.channels.ClosedByInterruptException * If another thread interrupts the current thread * while the connect operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws IOException * If some other I/O error occurs */ public abstract boolean finishConnect() throws IOException; /** * Returns all of the socket addresses to which this channel's socket is * bound. * * @return All the socket addresses that this channel's socket is * bound to, or an empty {@code Set} if the channel's socket is not * bound * * @throws ClosedChannelException * If the channel is closed * * @throws IOException * If an I/O error occurs */ public abstract Set<SocketAddress> getAllLocalAddresses() throws IOException; /** * Returns all of the remote addresses to which this channel's socket * is connected. * * <P> If the channel is connected to a remote peer that is bound to * multiple addresses then it is these addresses that the channel's socket * is connected. * * @return All of the remote addresses to which this channel's socket * is connected, or an empty {@code Set} if the channel's socket is * not connected * * @throws ClosedChannelException * If the channel is closed * * @throws IOException * If an I/O error occurs */ public abstract Set<SocketAddress> getRemoteAddresses() throws IOException; /** * Shutdown a connection without closing the channel. * * <P> Sends a shutdown command to the remote peer, effectively preventing * any new data from being written to the socket by either peer. Further * sends will throw {@link java.nio.channels.ClosedChannelException}. The * channel remains open to allow the for any data (and notifications) to be * received that may have been sent by the peer before it received the * shutdown command. If the channel is already shutdown then invoking this * method has no effect. * * @return This channel * * @throws java.nio.channels.NotYetConnectedException * If this channel is not yet connected * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws IOException * If some other I/O error occurs */ public abstract SctpChannel shutdown() throws IOException; /** * Returns the value of a socket option. * * @param <T> * The type of the socket option value * * @param name * The socket option * * @return The value of the socket option. A value of {@code null} may be * a valid value for some socket options. * * @throws UnsupportedOperationException * If the socket option is not supported by this channel * * @throws ClosedChannelException * If this channel is closed * * @throws IOException * If an I/O error occurs * * @see SctpStandardSocketOptions */ public abstract <T> T getOption(SctpSocketOption<T> name) throws IOException; /** * Sets the value of a socket option. * * @param <T> * The type of the socket option value * * @param name * The socket option * * @param value * The value of the socket option. A value of {@code null} may be * a valid value for some socket options. * * @return This channel * * @throws UnsupportedOperationException * If the socket option is not supported by this channel * * @throws IllegalArgumentException * If the value is not a valid value for this socket option * * @throws ClosedChannelException * If this channel is closed * * @throws IOException * If an I/O error occurs * * @see SctpStandardSocketOptions */ public abstract <T> SctpChannel setOption(SctpSocketOption<T> name, T value) throws IOException; /** * Returns a set of the socket options supported by this channel. * * <P> This method will continue to return the set of options even after the * channel has been closed. * * @return A set of the socket options supported by this channel */ public abstract Set<SctpSocketOption<?>> supportedOptions(); /** * Returns an operation set identifying this channel's supported operations. * * <P> SCTP channels support connecting, reading, and writing, so this * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT} * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link * SelectionKey#OP_WRITE}<tt>)</tt>. </p> * * @return The valid-operation set */ @Override public final int validOps() { return (SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT); } /** * Receives a message into the given buffer and/or handles a notification. * * <P> If a message or notification is immediately available, or if this * channel is in blocking mode and one eventually becomes available, then * the message or notification is returned or handled, respectively. If this * channel is in non-blocking mode and a message or notification is not * immediately available then this method immediately returns {@code null}. * * <P> If this method receives a message it is copied into the given byte * buffer. The message is transferred into the given byte buffer starting at * its current position and the buffers position is incremented by the * number of bytes read. If there are fewer bytes remaining in the buffer * than are required to hold the message, or the underlying input buffer * does not contain the complete message, then an invocation of {@link * MessageInfo#isComplete isComplete} on the returned {@code * MessageInfo} will return {@code false}, and more invocations of this * method will be necessary to completely consume the messgae. Only * one message at a time will be partially delivered in any stream. The * socket option {@link SctpStandardSocketOptions#SCTP_FRAGMENT_INTERLEAVE * SCTP_FRAGMENT_INTERLEAVE} controls various aspects of what interlacing of * messages occurs. * * <P> If this method receives a notification then the appropriate method of * the given handler, if there is one, is invoked. If the handler returns * {@link HandlerResult#CONTINUE CONTINUE} then this method will try to * receive another message/notification, otherwise, if {@link * HandlerResult#RETURN RETURN} is returned this method will return {@code * null}. If an uncaught exception is thrown by the handler it will be * propagated up the stack through this method. * * <P> This method may be invoked at any time. If another thread has * already initiated a receive operation upon this channel, then an * invocation of this method will block until the first operation is * complete. The given handler is invoked without holding any locks used * to enforce the above synchronization policy, that way handlers * will not stall other threads from receiving. A handler should not invoke * the {@code receive} method of this channel, if it does an * {@link IllegalReceiveException} will be thrown. * * @param <T> * The type of the attachment * * @param dst * The buffer into which message bytes are to be transferred * * @param attachment * The object to attach to the receive operation; can be * {@code null} * * @param handler * A handler to handle notifications from the SCTP stack, or {@code * null} to ignore any notifications. * * @return The {@code MessageInfo}, {@code null} if this channel is in * non-blocking mode and no messages are immediately available or * the notification handler returns {@link HandlerResult#RETURN * RETURN} after handling a notification * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.AsynchronousCloseException * If another thread closes this channel * while the read operation is in progress * * @throws java.nio.channels.ClosedByInterruptException * If another thread interrupts the current thread * while the read operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws java.nio.channels.NotYetConnectedException * If this channel is not yet connected * * @throws IllegalReceiveException * If the given handler invokes the {@code receive} method of this * channel * * @throws IOException * If some other I/O error occurs */ public abstract <T> MessageInfo receive(ByteBuffer dst, T attachment, NotificationHandler<T> handler) throws IOException; /** * Sends a message via this channel. * * <P> If this channel is in non-blocking mode and there is sufficient room * in the underlying output buffer, or if this channel is in blocking mode * and sufficient room becomes available, then the remaining bytes in the * given byte buffer are transmitted as a single message. Sending a message * is atomic unless explicit message completion {@link * SctpStandardSocketOptions#SCTP_EXPLICIT_COMPLETE SCTP_EXPLICIT_COMPLETE} * socket option is enabled on this channel's socket. * * <P> The message is transferred from the byte buffer as if by a regular * {@link java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer) * write} operation. * * <P> The bytes will be written to the stream number that is specified by * {@link MessageInfo#streamNumber streamNumber} in the given {@code * messageInfo}. * * <P> This method may be invoked at any time. If another thread has already * initiated a send operation upon this channel, then an invocation of * this method will block until the first operation is complete. * * @param src * The buffer containing the message to be sent * * @param messageInfo * Ancillary data about the message to be sent * * @return The number of bytes sent, which will be either the number of * bytes that were remaining in the messages buffer when this method * was invoked or, if this channel is non-blocking, may be zero if * there was insufficient room for the message in the underlying * output buffer * * @throws InvalidStreamException * If {@code streamNumner} is negative or greater than or equal to * the maximum number of outgoing streams * * @throws java.nio.channels.ClosedChannelException * If this channel is closed * * @throws java.nio.channels.AsynchronousCloseException * If another thread closes this channel * while the read operation is in progress * * @throws java.nio.channels.ClosedByInterruptException * If another thread interrupts the current thread * while the read operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws java.nio.channels.NotYetConnectedException * If this channel is not yet connected * * @throws IOException * If some other I/O error occurs */ public abstract int send(ByteBuffer src, MessageInfo messageInfo) throws IOException; }
googleads/google-ads-java
37,183
google-ads-examples/src/main/java/com/google/ads/googleads/examples/advancedoperations/AddSmartCampaign.java
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ads.googleads.examples.advancedoperations; import static com.google.ads.googleads.v21.enums.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING; import com.beust.jcommander.Parameter; import com.google.ads.googleads.examples.utils.ArgumentNames; import com.google.ads.googleads.examples.utils.CodeSampleHelper; import com.google.ads.googleads.examples.utils.CodeSampleParams; import com.google.ads.googleads.lib.GoogleAdsClient; import com.google.ads.googleads.lib.utils.FieldMasks; import com.google.ads.googleads.v21.common.AdScheduleInfo; import com.google.ads.googleads.v21.common.AdTextAsset; import com.google.ads.googleads.v21.common.KeywordThemeInfo; import com.google.ads.googleads.v21.common.LocationInfo; import com.google.ads.googleads.v21.common.SmartCampaignAdInfo; import com.google.ads.googleads.v21.enums.AdGroupTypeEnum.AdGroupType; import com.google.ads.googleads.v21.enums.AdTypeEnum.AdType; import com.google.ads.googleads.v21.enums.AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType; import com.google.ads.googleads.v21.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType; import com.google.ads.googleads.v21.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod; import com.google.ads.googleads.v21.enums.BudgetTypeEnum.BudgetType; import com.google.ads.googleads.v21.enums.CampaignStatusEnum.CampaignStatus; import com.google.ads.googleads.v21.enums.DayOfWeekEnum.DayOfWeek; import com.google.ads.googleads.v21.enums.MinuteOfHourEnum.MinuteOfHour; import com.google.ads.googleads.v21.errors.GoogleAdsError; import com.google.ads.googleads.v21.errors.GoogleAdsException; import com.google.ads.googleads.v21.resources.Ad; import com.google.ads.googleads.v21.resources.SmartCampaignSetting; import com.google.ads.googleads.v21.services.GoogleAdsServiceClient; import com.google.ads.googleads.v21.services.KeywordThemeConstantServiceClient; import com.google.ads.googleads.v21.services.MutateGoogleAdsResponse; import com.google.ads.googleads.v21.services.MutateOperation; import com.google.ads.googleads.v21.services.MutateOperationResponse; import com.google.ads.googleads.v21.services.SmartCampaignSuggestServiceClient; import com.google.ads.googleads.v21.services.SmartCampaignSuggestionInfo; import com.google.ads.googleads.v21.services.SmartCampaignSuggestionInfo.BusinessContext; import com.google.ads.googleads.v21.services.SmartCampaignSuggestionInfo.LocationList; import com.google.ads.googleads.v21.services.SuggestKeywordThemeConstantsRequest; import com.google.ads.googleads.v21.services.SuggestKeywordThemeConstantsResponse; import com.google.ads.googleads.v21.services.SuggestKeywordThemesRequest; import com.google.ads.googleads.v21.services.SuggestKeywordThemesResponse; import com.google.ads.googleads.v21.services.SuggestKeywordThemesResponse.KeywordTheme; import com.google.ads.googleads.v21.services.SuggestSmartCampaignAdRequest; import com.google.ads.googleads.v21.services.SuggestSmartCampaignAdResponse; import com.google.ads.googleads.v21.services.SuggestSmartCampaignBudgetOptionsRequest; import com.google.ads.googleads.v21.services.SuggestSmartCampaignBudgetOptionsResponse; import com.google.ads.googleads.v21.services.SuggestSmartCampaignBudgetOptionsResponse.BudgetOption; import com.google.ads.googleads.v21.utils.ResourceNames; import com.google.protobuf.Descriptors.OneofDescriptor; import com.google.protobuf.Message; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** Demonstrates how to create a Smart Campaign. */ public class AddSmartCampaign { private static final long GEO_TARGET_CONSTANT = 1023191; private static final String COUNTRY_CODE = "US"; private static final String LANGUAGE_CODE = "en"; private static final String LANDING_PAGE_URL = "http://www.example.com"; private static final String PHONE_NUMBER = "800-555-0100"; private static final long BUDGET_TEMPORARY_ID = -1; private static final long SMART_CAMPAIGN_TEMPORARY_ID = -2; private static final long AD_GROUP_TEMPORARY_ID = -3; private static final int NUM_REQUIRED_HEADLINES = 3; private static final int NUM_REQUIRED_DESCRIPTIONS = 2; private static class AddSmartCampaignParams extends CodeSampleParams { @Parameter( names = ArgumentNames.CUSTOMER_ID, description = "The Google Ads customer ID", required = true) private long customerId; @Parameter( names = ArgumentNames.KEYWORD_TEXT, description = "A keyword text used to retrieve keyword theme constant suggestions from the" + " KeywordThemeConstantService. These keyword theme suggestions are generated" + " using auto-completion data for the given text and may help improve the" + " performance of the Smart campaign.") private String keywordText; @Parameter( names = ArgumentNames.FREE_FORM_KEYWORD_TEXT, description = "A keyword text used to create a freeForm keyword theme, which is entirely" + " user-specified and not derived from any suggestion service. Using free-form" + " keyword themes is typically not recommended because they are less effective" + " than suggested keyword themes, however they are useful in situations where a" + " very specific term needs to be targeted.") private String freeFormKeywordText; @Parameter( names = ArgumentNames.BUSINESS_PROFILE_LOCATION, description = "The resource name of a Business Profile location. This is required if a business name" + " is not provided. It can be retrieved using the Business Profile API" + " (https://developers.google.com/my-business/reference/businessinformation/rest/v1/accounts.locations)" + " or from the Business Profile UI" + " (https://support.google.com/business/answer/10737668") private String businessProfileLocation; @Parameter( names = ArgumentNames.BUSINESS_NAME, description = "The name of a Business Profile business. This is required if a business" + " location ID is not provided.") private String businessName; } public static void main(String[] args) throws IOException { AddSmartCampaignParams params = new AddSmartCampaignParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE"); // Optionally specifies a seed keyword. params.keywordText = null; // Optionally specifies a keyword that should be included as-is. params.freeFormKeywordText = null; // Must specify one of business profile location or business name. params.businessProfileLocation = "INSERT_BUSINESS_PROFILE_LOCATION_HERE"; params.businessName = "INSERT_BUSINESS_NAME"; } GoogleAdsClient googleAdsClient = null; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); System.exit(1); } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); System.exit(1); } try { new AddSmartCampaign() .runExample( googleAdsClient, params.customerId, params.keywordText, params.freeFormKeywordText, params.businessProfileLocation, params.businessName); } catch (GoogleAdsException gae) { // GoogleAdsException is the base class for most exceptions thrown by an API request. // Instances of this exception have a message and a GoogleAdsFailure that contains a // collection of GoogleAdsErrors that indicate the underlying causes of the // GoogleAdsException. System.err.printf( "Request ID %s failed due to GoogleAdsException. Underlying errors:%n", gae.getRequestId()); int i = 0; for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) { System.err.printf(" Error %d: %s%n", i++, googleAdsError); } System.exit(1); } } private void runExample( GoogleAdsClient googleAdsClient, long customerId, String keywordText, String freeFormKeywordText, String businessProfileLocation, String businessName) { // Checks that exactly one of businessProfileLocation and businessName is set. if (businessProfileLocation != null && businessName != null) { throw new IllegalArgumentException( "Both the business location resource name and business name are provided but they are" + " mutually exclusive. Please only set a value for one of them."); } if (businessProfileLocation == null && businessName == null) { throw new IllegalArgumentException( "Neither the business location resource name nor the business name are provided. Please" + " set a value for one of them."); } // [START add_smart_campaign_12] // Gets the SmartCampaignSuggestionInfo object which acts as the basis for many of the // entities necessary to create a Smart campaign. It will be reused a number of times to // retrieve suggestions for keyword themes, budget amount, ad creatives, and campaign criteria. SmartCampaignSuggestionInfo suggestionInfo = getSmartCampaignSuggestionInfo(googleAdsClient, businessProfileLocation, businessName); // Generates a list of keyword themes using the SuggestKeywordThemes method on the // SmartCampaignSuggestService. It is strongly recommended that you use this strategy for // generating keyword themes. List<KeywordTheme> keywordThemes = getKeywordThemeSuggestions(googleAdsClient, customerId, suggestionInfo); // If a keyword text is given, retrieves keyword theme constant suggestions from the // KeywordThemeConstantService, maps them to KeywordThemes, and appends them to the existing // list. // This logic should ideally only be used if the suggestions from the // getKeywordThemeSuggestions function are insufficient. if (keywordText != null) { keywordThemes.addAll(getKeywordTextAutoCompletions(googleAdsClient, keywordText)); } // Converts the list of KeywordThemes to a list of KeywordThemes objects. List<KeywordThemeInfo> keywordThemeInfos = getKeywordThemeInfos(keywordThemes); // Optionally includes any freeForm keywords in verbatim. // [START add_smart_campaign_13] if (freeFormKeywordText != null) { keywordThemeInfos.add( KeywordThemeInfo.newBuilder().setFreeFormKeywordTheme(freeFormKeywordText).build()); } // [END add_smart_campaign_13] // Includes the keyword suggestions in the overall SuggestionInfo object. suggestionInfo = suggestionInfo.toBuilder().addAllKeywordThemes(keywordThemeInfos).build(); // [END add_smart_campaign_12] // Generates a suggested daily budget. long suggestedDailyBudgetMicros = getBudgetSuggestions(googleAdsClient, customerId, suggestionInfo); // Creates adSuggestions. SmartCampaignAdInfo adSuggestions = getAdSuggestions(googleAdsClient, customerId, suggestionInfo); // Creates an array of operations which will create the campaign and related entities. List<MutateOperation> operations = new ArrayList( Arrays.asList( createCampaignBudgetOperation(customerId, suggestedDailyBudgetMicros), createSmartCampaignOperation(customerId), createSmartCampaignSettingOperation( customerId, businessProfileLocation, businessName), createAdGroupOperation(customerId), createAdGroupAdOperation(customerId, adSuggestions))); operations.addAll( createCampaignCriterionOperations(customerId, keywordThemeInfos, suggestionInfo)); // Issues a mutate request to add the various entities required for a smart campaign. sendMutateRequest(googleAdsClient, customerId, operations); } /** * Retrieves KeywordThemes using the given suggestion info. * * <p>Here we use the SuggestKeywordThemes method, which uses all of the business details included * in the given SmartCampaignSuggestionInfo instance to generate keyword theme suggestions. This * is the recommended way to generate keyword themes because it uses detailed information about * your business, its location, and website content to generate keyword themes. */ // [START add_smart_campaign_11] private List<KeywordTheme> getKeywordThemeSuggestions( GoogleAdsClient googleAdsClient, long customerId, SmartCampaignSuggestionInfo suggestionInfo) { // Creates the service client. try (SmartCampaignSuggestServiceClient client = googleAdsClient.getLatestVersion().createSmartCampaignSuggestServiceClient()) { // Sends the request. SuggestKeywordThemesResponse response = client.suggestKeywordThemes( SuggestKeywordThemesRequest.newBuilder() .setSuggestionInfo(suggestionInfo) .setCustomerId(String.valueOf(customerId)) .build()); // Prints some information about the result. System.out.printf( "Retrieved %d keyword theme suggestions from the SuggestKeywordThemes method.%n", response.getKeywordThemesCount()); return new ArrayList(response.getKeywordThemesList()); } } // [END add_smart_campaign_11] /** * Retrieves KeywordThemeConstants that are derived from autocomplete data for the given keyword * text, which are converted to a list of KeywordTheme objects before being returned. */ // [START add_smart_campaign] private List<KeywordTheme> getKeywordTextAutoCompletions( GoogleAdsClient googleAdsClient, String keywordText) { try (KeywordThemeConstantServiceClient client = googleAdsClient.getLatestVersion().createKeywordThemeConstantServiceClient()) { SuggestKeywordThemeConstantsRequest request = SuggestKeywordThemeConstantsRequest.newBuilder() .setQueryText(keywordText) .setCountryCode(COUNTRY_CODE) .setLanguageCode(LANGUAGE_CODE) .build(); SuggestKeywordThemeConstantsResponse response = client.suggestKeywordThemeConstants(request); // Converts the keyword theme constants to KeywordTheme instances for consistency with the // response from SmartCampaignSuggestService.SuggestKeywordThemes. return response.getKeywordThemeConstantsList().stream() .map( keywordThemeConstant -> KeywordTheme.newBuilder().setKeywordThemeConstant(keywordThemeConstant).build()) .collect(Collectors.toList()); } } // [END add_smart_campaign] /** * Builds a SmartCampaignSuggestionInfo object with business details. * * <p>The details are used by the SmartCampaignSuggestService to suggest a budget amount as well * as creatives for the ad. * * <p>Note that when retrieving ad creative suggestions it's required that the "final_url", * "language_code" and "keyword_themes" fields are set on the SmartCampaignSuggestionInfo * instance. * * @return SmartCampaignSuggestionInfo a SmartCampaignSuggestionInfo instance. */ // [START add_smart_campaign_9] private SmartCampaignSuggestionInfo getSmartCampaignSuggestionInfo( GoogleAdsClient googleAdsClient, String businessProfileLocation, String businessName) { SmartCampaignSuggestionInfo.Builder suggestionInfoBuilder = SmartCampaignSuggestionInfo.newBuilder() // Adds the URL of the campaign's landing page. .setFinalUrl(LANDING_PAGE_URL) // Adds the language code for the campaign. .setLanguageCode(LANGUAGE_CODE) // Constructs location information using the given geo target constant. It's also // possible to provide a geographic proximity using the "proximity" field, // for example: // .setProximity( // ProximityInfo.newBuilder() // .setAddress( // AddressInfo.newBuilder() // .setPostalCode(INSERT_POSTAL_CODE) // .setProvinceCode(INSERT_PROVINCE_CODE) // .setCountryCode(INSERT_COUNTRY_CODE) // .setProvinceName(INSERT_PROVINCE_NAME) // .setStreetAddress(INSERT_STREET_ADDRESS) // .setStreetAddress2(INSERT_STREET_ADDRESS_2) // .setCityName(INSERT_CITY_NAME) // .build()) // .setRadius(INSERT_RADIUS) // .setRadiusUnits(INSERT_RADIUS_UNITS) // .build()) // For more information on proximities see: // https://developers.google.com/google-ads/api/reference/rpc/latest/ProximityInfo // // Adds LocationInfo objects to the list of locations. You have the option of // providing multiple locations when using location-based suggestions. .setLocationList( LocationList.newBuilder() // Sets one location to the resource name of the given geo target constant. .addLocations( LocationInfo.newBuilder() .setGeoTargetConstant( ResourceNames.geoTargetConstant(GEO_TARGET_CONSTANT)) .build()) .build()) // Adds a schedule detailing which days of the week the business is open. // This schedule describes a schedule in which the business is open on // Mondays from 9am to 5pm. .addAdSchedules( AdScheduleInfo.newBuilder() // Sets the day of this schedule as Monday. .setDayOfWeek(DayOfWeek.MONDAY) // Sets the start hour to 9am. .setStartHour(9) // Sets the end hour to 5pm. .setEndHour(17) // Sets the start and end minute of zero, for example: 9:00 and 5:00. .setStartMinute(MinuteOfHour.ZERO) .setEndMinute(MinuteOfHour.ZERO) .build()); // Sets either of the business_profile_location or business_name, depending on whichever is // provided. if (businessProfileLocation != null) { suggestionInfoBuilder.setBusinessProfileLocation(businessProfileLocation); } else { suggestionInfoBuilder.setBusinessContext( BusinessContext.newBuilder().setBusinessName(businessName).build()); } return suggestionInfoBuilder.build(); } // [END add_smart_campaign_9] /** * Retrieves a suggested budget amount for a new budget. * * <p>Using the SmartCampaignSuggestService to determine a daily budget for new and existing Smart * campaigns is highly recommended because it helps the campaigns achieve optimal performance. * * @return the recommended budget amount in micros ($1 = 1_000_000 micros). */ // [START add_smart_campaign_1] private long getBudgetSuggestions( GoogleAdsClient googleAdsClient, long customerId, SmartCampaignSuggestionInfo suggestionInfo) { SuggestSmartCampaignBudgetOptionsRequest.Builder request = SuggestSmartCampaignBudgetOptionsRequest.newBuilder() .setCustomerId(String.valueOf(customerId)); // You can retrieve suggestions for an existing campaign by setting the // "campaign" field of the request equal to the resource name of a campaign // and leaving the rest of the request fields below unset: // request.setCampaign("INSERT_CAMPAIGN_RESOURCE_NAME_HERE"); // Uses the suggestion_info field instead, since these suggestions are for a new campaign. request.setSuggestionInfo(suggestionInfo); // Issues a request to retrieve a budget suggestion. try (SmartCampaignSuggestServiceClient client = googleAdsClient.getLatestVersion().createSmartCampaignSuggestServiceClient()) { SuggestSmartCampaignBudgetOptionsResponse response = client.suggestSmartCampaignBudgetOptions(request.build()); BudgetOption recommendation = response.getRecommended(); System.out.printf( "A daily budget amount of %d micros was suggested, garnering an estimated minimum of %d" + " clicks and an estimated maximum of %d per day.%n", recommendation.getDailyAmountMicros(), recommendation.getMetrics().getMinDailyClicks(), recommendation.getMetrics().getMaxDailyClicks()); return recommendation.getDailyAmountMicros(); } } // [END add_smart_campaign_1] /** * Retrieves creative suggestions for a Smart campaign ad. * * <p>Using the SmartCampaignSuggestService to suggest creatives for new and existing Smart * campaigns is highly recommended because it helps the campaigns achieve optimal performance. * * @return SmartCampaignAdInfo a SmartCampaignAdInfo instance with suggested headlines and * descriptions. */ // [START add_smart_campaign_10] private SmartCampaignAdInfo getAdSuggestions( GoogleAdsClient googleAdsClient, long customerId, SmartCampaignSuggestionInfo suggestionInfo) { // Unlike the SuggestSmartCampaignBudgetOptions method, it's only possible to use // suggestion_info to retrieve ad creative suggestions. // Issues a request to retrieve ad creative suggestions. try (SmartCampaignSuggestServiceClient smartCampaignSuggestService = googleAdsClient.getLatestVersion().createSmartCampaignSuggestServiceClient()) { SuggestSmartCampaignAdResponse response = smartCampaignSuggestService.suggestSmartCampaignAd( SuggestSmartCampaignAdRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .setSuggestionInfo(suggestionInfo) .build()); // The SmartCampaignAdInfo object in the response contains a list of up to three headlines // and two descriptions. Note that some of the suggestions may have empty strings as text. // Before setting these on the ad you should review them and filter out any empty values. SmartCampaignAdInfo adSuggestions = response.getAdInfo(); for (AdTextAsset headline : adSuggestions.getHeadlinesList()) { System.out.println(!headline.getText().isEmpty() ? headline.getText() : "None"); } for (AdTextAsset description : adSuggestions.getDescriptionsList()) { System.out.println(!description.getText().isEmpty() ? description.getText() : "None"); } return adSuggestions; } } // [END add_smart_campaign_10] /** * Creates a MutateOperation that creates a new CampaignBudget. * * <p>A temporary ID will be assigned to this campaign budget so that it can be referenced by * other objects being created in the same Mutate request. */ // [START add_smart_campaign_2] private MutateOperation createCampaignBudgetOperation(long customerId, long dailyBudgetMicros) { MutateOperation.Builder builder = MutateOperation.newBuilder(); builder .getCampaignBudgetOperationBuilder() .getCreateBuilder() .setName("Smart campaign budget " + CodeSampleHelper.getShortPrintableDateTime()) .setDeliveryMethod(BudgetDeliveryMethod.STANDARD) // A budget used for Smart campaigns must have the type SMART_CAMPAIGN. .setType(BudgetType.SMART_CAMPAIGN) // The suggested budget amount from the SmartCampaignSuggestService is for a _daily_ budget. // We don't need to specify that here, because the budget period already defaults to DAILY. .setAmountMicros(dailyBudgetMicros) // Sets a temporary ID in the budget's resource name so it can be referenced by the campaign // in later steps. .setResourceName(ResourceNames.campaignBudget(customerId, BUDGET_TEMPORARY_ID)); return builder.build(); } // [END add_smart_campaign_2] /** * Creates a MutateOperation that creates a new Smart campaign. * * <p>A temporary ID will be assigned to this campaign so that it can be referenced by other * objects being created in the same Mutate request. */ // [START add_smart_campaign_3] private MutateOperation createSmartCampaignOperation(long customerId) { MutateOperation.Builder builder = MutateOperation.newBuilder(); builder .getCampaignOperationBuilder() .getCreateBuilder() .setName("Smart campaign " + CodeSampleHelper.getShortPrintableDateTime()) .setStatus(CampaignStatus.PAUSED) .setAdvertisingChannelType(AdvertisingChannelType.SMART) .setAdvertisingChannelSubType(AdvertisingChannelSubType.SMART_CAMPAIGN) // Assigns the resource name with a temporary ID. .setResourceName(ResourceNames.campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID)) .setCampaignBudget(ResourceNames.campaignBudget(customerId, BUDGET_TEMPORARY_ID)) // Declares whether this campaign serves political ads targeting the EU. .setContainsEuPoliticalAdvertising(DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING); return builder.build(); } // [END add_smart_campaign_3] /** * Creates a MutateOperation to create a new SmartCampaignSetting. * * <p>SmartCampaignSettings are unique in that they only support UPDATE operations, which are used * to update and create them. Below we will use a temporary ID in the resource name to associate * it with the campaign created in the previous step. */ // [START add_smart_campaign_4] private MutateOperation createSmartCampaignSettingOperation( long customerId, String businessProfileLocation, String businessName) { MutateOperation.Builder builder = MutateOperation.newBuilder(); SmartCampaignSetting.Builder settingBuilder = builder .getSmartCampaignSettingOperationBuilder() .getUpdateBuilder() // Sets a temporary ID in the campaign setting's resource name to associate it with // the campaign created in the previous step. .setResourceName( ResourceNames.smartCampaignSetting(customerId, SMART_CAMPAIGN_TEMPORARY_ID)); // Configures the SmartCampaignSetting using many of the same details used to // generate a budget suggestion. settingBuilder .setFinalUrl(LANDING_PAGE_URL) .setAdvertisingLanguageCode(LANGUAGE_CODE) .getPhoneNumberBuilder() .setCountryCode(COUNTRY_CODE) .setPhoneNumber(PHONE_NUMBER); // It's required that either a business profile location resource name or a business name is // added to the SmartCampaignSetting. if (businessProfileLocation != null) { settingBuilder.setBusinessProfileLocation(businessProfileLocation); } else { settingBuilder.setBusinessName(businessName); } builder .getSmartCampaignSettingOperationBuilder() .setUpdateMask(FieldMasks.allSetFieldsOf(settingBuilder.build())); return builder.build(); } // [END add_smart_campaign_4] /** * Creates a MutateOperation that creates a new ad group. * * <p>A temporary ID will be used in the campaign resource name for this ad group to associate it * with the Smart campaign created in earlier steps. A temporary ID will also be used for its own * resource name so that we can associate an ad group ad with it later in the process. * * <p>Only one ad group can be created for a given Smart campaign. */ // [START add_smart_campaign_5] private MutateOperation createAdGroupOperation(long customerId) { MutateOperation.Builder builder = MutateOperation.newBuilder(); builder .getAdGroupOperationBuilder() .getCreateBuilder() .setResourceName(ResourceNames.adGroup(customerId, AD_GROUP_TEMPORARY_ID)) .setName("Smart campaign ad group " + CodeSampleHelper.getShortPrintableDateTime()) .setCampaign(ResourceNames.campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID)) .setType(AdGroupType.SMART_CAMPAIGN_ADS); return builder.build(); } // [END add_smart_campaign_5] /** * Creates a MutateOperation that creates a new ad group ad. * * <p>A temporary ID will be used in the ad group resource name for this ad group ad to associate * it with the ad group created in earlier steps. */ // [START add_smart_campaign_6] private MutateOperation createAdGroupAdOperation( long customerId, SmartCampaignAdInfo adSuggestions) { MutateOperation.Builder opBuilder = MutateOperation.newBuilder(); // Constructs an Ad instance containing a SmartCampaignAd. Ad.Builder adBuilder = Ad.newBuilder(); adBuilder .setType(AdType.SMART_CAMPAIGN_AD) // The SmartCampaignAdInfo object includes headlines and descriptions retrieved // from the suggestSmartCampaignAd method. It's recommended that users review and approve or // update these creatives before they're set on the ad. It's possible that some or all of // these assets may contain empty texts, which should not be set on the ad and instead // should be replaced with meaningful texts from the user. Below we just accept the // creatives that were suggested while filtering out empty assets, but individual workflows // will vary here. .getSmartCampaignAdBuilder() .addAllHeadlines( adSuggestions.getHeadlinesList().stream() .filter(h -> h.hasText()) .collect(Collectors.toList())) .addAllDescriptions( adSuggestions.getDescriptionsList().stream() .filter(d -> d.hasText()) .collect(Collectors.toList())); // Adds additional headlines + descriptions if we didn't get enough back from the suggestion // service. int numHeadlines = adBuilder.getSmartCampaignAdBuilder().getHeadlinesCount(); if (numHeadlines < NUM_REQUIRED_HEADLINES) { for (int i = 0; i < NUM_REQUIRED_HEADLINES - numHeadlines; ++i) { adBuilder .getSmartCampaignAdBuilder() .addHeadlines(AdTextAsset.newBuilder().setText("Placeholder headline " + i).build()); } } if (adSuggestions.getDescriptionsCount() < NUM_REQUIRED_DESCRIPTIONS) { int numDescriptions = adBuilder.getSmartCampaignAdBuilder().getDescriptionsCount(); for (int i = 0; i < NUM_REQUIRED_DESCRIPTIONS - numDescriptions; ++i) { adBuilder .getSmartCampaignAdBuilder() .addDescriptions( AdTextAsset.newBuilder().setText("Placeholder description " + i).build()); } } opBuilder .getAdGroupAdOperationBuilder() .getCreateBuilder() .setAdGroup(ResourceNames.adGroup(customerId, AD_GROUP_TEMPORARY_ID)) .setAd(adBuilder); return opBuilder.build(); } // [END add_smart_campaign_6] // [START add_smart_campaign_8] /** * Creates {@link com.google.ads.googleads.v21.resources.CampaignCriterion} operations for add * each {@link KeywordThemeInfo}. */ private Collection<? extends MutateOperation> createCampaignCriterionOperations( long customerId, List<KeywordThemeInfo> keywordThemeInfos, SmartCampaignSuggestionInfo suggestionInfo) { List<MutateOperation> keywordThemeOperations = keywordThemeInfos.stream() .map( keywordTheme -> { MutateOperation.Builder builder = MutateOperation.newBuilder(); builder .getCampaignCriterionOperationBuilder() .getCreateBuilder() .setCampaign(ResourceNames.campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID)) .setKeywordTheme(keywordTheme); return builder.build(); }) .collect(Collectors.toList()); List<MutateOperation> locationOperations = suggestionInfo.getLocationList().getLocationsList().stream() .map( location -> { MutateOperation.Builder builder = MutateOperation.newBuilder(); builder .getCampaignCriterionOperationBuilder() .getCreateBuilder() .setCampaign(ResourceNames.campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID)) .setLocation(location); return builder.build(); }) .collect(Collectors.toList()); return Stream.concat(keywordThemeOperations.stream(), locationOperations.stream()) .collect(Collectors.toList()); } // [END add_smart_campaign_8] // [START add_smart_campaign_7] /** * Sends a mutate request with a group of mutate operations. * * <p>The {@link GoogleAdsServiceClient} allows batching together a list of operations. These are * executed sequentially, and later operations my refer to previous operations via temporary IDs. * For more detail on this, please refer to * https://developers.google.com/google-ads/api/docs/batch-processing/temporary-ids. */ private void sendMutateRequest( GoogleAdsClient googleAdsClient, long customerId, List<MutateOperation> operations) { try (GoogleAdsServiceClient client = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { MutateGoogleAdsResponse outerResponse = client.mutate(String.valueOf(customerId), operations); for (MutateOperationResponse innerResponse : outerResponse.getMutateOperationResponsesList()) { OneofDescriptor oneofDescriptor = innerResponse.getDescriptorForType().getOneofs().stream() .filter(o -> o.getName().equals("response")) .findFirst() .get(); Message createdEntity = (Message) innerResponse.getField(innerResponse.getOneofFieldDescriptor(oneofDescriptor)); String resourceName = (String) createdEntity.getField( createdEntity.getDescriptorForType().findFieldByName("resource_name")); System.out.printf( "Created a(n) %s with resource name: '%s'.%n", createdEntity.getClass().getSimpleName(), resourceName); } } } // [END add_smart_campaign_7] /** * Provides a helper method to convert a list of {@link KeywordTheme} objects to a list of {@link * KeywordThemeInfo} objects. */ private List<KeywordThemeInfo> getKeywordThemeInfos(List<KeywordTheme> keywordThemes) { return keywordThemes.stream() .map( keywordTheme -> { KeywordThemeInfo.Builder keywordThemeInfoBuilder = KeywordThemeInfo.newBuilder(); // Checks if the keyword_theme_constant field is set. if (keywordTheme.hasKeywordThemeConstant()) { return keywordThemeInfoBuilder .setKeywordThemeConstant( keywordTheme.getKeywordThemeConstant().getResourceName()) .build(); } else if (keywordTheme.hasFreeFormKeywordTheme()) { return keywordThemeInfoBuilder .setFreeFormKeywordTheme(keywordTheme.getFreeFormKeywordTheme()) .build(); } else { throw new IllegalArgumentException( String.format("A malformed KeywordTheme was encountered: %s", keywordTheme)); } }) .collect(Collectors.toCollection(ArrayList::new)); } }
apache/royale-compiler
36,894
compiler/src/main/java/org/apache/royale/compiler/internal/tree/as/NodeBase.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.royale.compiler.internal.tree.as; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import antlr.Token; import org.apache.royale.compiler.common.ASModifier; import org.apache.royale.compiler.common.ISourceLocation; import org.apache.royale.compiler.common.SourceLocation; import org.apache.royale.compiler.config.CompilerDiagnosticsConstants; import org.apache.royale.compiler.definitions.IDefinition; import org.apache.royale.compiler.filespecs.IFileSpecification; import org.apache.royale.compiler.internal.common.Counter; import org.apache.royale.compiler.internal.definitions.DefinitionBase; import org.apache.royale.compiler.internal.parsing.as.OffsetLookup; import org.apache.royale.compiler.internal.scopes.ASFileScope; import org.apache.royale.compiler.internal.scopes.ASScope; import org.apache.royale.compiler.internal.scopes.TypeScope; import org.apache.royale.compiler.internal.semantics.PostProcessStep; import org.apache.royale.compiler.problems.ICompilerProblem; import org.apache.royale.compiler.scopes.IASScope; import org.apache.royale.compiler.tree.ASTNodeID; import org.apache.royale.compiler.tree.as.IASNode; import org.apache.royale.compiler.tree.as.IFileNode; import org.apache.royale.compiler.tree.as.IImportNode; import org.apache.royale.compiler.tree.as.IPackageNode; import org.apache.royale.compiler.tree.as.IScopedNode; import org.apache.royale.compiler.tree.mxml.IMXMLClassDefinitionNode; import org.apache.royale.compiler.workspaces.IWorkspace; /** * Base class for ActionScript parse tree nodes */ public abstract class NodeBase extends SourceLocation implements IASNode { /** * Used in calls to CheapArray functions. It represents the type of objects * that appear in fSymbols. */ protected static final IASNode[] emptyNodeArray = new IASNode[0]; /** * Combine the attributes from the base class with the attributes specific * to this class * * @param superAttributes The attributes of the base class. * @param myAttributes The attributes of this class. * @return attribute value */ public static String[] combineAttributes(String[] superAttributes, String[] myAttributes) { String[] combinedAttributes = new String[superAttributes.length + myAttributes.length]; for (int i = 0; i < superAttributes.length; i++) { combinedAttributes[i] = superAttributes[i]; } for (int i = 0; i < myAttributes.length; i++) { combinedAttributes[superAttributes.length + i] = myAttributes[i]; } return combinedAttributes; } /** * Constructor. */ public NodeBase() { super(); parent = null; if (Counter.COUNT_NODES) countNodes(); } /** * Parent node. * <p> * Methods (even in NodeBase itself) should use getParent() instead of * accessing this member directly. getParent() is overridden in FileNode to * do something special when the FileNode represents a shared file. */ protected IASNode parent; @Override public IASNode getParent() { return parent; } @Override public int getChildCount() { return 0; } @Override public IASNode getChild(int i) { return null; } @Override public IFileSpecification getFileSpecification() { // TODO Make sure this works with include processing!!! ASFileScope fileScope = getFileScope(); IWorkspace w = fileScope.getWorkspace(); if ((CompilerDiagnosticsConstants.diagnostics & CompilerDiagnosticsConstants.WORKSPACE) == CompilerDiagnosticsConstants.WORKSPACE) System.out.println("NodeBase waiting for lock in getFileSpecification"); IFileSpecification fs = w.getFileSpecification(fileScope.getContainingPath()); if ((CompilerDiagnosticsConstants.diagnostics & CompilerDiagnosticsConstants.WORKSPACE) == CompilerDiagnosticsConstants.WORKSPACE) System.out.println("NodeBase done with lock in getFileSpecification"); return fs; } @Override public int getSpanningStart() { return getStart(); } /** * Get the node type as a string. For example, this will return * "IdentifierNode" for an IdentifierNode. * * @return the node type */ public String getNodeKind() { return getClass().getSimpleName(); } @Override public boolean contains(int offset) { return getAbsoluteStart() < offset && getAbsoluteEnd() >= offset; } /** * Determine whether the offset "loosely" fits within this node. With normal * nodes, this will return true if the offset matches fLocation.fStart or * fLocation.fEnd or anything in between. With bogus nodes (which have * fStart == fEnd), this will return true if the offset comes after fStart * and before any other nodes in the parse tree * * @param offset the offset to test * @return true if the offset is "loosely" contained within this node */ public boolean looselyContains(int offset) { if (getAbsoluteStart() == getAbsoluteEnd()) { // This is a bogus placeholder node (generally an identifier that's been inserted to complete an expression). // We'll pretend that it extends all the way to the start offset of the next node. Now to find that next node... if (getAbsoluteStart() <= offset) { NodeBase containingNode = (NodeBase)getParent(); // Step 1: Find a node that extends beyond the target offset while (containingNode != null && containingNode.getAbsoluteEnd() <= getAbsoluteEnd()) containingNode = (NodeBase)containingNode.getParent(); // If no such node exists, we know that there aren't any tokens in the parse // tree that end after this bogus token. So we can go ahead and pretend this node // extends all the way out. if (containingNode == null) return true; // Step 2: Find a node that starts after the target offset IASNode succeedingNode = containingNode.getSucceedingNode(getAbsoluteEnd()); // If no such node exists, we know that there aren't any tokens in the parse // tree that start after this bogus token. So we can go ahead and pretend this // node extends all the way out. if (succeedingNode == null) return true; // Otherwise, pretend this node extends all the way to the next token. if (succeedingNode.getAbsoluteStart() >= offset) return true; } } else { // This is a real token. See if the test offset fits within (including the boundaries, since we're looking // at "loose" containment. return getAbsoluteStart() <= offset && getAbsoluteEnd() >= offset; } return false; } @Override public IASNode getSucceedingNode(int offset) { // This node ends before the offset is even reached. This is hopeless. if (getAbsoluteEnd() <= offset) return null; // See if one of our children starts after the offset for (int i = 0; i < getChildCount(); i++) { IASNode child = getChild(i); if (child.getAbsoluteStart() > offset) return child; else if (child.getAbsoluteEnd() > offset) return child.getSucceedingNode(offset); } return null; } /** * Determine whether this node is transparent. If a node is transparent, it * can never be returned from getContainingNode... the offset will be * considered part of the parent node instead. * * @return true if the node is transparent */ public boolean isTransparent() { return false; } @Override public IASNode getContainingNode(int offset) { // This node doesn't even contain the offset. This is hopeless. if (!contains(offset)) { return null; } IASNode containingNode = this; int childCount = getChildCount(); // See if the offset is contained within one of our children. for (int i = 0; i < childCount; i++) { IASNode child = getChild(i); if (child.getAbsoluteStart() <= offset) { if (child.contains(offset)) { containingNode = child.getContainingNode(offset); if (child instanceof NodeBase && ((NodeBase)child).canContinueContainmentSearch(containingNode, this, i, true)) continue; break; } } else { if (child instanceof NodeBase && ((NodeBase)child).canContinueContainmentSearch(containingNode, this, i, false)) continue; // We've passed this offset without finding a child that contains it. This is // the nearest enclosing node. break; } } // Make sure we don't return a transparent node while (containingNode != null && containingNode instanceof NodeBase && ((NodeBase)containingNode).isTransparent()) { containingNode = containingNode.getParent(); } return containingNode; } @Override public boolean isTerminal() { return false; } @Override public IScopedNode getContainingScope() { return (IScopedNode)getAncestorOfType(IScopedNode.class); } // TODO Can probably eliminate this. protected boolean canContinueContainmentSearch(IASNode containingNode, IASNode currentNode, int childOffset, boolean offsetsStillValid) { return false; } @Override public IASNode getAncestorOfType(Class<? extends IASNode> nodeType) { IASNode current = getParent(); while (current != null && !(nodeType.isInstance(current))) current = current.getParent(); if (current != null) return current; return null; } @Override public String getPackageName() { // Starting with this node's parent, walk up the parent chain // looking for a package node or an MXML class definition node. // These two types of nodes understand what their package is. IASNode current = getParent(); while (current != null && !(current instanceof IPackageNode || current instanceof IMXMLClassDefinitionNode)) { current = current.getParent(); } if (current instanceof IPackageNode) return ((IPackageNode)current).getPackageName(); else if (current instanceof IMXMLClassDefinitionNode) return ((IMXMLClassDefinitionNode)current).getPackageName(); return null; } /** * Set the start offset of the node to fall just after the token. Used * during parsing. * * @param token start this node after this token */ public void startAfter(Token token) { if (token instanceof ISourceLocation) { startAfter((ISourceLocation) token); } } /** * Set the start offset of the node to fall just after the token. Used * during parsing. * * @param location start this node after this token */ public final void startAfter(ISourceLocation location) { final int end = location.getEnd(); if (end != UNKNOWN) { setSourcePath(location.getSourcePath()); setStart(end); setLine(location.getEndLine()); setColumn(location.getEndColumn()); } } /** * Set the start offset of the node to fall just before the token. Used * during parsing. * * @param token start this node before this token */ public final void startBefore(Token token) { if (token instanceof ISourceLocation) startBefore((ISourceLocation)token); } /** * Set the start offset of the node to fall just before the token. Used * during parsing. * * @param location start this node before this token */ public final void startBefore(ISourceLocation location) { final int start = location.getStart(); if (start != UNKNOWN) { setSourcePath(location.getSourcePath()); setStart(start); setLine(location.getLine()); setColumn(location.getColumn()); } } /** * Set the end offset of the node to fall just after the token. Used during * parsing. * * @param token end this node after this token */ public final void endAfter(Token token) { if (token instanceof ISourceLocation) endAfter((ISourceLocation)token); } /** * Set the end offset of the node to fall just after the token. Used during * parsing. * * @param location end this node after this token */ public final void endAfter(ISourceLocation location) { final int end = location.getEnd(); if (end != UNKNOWN) { setEnd(end); setEndLine(location.getEndLine()); setEndColumn(location.getEndColumn()); } } /** * Set the end offset of the node to fall just before the token. Used during * parsing. * * @param token start this node before this token */ public final void endBefore(Token token) { if (token instanceof ISourceLocation) endBefore((ISourceLocation)token); } /** * Set the end offset of the node to fall just before the token. Used during * parsing. * * @param location start this node before this token */ public final void endBefore(ISourceLocation location) { final int start = location.getStart(); if (start != UNKNOWN) { setEnd(start); setEndLine(location.getLine()); setEndColumn(location.getColumn()); } } /** * Set the start and end offsets of the node to coincide with the token's * offsets. Used during parsing. * * @param token the token to take the offsets from */ public final void span(Token token) { if (token instanceof ISourceLocation) span((ISourceLocation)token); } /** * Set the start and end offsets of the node to coincide with the tokens' * offsets. Used during parsing. * * @param firstToken the token to take the start offset and line number from * @param lastToken the token to take the end offset from */ public final void span(Token firstToken, Token lastToken) { if (firstToken instanceof ISourceLocation && lastToken instanceof ISourceLocation) span((ISourceLocation)firstToken, (ISourceLocation)lastToken); } /** * Set the start and end offsets of the node. Used during parsing. * * @param start start offset for the node * @param end end offset for the node * @param line line number for the node * @deprecated Use span(int,int,int,int,int,int) instead so that endLine and endColumn are included */ public final void span(int start, int end, int line, int column) { span(start, end, line, column, -1, -1); } /** * Set the start and end offsets of the node. Used during parsing. * * @param start start offset for the node * @param end end offset for the node * @param line line number for the node */ public final void span(int start, int end, int line, int column, int endLine, int endColumn) { setStart(start); setEnd(end); setLine(line); setColumn(column); setEndLine(endLine); setEndColumn(endColumn); } public Collection<ICompilerProblem> runPostProcess(EnumSet<PostProcessStep> set, ASScope containingScope) { ArrayList<ICompilerProblem> problems = new ArrayList<ICompilerProblem>(10); normalize(set.contains(PostProcessStep.CALCULATE_OFFSETS)); if (set.contains(PostProcessStep.POPULATE_SCOPE) || set.contains(PostProcessStep.RECONNECT_DEFINITIONS)) analyze(set, containingScope, problems); return problems; } protected void analyze(EnumSet<PostProcessStep> set, ASScope scope, Collection<ICompilerProblem> problems) { int childrenSize = getChildCount(); // Populate this scope with definitions found among the children for (int i = 0; i < childrenSize; i++) { IASNode child = getChild(i); if (child instanceof NodeBase) { if (child.getParent() == null) ((NodeBase)child).setParent(this); ((NodeBase)child).analyze(set, scope, problems); } } } /** * Changes the position of two children in our tree. Neither child can be * null and both must have the same parent * * @param child the child to replace target * @param target the child to replace child */ protected void swapChildren(NodeBase child, NodeBase target) { //no op in this impl } /** * Replaces the child with the given target. The child will be removed from * the tree, and its parentage will be updated * * @param child the {@link NodeBase} to replace * @param target the {@link NodeBase} to replace the replaced */ protected void replaceChild(NodeBase child, NodeBase target) { //no op } /** * Normalize the tree. Move custom children into the real child list and * fill in missing offsets so that offset lookup will work. Used during * parsing. */ public void normalize(boolean fillInOffsets) { // The list of children doesn't change, so the child count should be constant throughout the loop int childrenSize = getChildCount(); // Normalize the regular children for (int i = 0; i < childrenSize; i++) { IASNode child = getChild(i); if (child instanceof NodeBase) { ((NodeBase)child).setParent(this); ((NodeBase)child).normalize(fillInOffsets); } } // Add the special children (which get normalized as they're added) if (childrenSize == 0) setChildren(fillInOffsets); // Fill in offsets based on the child nodes if (fillInOffsets) fillInOffsets(); // fill in any dangling ends //fillEndOffsets(); // get rid of unused child space } /** * Allow various subclasses to do special kludgy things like identify * mx.core.Application.application */ protected void connectedToProjectScope() { // The list of children doesn't change, so the child count should be constant throughout the loop int childrenSize = getChildCount(); for (int i = 0; i < childrenSize; i++) { IASNode child = getChild(i); if (child instanceof NodeBase) ((NodeBase)child).connectedToProjectScope(); } } /** * If this node has custom children (names, arguments, etc), shove them into * the list of children. Used during parsing. */ protected void setChildren(boolean fillInOffsets) { //nothing in this class } /** * If the start and end offsets haven't been set explicitly, fill them in * based on the offsets of the children. Used during parsing. If the end * offset is less than any of the kids' offsets, change fLocation.fEnd to * encompass kids. */ protected void fillInOffsets() { int numChildren = getChildCount(); if (numChildren > 0) { int start = getAbsoluteStart(); int end = getAbsoluteEnd(); if (start == -1) { for (int i = 0; i < numChildren; i++) { IASNode child = getChild(i); int childStart = child.getAbsoluteStart(); if (childStart != -1) { if (getSourcePath() == null) setSourcePath(child.getSourcePath()); setStart(childStart); setLine(child.getLine()); setColumn(child.getColumn()); break; } } } for (int i = numChildren - 1; i >= 0; i--) { IASNode child = getChild(i); int childEnd = child.getAbsoluteEnd(); if (childEnd != -1) { if (end < childEnd) { setEnd(childEnd); setEndLine(child.getEndLine()); setEndColumn(child.getEndColumn()); } break; } } } } /** * Set the parent node. Used during parsing. * * @param parent parent node */ public void setParent(NodeBase parent) { this.parent = parent; } /** * Get the nearest containing scope for this node. Used during type * decoration. * * @return nearest containing scope for this node */ // TODO Make this more efficient using overrides on BlockNode and FileNode. public IScopedNode getScopeNode() { if (this instanceof IScopedNode && ((IScopedNode)this).getScope() != null) return (IScopedNode)this; IASNode parent = getParent(); if (parent != null && parent instanceof NodeBase) return ((NodeBase)parent).getScopeNode(); return null; } /** * Get the path of the file in which this parse tree node resides. * <p> * The tree builder can set a node's origin source file using * {@link #setSourcePath(String)}. If the source path was set, return the * source path; Otherwise, use root {@link FileNode}'s path. * * @return file path that contains this node */ public String getContainingFilePath() { String path = getSourcePath(); if (path != null) return path; final FileNode fileNode = (FileNode)getAncestorOfType(FileNode.class); if (fileNode != null) return fileNode.getSourcePath(); return null; } /** * For debugging only. Displays this node and its children in a form like * this: * * <pre> * FileNode "D:\tests\UIComponent.as" 0:0 0-467464 D:\tests\UIComponent.as * PackageNode "mx.core" 12:1 436-465667 D:\tests\UIComponent.as * FullNameNode "mx.core" 0:0 444-451 null * IdentifierNode "mx" 12:9 444-446 D:\tests\UIComponent.as * IdentifierNode "core" 12:12 447-451 D:\tests\UIComponent.as * ScopedBlockNode 13:1 454-465667 D:\tests\UIComponent.as * ImportNode "flash.accessibility.Accessibility" 14:1 457-497 D:\tests\UIComponent.as * FullNameNode "flash.accessibility.Accessibility" 0:0 464-497 null * FullNameNode "flash.accessibility" 0:0 464-483 null * IdentifierNode "flash" 14:8 464-469 D:\tests\UIComponent.as * IdentifierNode "accessibility" 14:14 470-483 D:\tests\UIComponent.as * IdentifierNode "Accessibility" 14:28 484-497 D:\tests\UIComponent.as * ... * </pre> * <p> * Subclasses may not override this, because we want to maintain regularity * for how all nodes display. */ @Override public final String toString() { StringBuilder sb = new StringBuilder(); buildStringRecursive(sb, 0, false); return sb.toString(); } /** * For debugging only. Called by {@code toString()}, and recursively by * itself, to display this node on one line and each descendant node on * subsequent indented lines. * * * */ public void buildStringRecursive(StringBuilder sb, int level, boolean skipSrcPath) { // Indent two spaces for each nesting level. for (int i = 0; i < level; i++) { sb.append(" "); } // Build the string that represents this node. buildOuterString(sb, skipSrcPath); sb.append('\n'); //To test scopes in ParserSuite if(skipSrcPath && (this instanceof IScopedNode)) { for (int i = 0; i < level+1; i++) sb.append(" "); sb.append("[Scope]"); sb.append("\n"); IScopedNode scopedNode = (IScopedNode)this; IASScope scope = scopedNode.getScope(); Collection<IDefinition> definitions = scope.getAllLocalDefinitions(); for(IDefinition def : definitions) { for (int i = 0; i < level+2; i++) sb.append(" "); ((DefinitionBase)def).buildString(sb, false); sb.append('\n'); } } // Recurse over the child nodes. int n = getChildCount(); for (int i = 0; i < n; i++) { NodeBase child = (NodeBase)getChild(i); // The child can be null if we're toString()'ing // in the debugger during tree building. if (child != null) child.buildStringRecursive(sb, level + 1, skipSrcPath); } } /** * For debugging only. Called by {@code buildStringRecursive()} to display * information for this node only. * <p> * An example is * * <pre> * PackageNode "mx.core" 12:1 436-465667 D:\tests\UIComponent.as * </pre>. * <p> * The type of node (PackageNode) is displayed first, followed by * node-specific information ("mx.core") followed by location information in * the form * * <pre> * line:column start-end sourcepath * </pre> * */ private void buildOuterString(StringBuilder sb, boolean skipSrcPath) { // First display the type of node, as represented by // the short name of the node class. sb.append(getNodeKind()); sb.append("(").append(getNodeID().name()).append(")"); sb.append(' '); // Display optional node-specific information in the middle. if (buildInnerString(sb)) sb.append(' '); // The SourceLocation superclass handles producing a string such as // "17:5 160-188" C:/test.as". if(skipSrcPath) sb.append(getOffsetsString()); else sb.append(super.toString()); } /** * For debugging only. This method is called by {@code buildOuterString()}. * It is overridden by subclasses to display optional node-specific * information in the middle of the string, between the node type and the * location information. */ protected boolean buildInnerString(StringBuilder sb) { return false; } /** * For debugging only. */ public String getInnerString() { StringBuilder sb = new StringBuilder(); buildInnerString(sb); return sb.toString(); } public ASFileScope getFileScope() { ASScope scope = getASScope(); assert scope != null; while (scope != null && !(scope instanceof ASFileScope)) { scope = scope.getContainingScope(); assert scope != null; } return (ASFileScope)scope; } /** * @return {@link OffsetLookup} object for the current tree or null. */ protected final OffsetLookup tryGetOffsetLookup() { // Try FileNode.getOffsetLookup() final IASNode fileNode = getAncestorOfType(IFileNode.class); if (fileNode != null) return ((IFileNode)fileNode).getOffsetLookup(); else return null; } /** * Get's the {@link IWorkspace} in which this {@link NodeBase} lives. * * @return The {@link IWorkspace} in which this {@link NodeBase} lives. */ public IWorkspace getWorkspace() { ASFileScope fileScope = getFileScope(); if (fileScope == null) { return null; } return fileScope.getWorkspace(); } /** * Get the scope this Node uses for name resolution as an ASScope. * * @return the ASScope for this node, or null if there isn't one. */ public ASScope getASScope() { IScopedNode scopeNode = getContainingScope(); IASScope scope = scopeNode != null ? scopeNode.getScope() : null; // If the ScopedNode had a null scope, keep looking up the tree until we // find one with a non-null scope. // TODO: Is it a bug that an IScopedNode returns null for it's scope? // TODO: this seems like a leftover from block scoping - for example, a // TODO: ForLoopNode is an IScopedNode, but it doesn't really have a scope while (scope == null && scopeNode != null) { scopeNode = scopeNode.getContainingScope(); scope = scopeNode != null ? scopeNode.getScope() : null; } if (scope instanceof TypeScope) { TypeScope typeScope = (TypeScope)scope; if (this instanceof BaseDefinitionNode) { if (((BaseDefinitionNode)this).hasModifier(ASModifier.STATIC)) scope = typeScope.getStaticScope(); else scope = typeScope.getInstanceScope(); } else { // Do we need the class or instance scope? BaseDefinitionNode bdn = (BaseDefinitionNode)this.getAncestorOfType(BaseDefinitionNode.class); if (bdn instanceof ClassNode) { // We must be loose code in a class scope = typeScope.getStaticScope(); } else { if (bdn != null && bdn.hasModifier(ASModifier.STATIC) // Namespaces are always static || bdn instanceof NamespaceNode) scope = typeScope.getStaticScope(); else scope = typeScope.getInstanceScope(); } } } ASScope asScope = scope instanceof ASScope ? (ASScope)scope : null; return asScope; } /** * Get the node's local start offset. */ @Override public int getStart() { final OffsetLookup offsetLookup = tryGetOffsetLookup(); if (offsetLookup != null) { // to handle start offset in an included file int absoluteOffset = getAbsoluteStart(); final String pathBeforeCaret = offsetLookup.getFilename(absoluteOffset - 1); // if the offset is the first offset in the included file return without adjustment if (pathBeforeCaret != null && pathBeforeCaret.equals(getSourcePath())) return offsetLookup.getLocalOffset(absoluteOffset-1)+1; return offsetLookup.getLocalOffset(absoluteOffset); } return super.getStart(); } /** * Get the node's local end offset. */ @Override public int getEnd() { final OffsetLookup offsetLookup = tryGetOffsetLookup(); return offsetLookup != null ? // to handle end offset in an included file offsetLookup.getLocalOffset(super.getEnd() - 1) + 1 : super.getEnd(); } /** * @return The node's absolute start offset. */ @Override public int getAbsoluteStart() { return super.getStart(); } /** * @return The node's absolute end offset. */ @Override public int getAbsoluteEnd() { return super.getEnd(); } /** * Collects the import nodes that are descendants of this node * but which are not contained within a scoped node. * <p> * This is a helper method for {@link IScopedNode#getAllImportNodes}(). * Since that method walks up the chain of scoped nodes, we don't want * to look inside scoped nodes that were already processed. * * @param importNodes The collection of import nodes being built. */ public void collectImportNodes(Collection<IImportNode> importNodes) { int childCount = getChildCount(); for (int i = 0; i < childCount; ++i) { IASNode child = getChild(i); if (child instanceof IImportNode) importNodes.add((IImportNode)child); else if (!(child instanceof IScopedNode)) ((NodeBase)child).collectImportNodes(importNodes); } } /** * Used only in asserts. */ public boolean verify() { // Verify the id. ASTNodeID id = getNodeID(); assert id != null && id != ASTNodeID.InvalidNodeID && id != ASTNodeID.UnknownID : "Definition has bad id"; // TODO: Verify the source location eventually. // assert getSourcePath() != null : "Node has null source path:\n" + toString(); // assert getStart() != UNKNOWN : "Node has unknown start:\n" + toString(); // assert getEnd() != UNKNOWN : "Node has unknown end:\n" + toString(); // assert getLine() != UNKNOWN : "Node has unknown line:\n" + toString(); // assert getColumn() != UNKNOWN : "Node has unknown column:\n" + toString(); // Verify the children. int n = getChildCount(); for (int i = 0; i < n; i++) { // Any null children? NodeBase child = (NodeBase)getChild(i); assert child != null : "Node has null child"; // Does each child have this node as its parent? // (Note: Two node classes override getParent() to not return the parent, // so exclude these for now.) if (!(child instanceof NamespaceIdentifierNode || child instanceof QualifiedNamespaceExpressionNode)) { assert child.getParent() == this : "Child node has bad parent"; } // Recurse on each child. child.verify(); } return true; } /** * Counts various types of nodes that are created, * as well as the total number of nodes. */ private void countNodes() { if ((CompilerDiagnosticsConstants.diagnostics & CompilerDiagnosticsConstants.COUNTER) == CompilerDiagnosticsConstants.COUNTER) System.out.println("ASScopeBase incrementing counter for " + getClass().getSimpleName()); Counter counter = Counter.getInstance(); counter.incrementCount(getClass().getSimpleName()); counter.incrementCount("nodes"); if ((CompilerDiagnosticsConstants.diagnostics & CompilerDiagnosticsConstants.COUNTER) == CompilerDiagnosticsConstants.COUNTER) System.out.println("ASScopeBase done incrementing counter for " + getClass().getSimpleName()); } }
googleapis/google-cloud-java
36,908
java-securitycenter/proto-google-cloud-securitycenter-v1p1beta1/src/main/java/com/google/cloud/securitycenter/v1p1beta1/UpdateOrganizationSettingsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/securitycenter/v1p1beta1/securitycenter_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.securitycenter.v1p1beta1; /** * * * <pre> * Request message for updating an organization's settings. * </pre> * * Protobuf type {@code google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest} */ public final class UpdateOrganizationSettingsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) UpdateOrganizationSettingsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateOrganizationSettingsRequest.newBuilder() to construct. private UpdateOrganizationSettingsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateOrganizationSettingsRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateOrganizationSettingsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycenter.v1p1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1p1beta1_UpdateOrganizationSettingsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycenter.v1p1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1p1beta1_UpdateOrganizationSettingsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.class, com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.Builder .class); } private int bitField0_; public static final int ORGANIZATION_SETTINGS_FIELD_NUMBER = 1; private com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings organizationSettings_; /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the organizationSettings field is set. */ @java.lang.Override public boolean hasOrganizationSettings() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The organizationSettings. */ @java.lang.Override public com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings getOrganizationSettings() { return organizationSettings_ == null ? com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.getDefaultInstance() : organizationSettings_; } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsOrBuilder getOrganizationSettingsOrBuilder() { return organizationSettings_ == null ? com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.getDefaultInstance() : organizationSettings_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getOrganizationSettings()); } 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, getOrganizationSettings()); } 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.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest)) { return super.equals(obj); } com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest other = (com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) obj; if (hasOrganizationSettings() != other.hasOrganizationSettings()) return false; if (hasOrganizationSettings()) { if (!getOrganizationSettings().equals(other.getOrganizationSettings())) 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 (hasOrganizationSettings()) { hash = (37 * hash) + ORGANIZATION_SETTINGS_FIELD_NUMBER; hash = (53 * hash) + getOrganizationSettings().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.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest 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 updating an organization's settings. * </pre> * * Protobuf type {@code google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycenter.v1p1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1p1beta1_UpdateOrganizationSettingsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycenter.v1p1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1p1beta1_UpdateOrganizationSettingsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.class, com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.Builder .class); } // Construct using // com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getOrganizationSettingsFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; organizationSettings_ = null; if (organizationSettingsBuilder_ != null) { organizationSettingsBuilder_.dispose(); organizationSettingsBuilder_ = 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.securitycenter.v1p1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1p1beta1_UpdateOrganizationSettingsRequest_descriptor; } @java.lang.Override public com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest getDefaultInstanceForType() { return com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest build() { com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest buildPartial() { com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest result = new com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.organizationSettings_ = organizationSettingsBuilder_ == null ? organizationSettings_ : organizationSettingsBuilder_.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.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) { return mergeFrom( (com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest other) { if (other == com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest .getDefaultInstance()) return this; if (other.hasOrganizationSettings()) { mergeOrganizationSettings(other.getOrganizationSettings()); } 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( getOrganizationSettingsFieldBuilder().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.securitycenter.v1p1beta1.OrganizationSettings organizationSettings_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings, com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.Builder, com.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsOrBuilder> organizationSettingsBuilder_; /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the organizationSettings field is set. */ public boolean hasOrganizationSettings() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The organizationSettings. */ public com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings getOrganizationSettings() { if (organizationSettingsBuilder_ == null) { return organizationSettings_ == null ? com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.getDefaultInstance() : organizationSettings_; } else { return organizationSettingsBuilder_.getMessage(); } } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setOrganizationSettings( com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings value) { if (organizationSettingsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } organizationSettings_ = value; } else { organizationSettingsBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setOrganizationSettings( com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.Builder builderForValue) { if (organizationSettingsBuilder_ == null) { organizationSettings_ = builderForValue.build(); } else { organizationSettingsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeOrganizationSettings( com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings value) { if (organizationSettingsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && organizationSettings_ != null && organizationSettings_ != com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings .getDefaultInstance()) { getOrganizationSettingsBuilder().mergeFrom(value); } else { organizationSettings_ = value; } } else { organizationSettingsBuilder_.mergeFrom(value); } if (organizationSettings_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearOrganizationSettings() { bitField0_ = (bitField0_ & ~0x00000001); organizationSettings_ = null; if (organizationSettingsBuilder_ != null) { organizationSettingsBuilder_.dispose(); organizationSettingsBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.Builder getOrganizationSettingsBuilder() { bitField0_ |= 0x00000001; onChanged(); return getOrganizationSettingsFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsOrBuilder getOrganizationSettingsOrBuilder() { if (organizationSettingsBuilder_ != null) { return organizationSettingsBuilder_.getMessageOrBuilder(); } else { return organizationSettings_ == null ? com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.getDefaultInstance() : organizationSettings_; } } /** * * * <pre> * Required. The organization settings resource to update. * </pre> * * <code> * .google.cloud.securitycenter.v1p1beta1.OrganizationSettings organization_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings, com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.Builder, com.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsOrBuilder> getOrganizationSettingsFieldBuilder() { if (organizationSettingsBuilder_ == null) { organizationSettingsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings, com.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.Builder, com.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsOrBuilder>( getOrganizationSettings(), getParentForChildren(), isClean()); organizationSettings_ = null; } return organizationSettingsBuilder_; } 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 FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * The FieldMask to use when updating the settings resource. * * If empty all mutable fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) private static final com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest(); } public static com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateOrganizationSettingsRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateOrganizationSettingsRequest>() { @java.lang.Override public UpdateOrganizationSettingsRequest 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<UpdateOrganizationSettingsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateOrganizationSettingsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,767
java-shopping-merchant-datasources/proto-google-shopping-merchant-datasources-v1beta/src/main/java/com/google/shopping/merchant/datasources/v1beta/DataSourceReference.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/merchant/datasources/v1beta/datasourcetypes.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.datasources.v1beta; /** * * * <pre> * Data source reference can be used to manage related data sources within the * data source service. * </pre> * * Protobuf type {@code google.shopping.merchant.datasources.v1beta.DataSourceReference} */ public final class DataSourceReference extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.datasources.v1beta.DataSourceReference) DataSourceReferenceOrBuilder { private static final long serialVersionUID = 0L; // Use DataSourceReference.newBuilder() to construct. private DataSourceReference(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DataSourceReference() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DataSourceReference(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.datasources.v1beta.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1beta_DataSourceReference_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.datasources.v1beta.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1beta_DataSourceReference_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.datasources.v1beta.DataSourceReference.class, com.google.shopping.merchant.datasources.v1beta.DataSourceReference.Builder.class); } private int dataSourceIdCase_ = 0; @SuppressWarnings("serial") private java.lang.Object dataSourceId_; public enum DataSourceIdCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { SELF(1), PRIMARY_DATA_SOURCE_NAME(3), SUPPLEMENTAL_DATA_SOURCE_NAME(2), DATASOURCEID_NOT_SET(0); private final int value; private DataSourceIdCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static DataSourceIdCase valueOf(int value) { return forNumber(value); } public static DataSourceIdCase forNumber(int value) { switch (value) { case 1: return SELF; case 3: return PRIMARY_DATA_SOURCE_NAME; case 2: return SUPPLEMENTAL_DATA_SOURCE_NAME; case 0: return DATASOURCEID_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public DataSourceIdCase getDataSourceIdCase() { return DataSourceIdCase.forNumber(dataSourceIdCase_); } public static final int SELF_FIELD_NUMBER = 1; /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return Whether the self field is set. */ @java.lang.Override public boolean hasSelf() { return dataSourceIdCase_ == 1; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return The self. */ @java.lang.Override public boolean getSelf() { if (dataSourceIdCase_ == 1) { return (java.lang.Boolean) dataSourceId_; } return false; } public static final int PRIMARY_DATA_SOURCE_NAME_FIELD_NUMBER = 3; /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the primaryDataSourceName field is set. */ public boolean hasPrimaryDataSourceName() { return dataSourceIdCase_ == 3; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The primaryDataSourceName. */ public java.lang.String getPrimaryDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 3) { dataSourceId_ = s; } return s; } } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for primaryDataSourceName. */ public com.google.protobuf.ByteString getPrimaryDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 3) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SUPPLEMENTAL_DATA_SOURCE_NAME_FIELD_NUMBER = 2; /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the supplementalDataSourceName field is set. */ public boolean hasSupplementalDataSourceName() { return dataSourceIdCase_ == 2; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The supplementalDataSourceName. */ public java.lang.String getSupplementalDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 2) { dataSourceId_ = s; } return s; } } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The bytes for supplementalDataSourceName. */ public com.google.protobuf.ByteString getSupplementalDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 2) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (dataSourceIdCase_ == 1) { output.writeBool(1, (boolean) ((java.lang.Boolean) dataSourceId_)); } if (dataSourceIdCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, dataSourceId_); } if (dataSourceIdCase_ == 3) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, dataSourceId_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (dataSourceIdCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeBoolSize( 1, (boolean) ((java.lang.Boolean) dataSourceId_)); } if (dataSourceIdCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, dataSourceId_); } if (dataSourceIdCase_ == 3) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, dataSourceId_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.merchant.datasources.v1beta.DataSourceReference)) { return super.equals(obj); } com.google.shopping.merchant.datasources.v1beta.DataSourceReference other = (com.google.shopping.merchant.datasources.v1beta.DataSourceReference) obj; if (!getDataSourceIdCase().equals(other.getDataSourceIdCase())) return false; switch (dataSourceIdCase_) { case 1: if (getSelf() != other.getSelf()) return false; break; case 3: if (!getPrimaryDataSourceName().equals(other.getPrimaryDataSourceName())) return false; break; case 2: if (!getSupplementalDataSourceName().equals(other.getSupplementalDataSourceName())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (dataSourceIdCase_) { case 1: hash = (37 * hash) + SELF_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSelf()); break; case 3: hash = (37 * hash) + PRIMARY_DATA_SOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getPrimaryDataSourceName().hashCode(); break; case 2: hash = (37 * hash) + SUPPLEMENTAL_DATA_SOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getSupplementalDataSourceName().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.shopping.merchant.datasources.v1beta.DataSourceReference prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Data source reference can be used to manage related data sources within the * data source service. * </pre> * * Protobuf type {@code google.shopping.merchant.datasources.v1beta.DataSourceReference} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.datasources.v1beta.DataSourceReference) com.google.shopping.merchant.datasources.v1beta.DataSourceReferenceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.datasources.v1beta.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1beta_DataSourceReference_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.datasources.v1beta.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1beta_DataSourceReference_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.datasources.v1beta.DataSourceReference.class, com.google.shopping.merchant.datasources.v1beta.DataSourceReference.Builder.class); } // Construct using // com.google.shopping.merchant.datasources.v1beta.DataSourceReference.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; dataSourceIdCase_ = 0; dataSourceId_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.datasources.v1beta.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1beta_DataSourceReference_descriptor; } @java.lang.Override public com.google.shopping.merchant.datasources.v1beta.DataSourceReference getDefaultInstanceForType() { return com.google.shopping.merchant.datasources.v1beta.DataSourceReference .getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.datasources.v1beta.DataSourceReference build() { com.google.shopping.merchant.datasources.v1beta.DataSourceReference result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.datasources.v1beta.DataSourceReference buildPartial() { com.google.shopping.merchant.datasources.v1beta.DataSourceReference result = new com.google.shopping.merchant.datasources.v1beta.DataSourceReference(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0( com.google.shopping.merchant.datasources.v1beta.DataSourceReference result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs( com.google.shopping.merchant.datasources.v1beta.DataSourceReference result) { result.dataSourceIdCase_ = dataSourceIdCase_; result.dataSourceId_ = this.dataSourceId_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.shopping.merchant.datasources.v1beta.DataSourceReference) { return mergeFrom( (com.google.shopping.merchant.datasources.v1beta.DataSourceReference) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.shopping.merchant.datasources.v1beta.DataSourceReference other) { if (other == com.google.shopping.merchant.datasources.v1beta.DataSourceReference .getDefaultInstance()) return this; switch (other.getDataSourceIdCase()) { case SELF: { setSelf(other.getSelf()); break; } case PRIMARY_DATA_SOURCE_NAME: { dataSourceIdCase_ = 3; dataSourceId_ = other.dataSourceId_; onChanged(); break; } case SUPPLEMENTAL_DATA_SOURCE_NAME: { dataSourceIdCase_ = 2; dataSourceId_ = other.dataSourceId_; onChanged(); break; } case DATASOURCEID_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { dataSourceId_ = input.readBool(); dataSourceIdCase_ = 1; break; } // case 8 case 18: { java.lang.String s = input.readStringRequireUtf8(); dataSourceIdCase_ = 2; dataSourceId_ = s; break; } // case 18 case 26: { java.lang.String s = input.readStringRequireUtf8(); dataSourceIdCase_ = 3; dataSourceId_ = s; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int dataSourceIdCase_ = 0; private java.lang.Object dataSourceId_; public DataSourceIdCase getDataSourceIdCase() { return DataSourceIdCase.forNumber(dataSourceIdCase_); } public Builder clearDataSourceId() { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); return this; } private int bitField0_; /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return Whether the self field is set. */ public boolean hasSelf() { return dataSourceIdCase_ == 1; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return The self. */ public boolean getSelf() { if (dataSourceIdCase_ == 1) { return (java.lang.Boolean) dataSourceId_; } return false; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @param value The self to set. * @return This builder for chaining. */ public Builder setSelf(boolean value) { dataSourceIdCase_ = 1; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return This builder for chaining. */ public Builder clearSelf() { if (dataSourceIdCase_ == 1) { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); } return this; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the primaryDataSourceName field is set. */ @java.lang.Override public boolean hasPrimaryDataSourceName() { return dataSourceIdCase_ == 3; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The primaryDataSourceName. */ @java.lang.Override public java.lang.String getPrimaryDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 3) { dataSourceId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for primaryDataSourceName. */ @java.lang.Override public com.google.protobuf.ByteString getPrimaryDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 3) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The primaryDataSourceName to set. * @return This builder for chaining. */ public Builder setPrimaryDataSourceName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } dataSourceIdCase_ = 3; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPrimaryDataSourceName() { if (dataSourceIdCase_ == 3) { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); } return this; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for primaryDataSourceName to set. * @return This builder for chaining. */ public Builder setPrimaryDataSourceNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); dataSourceIdCase_ = 3; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the supplementalDataSourceName field is set. */ @java.lang.Override public boolean hasSupplementalDataSourceName() { return dataSourceIdCase_ == 2; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The supplementalDataSourceName. */ @java.lang.Override public java.lang.String getSupplementalDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 2) { dataSourceId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The bytes for supplementalDataSourceName. */ @java.lang.Override public com.google.protobuf.ByteString getSupplementalDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 2) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The supplementalDataSourceName to set. * @return This builder for chaining. */ public Builder setSupplementalDataSourceName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } dataSourceIdCase_ = 2; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearSupplementalDataSourceName() { if (dataSourceIdCase_ == 2) { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); } return this; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The bytes for supplementalDataSourceName to set. * @return This builder for chaining. */ public Builder setSupplementalDataSourceNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); dataSourceIdCase_ = 2; dataSourceId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.merchant.datasources.v1beta.DataSourceReference) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.datasources.v1beta.DataSourceReference) private static final com.google.shopping.merchant.datasources.v1beta.DataSourceReference DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.datasources.v1beta.DataSourceReference(); } public static com.google.shopping.merchant.datasources.v1beta.DataSourceReference getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DataSourceReference> PARSER = new com.google.protobuf.AbstractParser<DataSourceReference>() { @java.lang.Override public DataSourceReference parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<DataSourceReference> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DataSourceReference> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.datasources.v1beta.DataSourceReference getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,886
java-vertexai/proto-google-cloud-vertexai-v1/src/main/java/com/google/cloud/vertexai/api/FunctionCallingConfig.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vertexai/v1/tool.proto // Protobuf Java Version: 3.25.3 package com.google.cloud.vertexai.api; /** * * * <pre> * Function calling config. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.FunctionCallingConfig} */ public final class FunctionCallingConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vertexai.v1.FunctionCallingConfig) FunctionCallingConfigOrBuilder { private static final long serialVersionUID = 0L; // Use FunctionCallingConfig.newBuilder() to construct. private FunctionCallingConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FunctionCallingConfig() { mode_ = 0; allowedFunctionNames_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FunctionCallingConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.ToolProto .internal_static_google_cloud_vertexai_v1_FunctionCallingConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.ToolProto .internal_static_google_cloud_vertexai_v1_FunctionCallingConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.FunctionCallingConfig.class, com.google.cloud.vertexai.api.FunctionCallingConfig.Builder.class); } /** * * * <pre> * Function calling mode. * </pre> * * Protobuf enum {@code google.cloud.vertexai.v1.FunctionCallingConfig.Mode} */ public enum Mode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unspecified function calling mode. This value should not be used. * </pre> * * <code>MODE_UNSPECIFIED = 0;</code> */ MODE_UNSPECIFIED(0), /** * * * <pre> * Default model behavior, model decides to predict either function calls * or natural language response. * </pre> * * <code>AUTO = 1;</code> */ AUTO(1), /** * * * <pre> * Model is constrained to always predicting function calls only. * If "allowed_function_names" are set, the predicted function calls will be * limited to any one of "allowed_function_names", else the predicted * function calls will be any one of the provided "function_declarations". * </pre> * * <code>ANY = 2;</code> */ ANY(2), /** * * * <pre> * Model will not predict any function calls. Model behavior is same as when * not passing any function declarations. * </pre> * * <code>NONE = 3;</code> */ NONE(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Unspecified function calling mode. This value should not be used. * </pre> * * <code>MODE_UNSPECIFIED = 0;</code> */ public static final int MODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Default model behavior, model decides to predict either function calls * or natural language response. * </pre> * * <code>AUTO = 1;</code> */ public static final int AUTO_VALUE = 1; /** * * * <pre> * Model is constrained to always predicting function calls only. * If "allowed_function_names" are set, the predicted function calls will be * limited to any one of "allowed_function_names", else the predicted * function calls will be any one of the provided "function_declarations". * </pre> * * <code>ANY = 2;</code> */ public static final int ANY_VALUE = 2; /** * * * <pre> * Model will not predict any function calls. Model behavior is same as when * not passing any function declarations. * </pre> * * <code>NONE = 3;</code> */ public static final int NONE_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 Mode 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 Mode forNumber(int value) { switch (value) { case 0: return MODE_UNSPECIFIED; case 1: return AUTO; case 2: return ANY; case 3: return NONE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Mode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Mode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Mode>() { public Mode findValueByNumber(int number) { return Mode.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.vertexai.api.FunctionCallingConfig.getDescriptor() .getEnumTypes() .get(0); } private static final Mode[] VALUES = values(); public static Mode 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 Mode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.vertexai.v1.FunctionCallingConfig.Mode) } public static final int MODE_FIELD_NUMBER = 1; private int mode_ = 0; /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for mode. */ @java.lang.Override public int getModeValue() { return mode_; } /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The mode. */ @java.lang.Override public com.google.cloud.vertexai.api.FunctionCallingConfig.Mode getMode() { com.google.cloud.vertexai.api.FunctionCallingConfig.Mode result = com.google.cloud.vertexai.api.FunctionCallingConfig.Mode.forNumber(mode_); return result == null ? com.google.cloud.vertexai.api.FunctionCallingConfig.Mode.UNRECOGNIZED : result; } public static final int ALLOWED_FUNCTION_NAMES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList allowedFunctionNames_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return A list containing the allowedFunctionNames. */ public com.google.protobuf.ProtocolStringList getAllowedFunctionNamesList() { return allowedFunctionNames_; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The count of allowedFunctionNames. */ public int getAllowedFunctionNamesCount() { return allowedFunctionNames_.size(); } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the element to return. * @return The allowedFunctionNames at the given index. */ public java.lang.String getAllowedFunctionNames(int index) { return allowedFunctionNames_.get(index); } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the value to return. * @return The bytes of the allowedFunctionNames at the given index. */ public com.google.protobuf.ByteString getAllowedFunctionNamesBytes(int index) { return allowedFunctionNames_.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 (mode_ != com.google.cloud.vertexai.api.FunctionCallingConfig.Mode.MODE_UNSPECIFIED.getNumber()) { output.writeEnum(1, mode_); } for (int i = 0; i < allowedFunctionNames_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString( output, 2, allowedFunctionNames_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (mode_ != com.google.cloud.vertexai.api.FunctionCallingConfig.Mode.MODE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, mode_); } { int dataSize = 0; for (int i = 0; i < allowedFunctionNames_.size(); i++) { dataSize += computeStringSizeNoTag(allowedFunctionNames_.getRaw(i)); } size += dataSize; size += 1 * getAllowedFunctionNamesList().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.vertexai.api.FunctionCallingConfig)) { return super.equals(obj); } com.google.cloud.vertexai.api.FunctionCallingConfig other = (com.google.cloud.vertexai.api.FunctionCallingConfig) obj; if (mode_ != other.mode_) return false; if (!getAllowedFunctionNamesList().equals(other.getAllowedFunctionNamesList())) 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) + MODE_FIELD_NUMBER; hash = (53 * hash) + mode_; if (getAllowedFunctionNamesCount() > 0) { hash = (37 * hash) + ALLOWED_FUNCTION_NAMES_FIELD_NUMBER; hash = (53 * hash) + getAllowedFunctionNamesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.FunctionCallingConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.vertexai.api.FunctionCallingConfig 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> * Function calling config. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.FunctionCallingConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vertexai.v1.FunctionCallingConfig) com.google.cloud.vertexai.api.FunctionCallingConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.ToolProto .internal_static_google_cloud_vertexai_v1_FunctionCallingConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.ToolProto .internal_static_google_cloud_vertexai_v1_FunctionCallingConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.FunctionCallingConfig.class, com.google.cloud.vertexai.api.FunctionCallingConfig.Builder.class); } // Construct using com.google.cloud.vertexai.api.FunctionCallingConfig.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; mode_ = 0; allowedFunctionNames_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vertexai.api.ToolProto .internal_static_google_cloud_vertexai_v1_FunctionCallingConfig_descriptor; } @java.lang.Override public com.google.cloud.vertexai.api.FunctionCallingConfig getDefaultInstanceForType() { return com.google.cloud.vertexai.api.FunctionCallingConfig.getDefaultInstance(); } @java.lang.Override public com.google.cloud.vertexai.api.FunctionCallingConfig build() { com.google.cloud.vertexai.api.FunctionCallingConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vertexai.api.FunctionCallingConfig buildPartial() { com.google.cloud.vertexai.api.FunctionCallingConfig result = new com.google.cloud.vertexai.api.FunctionCallingConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.vertexai.api.FunctionCallingConfig result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.mode_ = mode_; } if (((from_bitField0_ & 0x00000002) != 0)) { allowedFunctionNames_.makeImmutable(); result.allowedFunctionNames_ = allowedFunctionNames_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.vertexai.api.FunctionCallingConfig) { return mergeFrom((com.google.cloud.vertexai.api.FunctionCallingConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.vertexai.api.FunctionCallingConfig other) { if (other == com.google.cloud.vertexai.api.FunctionCallingConfig.getDefaultInstance()) return this; if (other.mode_ != 0) { setModeValue(other.getModeValue()); } if (!other.allowedFunctionNames_.isEmpty()) { if (allowedFunctionNames_.isEmpty()) { allowedFunctionNames_ = other.allowedFunctionNames_; bitField0_ |= 0x00000002; } else { ensureAllowedFunctionNamesIsMutable(); allowedFunctionNames_.addAll(other.allowedFunctionNames_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { mode_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensureAllowedFunctionNamesIsMutable(); allowedFunctionNames_.add(s); break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int mode_ = 0; /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for mode. */ @java.lang.Override public int getModeValue() { return mode_; } /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The enum numeric value on the wire for mode to set. * @return This builder for chaining. */ public Builder setModeValue(int value) { mode_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The mode. */ @java.lang.Override public com.google.cloud.vertexai.api.FunctionCallingConfig.Mode getMode() { com.google.cloud.vertexai.api.FunctionCallingConfig.Mode result = com.google.cloud.vertexai.api.FunctionCallingConfig.Mode.forNumber(mode_); return result == null ? com.google.cloud.vertexai.api.FunctionCallingConfig.Mode.UNRECOGNIZED : result; } /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The mode to set. * @return This builder for chaining. */ public Builder setMode(com.google.cloud.vertexai.api.FunctionCallingConfig.Mode value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; mode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Optional. Function calling mode. * </pre> * * <code> * .google.cloud.vertexai.v1.FunctionCallingConfig.Mode mode = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearMode() { bitField0_ = (bitField0_ & ~0x00000001); mode_ = 0; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList allowedFunctionNames_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureAllowedFunctionNamesIsMutable() { if (!allowedFunctionNames_.isModifiable()) { allowedFunctionNames_ = new com.google.protobuf.LazyStringArrayList(allowedFunctionNames_); } bitField0_ |= 0x00000002; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return A list containing the allowedFunctionNames. */ public com.google.protobuf.ProtocolStringList getAllowedFunctionNamesList() { allowedFunctionNames_.makeImmutable(); return allowedFunctionNames_; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The count of allowedFunctionNames. */ public int getAllowedFunctionNamesCount() { return allowedFunctionNames_.size(); } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the element to return. * @return The allowedFunctionNames at the given index. */ public java.lang.String getAllowedFunctionNames(int index) { return allowedFunctionNames_.get(index); } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the value to return. * @return The bytes of the allowedFunctionNames at the given index. */ public com.google.protobuf.ByteString getAllowedFunctionNamesBytes(int index) { return allowedFunctionNames_.getByteString(index); } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index to set the value at. * @param value The allowedFunctionNames to set. * @return This builder for chaining. */ public Builder setAllowedFunctionNames(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureAllowedFunctionNamesIsMutable(); allowedFunctionNames_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The allowedFunctionNames to add. * @return This builder for chaining. */ public Builder addAllowedFunctionNames(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureAllowedFunctionNamesIsMutable(); allowedFunctionNames_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param values The allowedFunctionNames to add. * @return This builder for chaining. */ public Builder addAllAllowedFunctionNames(java.lang.Iterable<java.lang.String> values) { ensureAllowedFunctionNamesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, allowedFunctionNames_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearAllowedFunctionNames() { allowedFunctionNames_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * Optional. Function names to call. Only set when the Mode is ANY. Function * names should match [FunctionDeclaration.name]. With mode set to ANY, model * will predict a function call from the set of function names provided. * </pre> * * <code>repeated string allowed_function_names = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The bytes of the allowedFunctionNames to add. * @return This builder for chaining. */ public Builder addAllowedFunctionNamesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureAllowedFunctionNamesIsMutable(); allowedFunctionNames_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vertexai.v1.FunctionCallingConfig) } // @@protoc_insertion_point(class_scope:google.cloud.vertexai.v1.FunctionCallingConfig) private static final com.google.cloud.vertexai.api.FunctionCallingConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vertexai.api.FunctionCallingConfig(); } public static com.google.cloud.vertexai.api.FunctionCallingConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FunctionCallingConfig> PARSER = new com.google.protobuf.AbstractParser<FunctionCallingConfig>() { @java.lang.Override public FunctionCallingConfig 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<FunctionCallingConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FunctionCallingConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vertexai.api.FunctionCallingConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/gobblin
37,243
gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.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.gobblin.publisher; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Closer; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import org.apache.gobblin.config.ConfigBuilder; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.SourceState; import org.apache.gobblin.configuration.State; import org.apache.gobblin.configuration.WorkUnitState; import org.apache.gobblin.dataset.DatasetConstants; import org.apache.gobblin.dataset.DatasetDescriptor; import org.apache.gobblin.dataset.Descriptor; import org.apache.gobblin.dataset.PartitionDescriptor; import org.apache.gobblin.metadata.MetadataMerger; import org.apache.gobblin.metadata.types.StaticStringMetadataMerger; import org.apache.gobblin.metrics.event.lineage.LineageInfo; import org.apache.gobblin.util.ForkOperatorUtils; import org.apache.gobblin.util.HadoopUtils; import org.apache.gobblin.util.ParallelRunner; import org.apache.gobblin.util.WriterUtils; import org.apache.gobblin.util.reflection.GobblinConstructorUtils; import org.apache.gobblin.writer.FsDataWriter; import org.apache.gobblin.writer.FsWriterMetrics; import org.apache.gobblin.writer.PartitionIdentifier; import org.apache.gobblin.writer.PartitionedDataWriter; import static org.apache.gobblin.util.retry.RetryerFactory.*; /** * A basic implementation of {@link SingleTaskDataPublisher} that publishes the data from the writer output directory * to the final output directory. * * <p> * The final output directory is specified by {@link ConfigurationKeys#DATA_PUBLISHER_FINAL_DIR}. The output of each * writer is written to this directory. Each individual writer can also specify a path in the config key * {@link ConfigurationKeys#WRITER_FILE_PATH}. Then the final output data for a writer will be * {@link ConfigurationKeys#DATA_PUBLISHER_FINAL_DIR}/{@link ConfigurationKeys#WRITER_FILE_PATH}. If the * {@link ConfigurationKeys#WRITER_FILE_PATH} is not specified, a default one is assigned. The default path is * constructed in the {@link org.apache.gobblin.source.workunit.Extract#getOutputFilePath()} method. * </p> * * <p> * This publisher records all dirs it publishes to in property {@link ConfigurationKeys#PUBLISHER_DIRS}. Each time it * publishes a {@link Path}, if the path is a directory, it records this path. If the path is a file, it records the * parent directory of the path. To change this behavior one may override * {@link #recordPublisherOutputDirs(Path, Path, int)}. * </p> */ public class BaseDataPublisher extends SingleTaskDataPublisher { private static final Logger LOG = LoggerFactory.getLogger(BaseDataPublisher.class); protected final int numBranches; protected final List<FileSystem> writerFileSystemByBranches; protected final List<FileSystem> publisherFileSystemByBranches; protected final List<FileSystem> metaDataWriterFileSystemByBranches; protected final List<Optional<String>> publisherFinalDirOwnerGroupsByBranches; protected final List<Optional<String>> publisherOutputDirOwnerGroupByBranches; protected final List<FsPermission> permissions; protected final Closer closer; protected final Closer parallelRunnerCloser; protected final int parallelRunnerThreads; protected final Map<String, ParallelRunner> parallelRunners = Maps.newHashMap(); protected final Set<Path> publisherOutputDirs = Sets.newHashSet(); protected final Optional<LineageInfo> lineageInfo; /* Each partition in each branch may have separate metadata. The metadata mergers are responsible * for aggregating this information from all workunits so it can be published. */ protected final Map<PartitionIdentifier, MetadataMerger<String>> metadataMergers; protected final boolean shouldRetry; static final String DATA_PUBLISHER_RETRY_PREFIX = ConfigurationKeys.DATA_PUBLISHER_PREFIX + ".retry."; static final String PUBLISH_RETRY_ENABLED = DATA_PUBLISHER_RETRY_PREFIX + "enabled"; static final Config PUBLISH_RETRY_DEFAULTS; protected final Config retryerConfig; static { Map<String, Object> configMap = ImmutableMap.<String, Object>builder() .put(RETRY_TIME_OUT_MS, TimeUnit.MINUTES.toMillis(2L)) //Overall retry for 2 minutes .put(RETRY_INTERVAL_MS, TimeUnit.SECONDS.toMillis(5L)) //Try to retry 5 seconds .put(RETRY_MULTIPLIER, 2L) // Multiply by 2 every attempt .put(RETRY_TYPE, RetryType.EXPONENTIAL.name()) .build(); PUBLISH_RETRY_DEFAULTS = ConfigFactory.parseMap(configMap); }; public BaseDataPublisher(State state) throws IOException { super(state); this.closer = Closer.create(); Configuration conf = new Configuration(); // Add all job configuration properties so they are picked up by Hadoop for (String key : this.getState().getPropertyNames()) { conf.set(key, this.getState().getProp(key)); } // Extract LineageInfo from state if (state instanceof SourceState) { lineageInfo = LineageInfo.getLineageInfo(((SourceState) state).getBroker()); } else if (state instanceof WorkUnitState) { lineageInfo = LineageInfo.getLineageInfo(((WorkUnitState) state).getTaskBrokerNullable()); } else { lineageInfo = Optional.absent(); } this.numBranches = this.getState().getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); this.shouldRetry = this.getState().getPropAsBoolean(PUBLISH_RETRY_ENABLED, false); this.writerFileSystemByBranches = Lists.newArrayListWithCapacity(this.numBranches); this.publisherFileSystemByBranches = Lists.newArrayListWithCapacity(this.numBranches); this.metaDataWriterFileSystemByBranches = Lists.newArrayListWithCapacity(this.numBranches); this.publisherFinalDirOwnerGroupsByBranches = Lists.newArrayListWithCapacity(this.numBranches); this.publisherOutputDirOwnerGroupByBranches = Lists.newArrayListWithCapacity(this.numBranches); this.permissions = Lists.newArrayListWithCapacity(this.numBranches); this.metadataMergers = new HashMap<>(); // Get a FileSystem instance for each branch for (int i = 0; i < this.numBranches; i++) { URI writerUri = URI.create(this.getState().getProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, this.numBranches, i), ConfigurationKeys.LOCAL_FS_URI)); this.writerFileSystemByBranches.add(FileSystem.get(writerUri, conf)); URI publisherUri = URI.create(this.getState().getProp(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_FILE_SYSTEM_URI, this.numBranches, i), writerUri.toString())); this.publisherFileSystemByBranches.add(FileSystem.get(publisherUri, conf)); this.metaDataWriterFileSystemByBranches.add(FileSystem.get(publisherUri, conf)); // The group(s) will be applied to the final publisher output directory(ies) // (Deprecated) See ConfigurationKeys.DATA_PUBLISHER_FINAL_DIR_GROUP this.publisherFinalDirOwnerGroupsByBranches.add(Optional.fromNullable(this.getState().getProp(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_FINAL_DIR_GROUP, this.numBranches, i)))); this.publisherOutputDirOwnerGroupByBranches.add(Optional.fromNullable(this.getState().getProp(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_OUTPUT_DIR_GROUP, this.numBranches, i)))); // The permission(s) will be applied to all directories created by the publisher, // which do NOT include directories created by the writer and moved by the publisher. // The permissions of those directories are controlled by writer.file.permissions and writer.dir.permissions. this.permissions.add(new FsPermission(state.getPropAsShortWithRadix( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_PERMISSIONS, this.numBranches, i), FsPermission.getDefault().toShort(), ConfigurationKeys.PERMISSION_PARSING_RADIX))); } if (this.shouldRetry) { this.retryerConfig = ConfigBuilder.create() .loadProps(this.getState().getProperties(), DATA_PUBLISHER_RETRY_PREFIX) .build() .withFallback(PUBLISH_RETRY_DEFAULTS); LOG.info("Retry enabled for publish with config : " + retryerConfig.root().render(ConfigRenderOptions.concise())); } else { LOG.info("Retry disabled for publish."); this.retryerConfig = WriterUtils.NO_RETRY_CONFIG; } this.parallelRunnerThreads = state.getPropAsInt(ParallelRunner.PARALLEL_RUNNER_THREADS_KEY, ParallelRunner.DEFAULT_PARALLEL_RUNNER_THREADS); this.parallelRunnerCloser = Closer.create(); } private MetadataMerger<String> buildMetadataMergerForBranch(String metadataFromConfig, int branchId, Path existingMetadataPath) { // Legacy behavior -- if we shouldn't publish writer state, instantiate a static metadata merger // that just returns the metadata from config (if any) if (!shouldPublishWriterMetadataForBranch(branchId)) { return new StaticStringMetadataMerger(metadataFromConfig); } String keyName = ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISH_WRITER_METADATA_MERGER_NAME_KEY, this.numBranches, branchId); String className = this.getState().getProp(keyName, ConfigurationKeys.DATA_PUBLISH_WRITER_METADATA_MERGER_NAME_DEFAULT); try { Class<?> mdClass = Class.forName(className); // If the merger understands properties, use that constructor; otherwise use the default // parameter-less ctor @SuppressWarnings("unchecked") Object merger = GobblinConstructorUtils .invokeFirstConstructor(mdClass, Collections.<Object>singletonList(this.getState().getProperties()), Collections.<Object>emptyList()); try { @SuppressWarnings("unchecked") MetadataMerger<String> casted = (MetadataMerger<String>) merger; // Merge existing metadata from the partition if it exists.. String existingMetadata = loadExistingMetadata(existingMetadataPath, branchId); if (existingMetadata != null) { casted.update(existingMetadata); } // Then metadata from the config... if (metadataFromConfig != null) { casted.update(metadataFromConfig); } return casted; } catch (ClassCastException e) { throw new IllegalArgumentException(className + " does not implement the MetadataMerger interface", e); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Specified metadata merger class " + className + " not found!", e); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Error building merger class " + className, e); } } /** * Read in existing metadata as a UTF8 string. */ private String loadExistingMetadata(Path metadataFilename, int branchId) { try { FileSystem fsForBranch = writerFileSystemByBranches.get(branchId); if (!fsForBranch.exists(metadataFilename)) { return null; } FSDataInputStream existingMetadata = writerFileSystemByBranches.get(branchId).open(metadataFilename); return IOUtils.toString(existingMetadata, StandardCharsets.UTF_8); } catch (IOException e) { LOG.warn("IOException {} while trying to read existing metadata {} - treating as null", e.getMessage(), metadataFilename.toString()); return null; } } @Override public void initialize() throws IOException { // Nothing needs to be done since the constructor already initializes the publisher. } @Override public void close() throws IOException { try { for (Path path : this.publisherOutputDirs) { this.state.appendToSetProp(ConfigurationKeys.PUBLISHER_DIRS, path.toString()); } this.state.setProp(ConfigurationKeys.PUBLISHER_LATEST_FILE_ARRIVAL_TIMESTAMP, System.currentTimeMillis()); } finally { this.closer.close(); } } private void addLineageInfo(WorkUnitState state, int branchId) { if (!this.lineageInfo.isPresent()) { LOG.info("Will not add lineage info"); return; } // Final dataset descriptor DatasetDescriptor datasetDescriptor = createDestinationDescriptor(state, branchId); List<PartitionDescriptor> partitions = PartitionedDataWriter.getPartitionInfoAndClean(state, branchId); List<Descriptor> descriptors = new ArrayList<>(); if (partitions.size() == 0) { // Report as dataset level lineage descriptors.add(datasetDescriptor); } else { // Report as partition level lineage for (PartitionDescriptor partition : partitions) { descriptors.add(partition.copyWithNewDataset(datasetDescriptor)); } } this.lineageInfo.get().putDestination(descriptors, branchId, state); } /** * Create destination dataset descriptor */ protected DatasetDescriptor createDestinationDescriptor(WorkUnitState state, int branchId) { Path publisherOutputDir = getPublisherOutputDir(state, branchId); FileSystem fs = this.publisherFileSystemByBranches.get(branchId); DatasetDescriptor destination = new DatasetDescriptor(fs.getScheme(), fs.getUri(), publisherOutputDir.toString()); destination.addMetadata(DatasetConstants.FS_URI, fs.getUri().toString()); destination.addMetadata(DatasetConstants.BRANCH, String.valueOf(branchId)); return destination; } @Override public void publishData(WorkUnitState state) throws IOException { for (int branchId = 0; branchId < this.numBranches; branchId++) { publishSingleTaskData(state, branchId); } this.parallelRunnerCloser.close(); } /** * This method publishes output data for a single task based on the given {@link WorkUnitState}. * Output data from other tasks won't be published even if they are in the same folder. */ private void publishSingleTaskData(WorkUnitState state, int branchId) throws IOException { publishData(state, branchId, true, new HashSet<Path>()); addLineageInfo(state, branchId); } @Override public void publishData(Collection<? extends WorkUnitState> states) throws IOException { // We need a Set to collect unique writer output paths as multiple tasks may belong to the same extract. Tasks that // belong to the same Extract will by default have the same output directory Set<Path> writerOutputPathsMoved = Sets.newHashSet(); for (WorkUnitState workUnitState : states) { for (int branchId = 0; branchId < this.numBranches; branchId++) { publishMultiTaskData(workUnitState, branchId, writerOutputPathsMoved); } } this.parallelRunnerCloser.close(); } /** * This method publishes task output data for the given {@link WorkUnitState}, but if there are output data of * other tasks in the same folder, it may also publish those data. */ protected void publishMultiTaskData(WorkUnitState state, int branchId, Set<Path> writerOutputPathsMoved) throws IOException { publishData(state, branchId, false, writerOutputPathsMoved); addLineageInfo(state, branchId); } protected void publishData(WorkUnitState state, int branchId, boolean publishSingleTaskData, Set<Path> writerOutputPathsMoved) throws IOException { // Get a ParallelRunner instance for moving files in parallel ParallelRunner parallelRunner = this.getParallelRunner(this.writerFileSystemByBranches.get(branchId)); // The directory where the workUnitState wrote its output data. Path writerOutputDir = WriterUtils.getWriterOutputDir(state, this.numBranches, branchId); if (!this.writerFileSystemByBranches.get(branchId).exists(writerOutputDir)) { LOG.warn(String.format("Branch %d of WorkUnit %s produced no data", branchId, state.getId())); return; } // The directory where the final output directory for this job will be placed. // It is a combination of DATA_PUBLISHER_FINAL_DIR and WRITER_FILE_PATH. Path publisherOutputDir = getPublisherOutputDir(state, branchId); if (publishSingleTaskData) { // Create final output directory WriterUtils.mkdirsWithRecursivePermissionWithRetry(this.publisherFileSystemByBranches.get(branchId), publisherOutputDir, this.permissions.get(branchId), retryerConfig); if(this.publisherOutputDirOwnerGroupByBranches.get(branchId).isPresent()) { LOG.info(String.format("Setting path %s group to %s", publisherOutputDir.toString(), this.publisherOutputDirOwnerGroupByBranches.get(branchId).get())); HadoopUtils.setGroup(this.publisherFileSystemByBranches.get(branchId), publisherOutputDir, this.publisherOutputDirOwnerGroupByBranches.get(branchId).get()); } addSingleTaskWriterOutputToExistingDir(writerOutputDir, publisherOutputDir, state, branchId, parallelRunner); } else { if (writerOutputPathsMoved.contains(writerOutputDir)) { // This writer output path has already been moved for another task of the same extract // If publishSingleTaskData=true, writerOutputPathMoved is ignored. return; } if (this.publisherFileSystemByBranches.get(branchId).exists(publisherOutputDir)) { // The final output directory already exists, check if the job is configured to replace it. // If publishSingleTaskData=true, final output directory is never replaced. boolean replaceFinalOutputDir = this.getState().getPropAsBoolean(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_REPLACE_FINAL_DIR, this.numBranches, branchId)); // If the final output directory is not configured to be replaced, put new data to the existing directory. if (!replaceFinalOutputDir) { addWriterOutputToExistingDir(writerOutputDir, publisherOutputDir, state, branchId, parallelRunner); writerOutputPathsMoved.add(writerOutputDir); return; } // Delete the final output directory if it is configured to be replaced LOG.info("Deleting publisher output dir " + publisherOutputDir); this.publisherFileSystemByBranches.get(branchId).delete(publisherOutputDir, true); } else { // Create the parent directory of the final output directory if it does not exist WriterUtils.mkdirsWithRecursivePermissionWithRetry(this.publisherFileSystemByBranches.get(branchId), publisherOutputDir.getParent(), this.permissions.get(branchId), retryerConfig); if(this.publisherOutputDirOwnerGroupByBranches.get(branchId).isPresent()) { LOG.info(String.format("Setting path %s group to %s", publisherOutputDir.toString(), this.publisherOutputDirOwnerGroupByBranches.get(branchId).get())); HadoopUtils.setGroup(this.publisherFileSystemByBranches.get(branchId), publisherOutputDir, this.publisherOutputDirOwnerGroupByBranches.get(branchId).get()); } } movePath(parallelRunner, state, writerOutputDir, publisherOutputDir, branchId); writerOutputPathsMoved.add(writerOutputDir); } } /** * Get the output directory path this {@link BaseDataPublisher} will write to. * * <p> * This is the default implementation. Subclasses of {@link BaseDataPublisher} may override this * to write to a custom directory or write using a custom directory structure or naming pattern. * </p> * * @param workUnitState a {@link WorkUnitState} object * @param branchId the fork branch ID * @return the output directory path this {@link BaseDataPublisher} will write to */ protected Path getPublisherOutputDir(WorkUnitState workUnitState, int branchId) { return WriterUtils.getDataPublisherFinalDir(workUnitState, this.numBranches, branchId); } protected void addSingleTaskWriterOutputToExistingDir(Path writerOutputDir, Path publisherOutputDir, WorkUnitState workUnitState, int branchId, ParallelRunner parallelRunner) throws IOException { String outputFilePropName = ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.WRITER_FINAL_OUTPUT_FILE_PATHS, this.numBranches, branchId); if (!workUnitState.contains(outputFilePropName)) { LOG.warn("Missing property " + outputFilePropName + ". This task may have pulled no data."); return; } Iterable<String> taskOutputFiles = workUnitState.getPropAsSet(outputFilePropName); for (String taskOutputFile : taskOutputFiles) { Path taskOutputPath = new Path(taskOutputFile); if (!this.writerFileSystemByBranches.get(branchId).exists(taskOutputPath)) { LOG.warn("Task output file " + taskOutputFile + " doesn't exist."); continue; } String pathSuffix = taskOutputFile .substring(taskOutputFile.indexOf(writerOutputDir.toString()) + writerOutputDir.toString().length() + 1); Path publisherOutputPath = new Path(publisherOutputDir, pathSuffix); WriterUtils.mkdirsWithRecursivePermissionWithRetry(this.publisherFileSystemByBranches.get(branchId), publisherOutputPath.getParent(), this.permissions.get(branchId), retryerConfig); movePath(parallelRunner, workUnitState, taskOutputPath, publisherOutputPath, branchId); } } protected void addWriterOutputToExistingDir(Path writerOutputDir, Path publisherOutputDir, WorkUnitState workUnitState, int branchId, ParallelRunner parallelRunner) throws IOException { boolean preserveFileName = workUnitState.getPropAsBoolean(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.SOURCE_FILEBASED_PRESERVE_FILE_NAME, this.numBranches, branchId), false); // Go through each file in writerOutputDir and move it into publisherOutputDir for (FileStatus status : this.writerFileSystemByBranches.get(branchId).listStatus(writerOutputDir)) { // Preserve the file name if configured, use specified name otherwise Path finalOutputPath = preserveFileName ? new Path(publisherOutputDir, workUnitState.getProp(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_FINAL_NAME, this.numBranches, branchId))) : new Path(publisherOutputDir, status.getPath().getName()); movePath(parallelRunner, workUnitState, status.getPath(), finalOutputPath, branchId); } } protected void movePath(ParallelRunner parallelRunner, State state, Path src, Path dst, int branchId) throws IOException { LOG.info(String.format("Moving %s to %s", src, dst)); boolean overwrite = state.getPropAsBoolean(ConfigurationKeys.DATA_PUBLISHER_OVERWRITE_ENABLED, false); this.publisherOutputDirs.addAll(recordPublisherOutputDirs(src, dst, branchId)); parallelRunner.movePath(src, this.publisherFileSystemByBranches.get(branchId), dst, overwrite, this.publisherFinalDirOwnerGroupsByBranches.get(branchId)); } protected Collection<Path> recordPublisherOutputDirs(Path src, Path dst, int branchId) throws IOException { // Getting file status from src rather than dst, because at this time dst doesn't yet exist. // If src is a dir, add dst to the set of paths. Otherwise, add dst's parent. if (this.writerFileSystemByBranches.get(branchId).getFileStatus(src).isDirectory()) { return ImmutableList.<Path>of(dst); } return ImmutableList.<Path>of(dst.getParent()); } private ParallelRunner getParallelRunner(FileSystem fs) { String uri = fs.getUri().toString(); if (!this.parallelRunners.containsKey(uri)) { this.parallelRunners .put(uri, this.parallelRunnerCloser.register(new ParallelRunner(this.parallelRunnerThreads, fs))); } return this.parallelRunners.get(uri); } /** * Merge all of the metadata output from each work-unit and publish the merged record. * @param states States from all tasks * @throws IOException If there is an error publishing the file */ @Override public void publishMetadata(Collection<? extends WorkUnitState> states) throws IOException { Set<String> partitions = new HashSet<>(); // There should be one merged metadata file per branch; first merge all of the pieces together mergeMetadataAndCollectPartitionNames(states, partitions); partitions.removeIf(Objects::isNull); // Now, pick an arbitrary WorkUnitState to get config information around metadata such as // the desired output filename. We assume that publisher config settings // are the same across all workunits so it doesn't really matter which workUnit we retrieve this information // from. WorkUnitState anyState = states.iterator().next(); for (int branchId = 0; branchId < numBranches; branchId++) { String mdOutputPath = getMetadataOutputPathFromState(anyState, branchId); String userSpecifiedPath = getUserSpecifiedOutputPathFromState(anyState, branchId); if (partitions.isEmpty() || userSpecifiedPath != null) { publishMetadata(getMergedMetadataForPartitionAndBranch(null, branchId), branchId, getMetadataOutputFileForBranch(anyState, branchId)); } else { String metadataFilename = getMetadataFileNameForBranch(anyState, branchId); if (mdOutputPath == null || metadataFilename == null) { LOG.info("Metadata filename not set for branch " + String.valueOf(branchId) + ": not publishing metadata."); continue; } for (String partition : partitions) { publishMetadata(getMergedMetadataForPartitionAndBranch(partition, branchId), branchId, new Path(new Path(mdOutputPath, partition), metadataFilename)); } } } } /* * Metadata that we publish can come from several places: * - It can be passed in job config (DATA_PUBLISHER_METADATA_STR) * - It can be picked up from previous runs of a job (if the output partition already exists) * -- The above two are handled when we construct a new MetadataMerger * * - The source/converters/writers associated with each branch of a job may add their own metadata * (eg: this dataset is encrypted using AES256). This is returned by getIntermediateMetadataFromState() * and fed into the MetadataMerger. * - FsWriterMetrics can be emitted and rolled up into metadata. These metrics are specific to a {partition, branch} * combo as they mention per-output file metrics. This is also fed into metadata mergers. * * Each writer should only be a part of one branch, but it may be responsible for multiple partitions. */ private void mergeMetadataAndCollectPartitionNames(Collection<? extends WorkUnitState> states, Set<String> partitionPaths) { for (WorkUnitState workUnitState : states) { // First extract the partition paths and metrics from the work unit. This is essentially // equivalent to grouping FsWriterMetrics by {partitionKey, branchId} and extracting // all partitionPaths into a set. Map<PartitionIdentifier, Set<FsWriterMetrics>> metricsByPartition = new HashMap<>(); boolean partitionFound = false; for (Map.Entry<Object, Object> property : workUnitState.getProperties().entrySet()) { if (((String) property.getKey()).startsWith(ConfigurationKeys.WRITER_PARTITION_PATH_KEY)) { partitionPaths.add((String) property.getValue()); partitionFound = true; } else if (((String) property.getKey()).startsWith(FsDataWriter.FS_WRITER_METRICS_KEY)) { try { FsWriterMetrics parsedMetrics = FsWriterMetrics.fromJson((String) property.getValue()); partitionPaths.add(parsedMetrics.getPartitionInfo().getPartitionKey()); Set<FsWriterMetrics> metricsForPartition = metricsByPartition.computeIfAbsent(parsedMetrics.getPartitionInfo(), k -> new HashSet<>()); metricsForPartition.add(parsedMetrics); } catch (IOException e) { LOG.warn("Error parsing metrics from property {} - ignoring", (String) property.getValue()); } } } // no specific partitions - add null as a placeholder if (!partitionFound) { partitionPaths.add(null); } final String configBasedMetadata = getMetadataFromWorkUnitState(workUnitState); // Now update all metadata mergers with branch metadata + partition metrics for (int branchId = 0; branchId < numBranches; branchId++) { for (String partition : partitionPaths) { PartitionIdentifier partitionIdentifier = new PartitionIdentifier(partition, branchId); final int branch = branchId; MetadataMerger<String> mdMerger = metadataMergers.computeIfAbsent(partitionIdentifier, k -> buildMetadataMergerForBranch(configBasedMetadata, branch, getMetadataOutputFileForBranch(workUnitState, branch))); if (shouldPublishWriterMetadataForBranch(branchId)) { String md = getIntermediateMetadataFromState(workUnitState, branchId); mdMerger.update(md); Set<FsWriterMetrics> metricsForPartition = metricsByPartition.getOrDefault(partitionIdentifier, Collections.emptySet()); for (FsWriterMetrics metrics : metricsForPartition) { mdMerger.update(metrics); } } } } } } /** * Publish metadata for each branch. We expect the metadata to be of String format and * populated in either the WRITER_MERGED_METADATA_KEY state or the WRITER_METADATA_KEY configuration key. */ @Override public void publishMetadata(WorkUnitState state) throws IOException { publishMetadata(Collections.singleton(state)); } /** * Publish metadata to a set of paths */ private void publishMetadata(String metadataValue, int branchId, Path metadataOutputPath) throws IOException { try { if (metadataOutputPath == null) { LOG.info("Metadata output path not set for branch " + String.valueOf(branchId) + ", not publishing."); return; } if (metadataValue == null) { LOG.info("No metadata collected for branch " + String.valueOf(branchId) + ", not publishing."); return; } FileSystem fs = this.metaDataWriterFileSystemByBranches.get(branchId); if (!fs.exists(metadataOutputPath.getParent())) { WriterUtils.mkdirsWithRecursivePermissionWithRetry(fs, metadataOutputPath, this.permissions.get(branchId), retryerConfig); } //Delete the file if metadata already exists if (fs.exists(metadataOutputPath)) { HadoopUtils.deletePath(fs, metadataOutputPath, false); } LOG.info("Writing metadata for branch " + String.valueOf(branchId) + " to " + metadataOutputPath.toString()); try (FSDataOutputStream outputStream = fs.create(metadataOutputPath)) { outputStream.write(metadataValue.getBytes(StandardCharsets.UTF_8)); } } catch (IOException e) { LOG.error("Metadata file is not generated: " + e, e); } } private String getMetadataFileNameForBranch(WorkUnitState state, int branchId) { // Note: This doesn't follow the pattern elsewhere in Gobblin where we have branch specific config // parameters! Leaving this way for backwards compatibility. String filePrefix = state.getProp(ConfigurationKeys.DATA_PUBLISHER_METADATA_OUTPUT_FILE); return ForkOperatorUtils.getPropertyNameForBranch(filePrefix, this.numBranches, branchId); } private Path getMetadataOutputFileForBranch(WorkUnitState state, int branchId) { String metaDataOutputDirStr = getMetadataOutputPathFromState(state, branchId); String fileName = getMetadataFileNameForBranch(state, branchId); if (metaDataOutputDirStr == null || fileName == null) { return null; } return new Path(metaDataOutputDirStr, fileName); } private String getUserSpecifiedOutputPathFromState(WorkUnitState state, int branchId) { String outputDir = state.getProp(ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISHER_METADATA_OUTPUT_DIR, this.numBranches, branchId)); // An older version of this code did not get a branch specific PUBLISHER_METADATA_OUTPUT_DIR so fallback // for compatibility's sake if (outputDir == null && this.numBranches > 1) { outputDir = state.getProp(ConfigurationKeys.DATA_PUBLISHER_METADATA_OUTPUT_DIR); if (outputDir != null) { LOG.warn("Branches are configured for this job but a per branch metadata output directory was not set;" + " is this intended?"); } } return outputDir; } private String getMetadataOutputPathFromState(WorkUnitState state, int branchId) { String outputDir = getUserSpecifiedOutputPathFromState(state, branchId); // Just write out to the regular output path if a metadata specific path hasn't been provided if (outputDir == null) { String publisherOutputDir = getPublisherOutputDir(state, branchId).toString(); LOG.info("Missing metadata output directory path : " + ConfigurationKeys.DATA_PUBLISHER_METADATA_OUTPUT_DIR + " in the config; assuming outputPath " + publisherOutputDir); return publisherOutputDir; } return outputDir; } /* * Retrieve intermediate metadata (eg the metadata stored by each writer) for a given state and branch id. */ private String getIntermediateMetadataFromState(WorkUnitState state, int branchId) { return state.getProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_METADATA_KEY, this.numBranches, branchId)); } /* * Get the merged metadata given a workunit state and branch id. This method assumes * all intermediate metadata has already been passed to the MetadataMerger. * * If metadata mergers are not configured, instead return the metadata from job config that was * passed in by the user. */ private String getMergedMetadataForPartitionAndBranch(String partitionId, int branchId) { String mergedMd = null; MetadataMerger<String> mergerForBranch = metadataMergers.get(new PartitionIdentifier(partitionId, branchId)); if (mergerForBranch != null) { mergedMd = mergerForBranch.getMergedMetadata(); if (mergedMd == null) { LOG.warn("Metadata merger for branch {} returned null - bug in merger?", branchId); } } return mergedMd; } private boolean shouldPublishWriterMetadataForBranch(int branchId) { String keyName = ForkOperatorUtils .getPropertyNameForBranch(ConfigurationKeys.DATA_PUBLISH_WRITER_METADATA_KEY, this.numBranches, branchId); return this.getState().getPropAsBoolean(keyName, false); } /** * Retrieve metadata from job state config */ private String getMetadataFromWorkUnitState(WorkUnitState workUnitState) { return workUnitState.getProp(ConfigurationKeys.DATA_PUBLISHER_METADATA_STR); } /** * The BaseDataPublisher relies on publishData() to create and clean-up the output directories, so data * has to be published before the metadata can be. */ @Override protected boolean shouldPublishMetadataFirst() { return false; } }
apache/hbase
36,968
hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/TIncrement.java
/** * Autogenerated by Thrift Compiler (0.14.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hbase.thrift2.generated; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) /** * Used to perform Increment operations for a single row. * * You can specify how this Increment should be written to the write-ahead Log (WAL) * by changing the durability. If you don't provide durability, it defaults to * column family's default setting for durability. */ @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.14.1)", date = "2025-08-16") public class TIncrement implements org.apache.thrift.TBase<TIncrement, TIncrement._Fields>, java.io.Serializable, Cloneable, Comparable<TIncrement> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TIncrement"); private static final org.apache.thrift.protocol.TField ROW_FIELD_DESC = new org.apache.thrift.protocol.TField("row", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField COLUMNS_FIELD_DESC = new org.apache.thrift.protocol.TField("columns", org.apache.thrift.protocol.TType.LIST, (short)2); private static final org.apache.thrift.protocol.TField ATTRIBUTES_FIELD_DESC = new org.apache.thrift.protocol.TField("attributes", org.apache.thrift.protocol.TType.MAP, (short)4); private static final org.apache.thrift.protocol.TField DURABILITY_FIELD_DESC = new org.apache.thrift.protocol.TField("durability", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField CELL_VISIBILITY_FIELD_DESC = new org.apache.thrift.protocol.TField("cellVisibility", org.apache.thrift.protocol.TType.STRUCT, (short)6); private static final org.apache.thrift.protocol.TField RETURN_RESULTS_FIELD_DESC = new org.apache.thrift.protocol.TField("returnResults", org.apache.thrift.protocol.TType.BOOL, (short)7); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new TIncrementStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new TIncrementTupleSchemeFactory(); public @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row; // required public @org.apache.thrift.annotation.Nullable java.util.List<TColumnIncrement> columns; // required public @org.apache.thrift.annotation.Nullable java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> attributes; // optional /** * * @see TDurability */ public @org.apache.thrift.annotation.Nullable TDurability durability; // optional public @org.apache.thrift.annotation.Nullable TCellVisibility cellVisibility; // optional public boolean returnResults; // 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 { ROW((short)1, "row"), COLUMNS((short)2, "columns"), ATTRIBUTES((short)4, "attributes"), /** * * @see TDurability */ DURABILITY((short)5, "durability"), CELL_VISIBILITY((short)6, "cellVisibility"), RETURN_RESULTS((short)7, "returnResults"); 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: // ROW return ROW; case 2: // COLUMNS return COLUMNS; case 4: // ATTRIBUTES return ATTRIBUTES; case 5: // DURABILITY return DURABILITY; case 6: // CELL_VISIBILITY return CELL_VISIBILITY; case 7: // RETURN_RESULTS return RETURN_RESULTS; 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 __RETURNRESULTS_ISSET_ID = 0; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.ATTRIBUTES,_Fields.DURABILITY,_Fields.CELL_VISIBILITY,_Fields.RETURN_RESULTS}; 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.ROW, new org.apache.thrift.meta_data.FieldMetaData("row", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.COLUMNS, new org.apache.thrift.meta_data.FieldMetaData("columns", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TColumnIncrement.class)))); tmpMap.put(_Fields.ATTRIBUTES, new org.apache.thrift.meta_data.FieldMetaData("attributes", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true), new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)))); tmpMap.put(_Fields.DURABILITY, new org.apache.thrift.meta_data.FieldMetaData("durability", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, TDurability.class))); tmpMap.put(_Fields.CELL_VISIBILITY, new org.apache.thrift.meta_data.FieldMetaData("cellVisibility", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TCellVisibility.class))); tmpMap.put(_Fields.RETURN_RESULTS, new org.apache.thrift.meta_data.FieldMetaData("returnResults", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TIncrement.class, metaDataMap); } public TIncrement() { } public TIncrement( java.nio.ByteBuffer row, java.util.List<TColumnIncrement> columns) { this(); this.row = org.apache.thrift.TBaseHelper.copyBinary(row); this.columns = columns; } /** * Performs a deep copy on <i>other</i>. */ public TIncrement(TIncrement other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetRow()) { this.row = org.apache.thrift.TBaseHelper.copyBinary(other.row); } if (other.isSetColumns()) { java.util.List<TColumnIncrement> __this__columns = new java.util.ArrayList<TColumnIncrement>(other.columns.size()); for (TColumnIncrement other_element : other.columns) { __this__columns.add(new TColumnIncrement(other_element)); } this.columns = __this__columns; } if (other.isSetAttributes()) { java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> __this__attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(other.attributes); this.attributes = __this__attributes; } if (other.isSetDurability()) { this.durability = other.durability; } if (other.isSetCellVisibility()) { this.cellVisibility = new TCellVisibility(other.cellVisibility); } this.returnResults = other.returnResults; } public TIncrement deepCopy() { return new TIncrement(this); } @Override public void clear() { this.row = null; this.columns = null; this.attributes = null; this.durability = null; this.cellVisibility = null; setReturnResultsIsSet(false); this.returnResults = false; } public byte[] getRow() { setRow(org.apache.thrift.TBaseHelper.rightSize(row)); return row == null ? null : row.array(); } public java.nio.ByteBuffer bufferForRow() { return org.apache.thrift.TBaseHelper.copyBinary(row); } public TIncrement setRow(byte[] row) { this.row = row == null ? (java.nio.ByteBuffer)null : java.nio.ByteBuffer.wrap(row.clone()); return this; } public TIncrement setRow(@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row) { this.row = org.apache.thrift.TBaseHelper.copyBinary(row); return this; } public void unsetRow() { this.row = null; } /** Returns true if field row is set (has been assigned a value) and false otherwise */ public boolean isSetRow() { return this.row != null; } public void setRowIsSet(boolean value) { if (!value) { this.row = null; } } public int getColumnsSize() { return (this.columns == null) ? 0 : this.columns.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<TColumnIncrement> getColumnsIterator() { return (this.columns == null) ? null : this.columns.iterator(); } public void addToColumns(TColumnIncrement elem) { if (this.columns == null) { this.columns = new java.util.ArrayList<TColumnIncrement>(); } this.columns.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<TColumnIncrement> getColumns() { return this.columns; } public TIncrement setColumns(@org.apache.thrift.annotation.Nullable java.util.List<TColumnIncrement> columns) { this.columns = columns; return this; } public void unsetColumns() { this.columns = null; } /** Returns true if field columns is set (has been assigned a value) and false otherwise */ public boolean isSetColumns() { return this.columns != null; } public void setColumnsIsSet(boolean value) { if (!value) { this.columns = null; } } public int getAttributesSize() { return (this.attributes == null) ? 0 : this.attributes.size(); } public void putToAttributes(java.nio.ByteBuffer key, java.nio.ByteBuffer val) { if (this.attributes == null) { this.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(); } this.attributes.put(key, val); } @org.apache.thrift.annotation.Nullable public java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> getAttributes() { return this.attributes; } public TIncrement setAttributes(@org.apache.thrift.annotation.Nullable java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> attributes) { this.attributes = attributes; return this; } public void unsetAttributes() { this.attributes = null; } /** Returns true if field attributes is set (has been assigned a value) and false otherwise */ public boolean isSetAttributes() { return this.attributes != null; } public void setAttributesIsSet(boolean value) { if (!value) { this.attributes = null; } } /** * * @see TDurability */ @org.apache.thrift.annotation.Nullable public TDurability getDurability() { return this.durability; } /** * * @see TDurability */ public TIncrement setDurability(@org.apache.thrift.annotation.Nullable TDurability durability) { this.durability = durability; return this; } public void unsetDurability() { this.durability = null; } /** Returns true if field durability is set (has been assigned a value) and false otherwise */ public boolean isSetDurability() { return this.durability != null; } public void setDurabilityIsSet(boolean value) { if (!value) { this.durability = null; } } @org.apache.thrift.annotation.Nullable public TCellVisibility getCellVisibility() { return this.cellVisibility; } public TIncrement setCellVisibility(@org.apache.thrift.annotation.Nullable TCellVisibility cellVisibility) { this.cellVisibility = cellVisibility; return this; } public void unsetCellVisibility() { this.cellVisibility = null; } /** Returns true if field cellVisibility is set (has been assigned a value) and false otherwise */ public boolean isSetCellVisibility() { return this.cellVisibility != null; } public void setCellVisibilityIsSet(boolean value) { if (!value) { this.cellVisibility = null; } } public boolean isReturnResults() { return this.returnResults; } public TIncrement setReturnResults(boolean returnResults) { this.returnResults = returnResults; setReturnResultsIsSet(true); return this; } public void unsetReturnResults() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __RETURNRESULTS_ISSET_ID); } /** Returns true if field returnResults is set (has been assigned a value) and false otherwise */ public boolean isSetReturnResults() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __RETURNRESULTS_ISSET_ID); } public void setReturnResultsIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __RETURNRESULTS_ISSET_ID, value); } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case ROW: if (value == null) { unsetRow(); } else { if (value instanceof byte[]) { setRow((byte[])value); } else { setRow((java.nio.ByteBuffer)value); } } break; case COLUMNS: if (value == null) { unsetColumns(); } else { setColumns((java.util.List<TColumnIncrement>)value); } break; case ATTRIBUTES: if (value == null) { unsetAttributes(); } else { setAttributes((java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer>)value); } break; case DURABILITY: if (value == null) { unsetDurability(); } else { setDurability((TDurability)value); } break; case CELL_VISIBILITY: if (value == null) { unsetCellVisibility(); } else { setCellVisibility((TCellVisibility)value); } break; case RETURN_RESULTS: if (value == null) { unsetReturnResults(); } else { setReturnResults((java.lang.Boolean)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case ROW: return getRow(); case COLUMNS: return getColumns(); case ATTRIBUTES: return getAttributes(); case DURABILITY: return getDurability(); case CELL_VISIBILITY: return getCellVisibility(); case RETURN_RESULTS: return isReturnResults(); } 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 ROW: return isSetRow(); case COLUMNS: return isSetColumns(); case ATTRIBUTES: return isSetAttributes(); case DURABILITY: return isSetDurability(); case CELL_VISIBILITY: return isSetCellVisibility(); case RETURN_RESULTS: return isSetReturnResults(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof TIncrement) return this.equals((TIncrement)that); return false; } public boolean equals(TIncrement that) { if (that == null) return false; if (this == that) return true; boolean this_present_row = true && this.isSetRow(); boolean that_present_row = true && that.isSetRow(); if (this_present_row || that_present_row) { if (!(this_present_row && that_present_row)) return false; if (!this.row.equals(that.row)) return false; } boolean this_present_columns = true && this.isSetColumns(); boolean that_present_columns = true && that.isSetColumns(); if (this_present_columns || that_present_columns) { if (!(this_present_columns && that_present_columns)) return false; if (!this.columns.equals(that.columns)) return false; } boolean this_present_attributes = true && this.isSetAttributes(); boolean that_present_attributes = true && that.isSetAttributes(); if (this_present_attributes || that_present_attributes) { if (!(this_present_attributes && that_present_attributes)) return false; if (!this.attributes.equals(that.attributes)) return false; } boolean this_present_durability = true && this.isSetDurability(); boolean that_present_durability = true && that.isSetDurability(); if (this_present_durability || that_present_durability) { if (!(this_present_durability && that_present_durability)) return false; if (!this.durability.equals(that.durability)) return false; } boolean this_present_cellVisibility = true && this.isSetCellVisibility(); boolean that_present_cellVisibility = true && that.isSetCellVisibility(); if (this_present_cellVisibility || that_present_cellVisibility) { if (!(this_present_cellVisibility && that_present_cellVisibility)) return false; if (!this.cellVisibility.equals(that.cellVisibility)) return false; } boolean this_present_returnResults = true && this.isSetReturnResults(); boolean that_present_returnResults = true && that.isSetReturnResults(); if (this_present_returnResults || that_present_returnResults) { if (!(this_present_returnResults && that_present_returnResults)) return false; if (this.returnResults != that.returnResults) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetRow()) ? 131071 : 524287); if (isSetRow()) hashCode = hashCode * 8191 + row.hashCode(); hashCode = hashCode * 8191 + ((isSetColumns()) ? 131071 : 524287); if (isSetColumns()) hashCode = hashCode * 8191 + columns.hashCode(); hashCode = hashCode * 8191 + ((isSetAttributes()) ? 131071 : 524287); if (isSetAttributes()) hashCode = hashCode * 8191 + attributes.hashCode(); hashCode = hashCode * 8191 + ((isSetDurability()) ? 131071 : 524287); if (isSetDurability()) hashCode = hashCode * 8191 + durability.getValue(); hashCode = hashCode * 8191 + ((isSetCellVisibility()) ? 131071 : 524287); if (isSetCellVisibility()) hashCode = hashCode * 8191 + cellVisibility.hashCode(); hashCode = hashCode * 8191 + ((isSetReturnResults()) ? 131071 : 524287); if (isSetReturnResults()) hashCode = hashCode * 8191 + ((returnResults) ? 131071 : 524287); return hashCode; } @Override public int compareTo(TIncrement other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetRow(), other.isSetRow()); if (lastComparison != 0) { return lastComparison; } if (isSetRow()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.row, other.row); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetColumns(), other.isSetColumns()); if (lastComparison != 0) { return lastComparison; } if (isSetColumns()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.columns, other.columns); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetAttributes(), other.isSetAttributes()); if (lastComparison != 0) { return lastComparison; } if (isSetAttributes()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.attributes, other.attributes); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetDurability(), other.isSetDurability()); if (lastComparison != 0) { return lastComparison; } if (isSetDurability()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.durability, other.durability); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetCellVisibility(), other.isSetCellVisibility()); if (lastComparison != 0) { return lastComparison; } if (isSetCellVisibility()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cellVisibility, other.cellVisibility); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetReturnResults(), other.isSetReturnResults()); if (lastComparison != 0) { return lastComparison; } if (isSetReturnResults()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.returnResults, other.returnResults); 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("TIncrement("); boolean first = true; sb.append("row:"); if (this.row == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.row, sb); } first = false; if (!first) sb.append(", "); sb.append("columns:"); if (this.columns == null) { sb.append("null"); } else { sb.append(this.columns); } first = false; if (isSetAttributes()) { if (!first) sb.append(", "); sb.append("attributes:"); if (this.attributes == null) { sb.append("null"); } else { sb.append(this.attributes); } first = false; } if (isSetDurability()) { if (!first) sb.append(", "); sb.append("durability:"); if (this.durability == null) { sb.append("null"); } else { sb.append(this.durability); } first = false; } if (isSetCellVisibility()) { if (!first) sb.append(", "); sb.append("cellVisibility:"); if (this.cellVisibility == null) { sb.append("null"); } else { sb.append(this.cellVisibility); } first = false; } if (isSetReturnResults()) { if (!first) sb.append(", "); sb.append("returnResults:"); sb.append(this.returnResults); first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (row == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'row' was not present! Struct: " + toString()); } if (columns == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'columns' was not present! Struct: " + toString()); } // check for sub-struct validity if (cellVisibility != null) { cellVisibility.validate(); } } 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 TIncrementStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TIncrementStandardScheme getScheme() { return new TIncrementStandardScheme(); } } private static class TIncrementStandardScheme extends org.apache.thrift.scheme.StandardScheme<TIncrement> { public void read(org.apache.thrift.protocol.TProtocol iprot, TIncrement 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: // ROW if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.row = iprot.readBinary(); struct.setRowIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // COLUMNS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list70 = iprot.readListBegin(); struct.columns = new java.util.ArrayList<TColumnIncrement>(_list70.size); @org.apache.thrift.annotation.Nullable TColumnIncrement _elem71; for (int _i72 = 0; _i72 < _list70.size; ++_i72) { _elem71 = new TColumnIncrement(); _elem71.read(iprot); struct.columns.add(_elem71); } iprot.readListEnd(); } struct.setColumnsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ATTRIBUTES if (schemeField.type == org.apache.thrift.protocol.TType.MAP) { { org.apache.thrift.protocol.TMap _map73 = iprot.readMapBegin(); struct.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(2*_map73.size); @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _key74; @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _val75; for (int _i76 = 0; _i76 < _map73.size; ++_i76) { _key74 = iprot.readBinary(); _val75 = iprot.readBinary(); struct.attributes.put(_key74, _val75); } iprot.readMapEnd(); } struct.setAttributesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // DURABILITY if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.durability = org.apache.hadoop.hbase.thrift2.generated.TDurability.findByValue(iprot.readI32()); struct.setDurabilityIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // CELL_VISIBILITY if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.cellVisibility = new TCellVisibility(); struct.cellVisibility.read(iprot); struct.setCellVisibilityIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // RETURN_RESULTS if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.returnResults = iprot.readBool(); struct.setReturnResultsIsSet(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(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, TIncrement struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.row != null) { oprot.writeFieldBegin(ROW_FIELD_DESC); oprot.writeBinary(struct.row); oprot.writeFieldEnd(); } if (struct.columns != null) { oprot.writeFieldBegin(COLUMNS_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.columns.size())); for (TColumnIncrement _iter77 : struct.columns) { _iter77.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.attributes != null) { if (struct.isSetAttributes()) { oprot.writeFieldBegin(ATTRIBUTES_FIELD_DESC); { oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING, struct.attributes.size())); for (java.util.Map.Entry<java.nio.ByteBuffer, java.nio.ByteBuffer> _iter78 : struct.attributes.entrySet()) { oprot.writeBinary(_iter78.getKey()); oprot.writeBinary(_iter78.getValue()); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.durability != null) { if (struct.isSetDurability()) { oprot.writeFieldBegin(DURABILITY_FIELD_DESC); oprot.writeI32(struct.durability.getValue()); oprot.writeFieldEnd(); } } if (struct.cellVisibility != null) { if (struct.isSetCellVisibility()) { oprot.writeFieldBegin(CELL_VISIBILITY_FIELD_DESC); struct.cellVisibility.write(oprot); oprot.writeFieldEnd(); } } if (struct.isSetReturnResults()) { oprot.writeFieldBegin(RETURN_RESULTS_FIELD_DESC); oprot.writeBool(struct.returnResults); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class TIncrementTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TIncrementTupleScheme getScheme() { return new TIncrementTupleScheme(); } } private static class TIncrementTupleScheme extends org.apache.thrift.scheme.TupleScheme<TIncrement> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, TIncrement struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; oprot.writeBinary(struct.row); { oprot.writeI32(struct.columns.size()); for (TColumnIncrement _iter79 : struct.columns) { _iter79.write(oprot); } } java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetAttributes()) { optionals.set(0); } if (struct.isSetDurability()) { optionals.set(1); } if (struct.isSetCellVisibility()) { optionals.set(2); } if (struct.isSetReturnResults()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetAttributes()) { { oprot.writeI32(struct.attributes.size()); for (java.util.Map.Entry<java.nio.ByteBuffer, java.nio.ByteBuffer> _iter80 : struct.attributes.entrySet()) { oprot.writeBinary(_iter80.getKey()); oprot.writeBinary(_iter80.getValue()); } } } if (struct.isSetDurability()) { oprot.writeI32(struct.durability.getValue()); } if (struct.isSetCellVisibility()) { struct.cellVisibility.write(oprot); } if (struct.isSetReturnResults()) { oprot.writeBool(struct.returnResults); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, TIncrement struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; struct.row = iprot.readBinary(); struct.setRowIsSet(true); { org.apache.thrift.protocol.TList _list81 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRUCT); struct.columns = new java.util.ArrayList<TColumnIncrement>(_list81.size); @org.apache.thrift.annotation.Nullable TColumnIncrement _elem82; for (int _i83 = 0; _i83 < _list81.size; ++_i83) { _elem82 = new TColumnIncrement(); _elem82.read(iprot); struct.columns.add(_elem82); } } struct.setColumnsIsSet(true); java.util.BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { { org.apache.thrift.protocol.TMap _map84 = iprot.readMapBegin(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING); struct.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(2*_map84.size); @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _key85; @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _val86; for (int _i87 = 0; _i87 < _map84.size; ++_i87) { _key85 = iprot.readBinary(); _val86 = iprot.readBinary(); struct.attributes.put(_key85, _val86); } } struct.setAttributesIsSet(true); } if (incoming.get(1)) { struct.durability = org.apache.hadoop.hbase.thrift2.generated.TDurability.findByValue(iprot.readI32()); struct.setDurabilityIsSet(true); } if (incoming.get(2)) { struct.cellVisibility = new TCellVisibility(); struct.cellVisibility.read(iprot); struct.setCellVisibilityIsSet(true); } if (incoming.get(3)) { struct.returnResults = iprot.readBool(); struct.setReturnResultsIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
apache/ozone
36,849
hadoop-ozone/tools/src/main/java/org/apache/hadoop/ozone/debug/ldb/DBScanner.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.debug.ldb; import static java.nio.charset.StandardCharsets.UTF_8; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.hdds.cli.AbstractSubcommand; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.scm.container.ContainerID; import org.apache.hadoop.hdds.scm.pipeline.PipelineID; import org.apache.hadoop.hdds.utils.IOUtils; import org.apache.hadoop.hdds.utils.db.DBColumnFamilyDefinition; import org.apache.hadoop.hdds.utils.db.DBDefinition; import org.apache.hadoop.hdds.utils.db.FixedLengthStringCodec; import org.apache.hadoop.hdds.utils.db.LongCodec; import org.apache.hadoop.hdds.utils.db.RocksDatabase; import org.apache.hadoop.hdds.utils.db.managed.ManagedReadOptions; import org.apache.hadoop.hdds.utils.db.managed.ManagedRocksDB; import org.apache.hadoop.hdds.utils.db.managed.ManagedRocksIterator; import org.apache.hadoop.hdds.utils.db.managed.ManagedSlice; import org.apache.hadoop.ozone.OzoneConsts; import org.apache.hadoop.ozone.container.common.statemachine.DatanodeConfiguration; import org.apache.hadoop.ozone.container.metadata.DatanodeSchemaThreeDBDefinition; import org.apache.hadoop.ozone.debug.DBDefinitionFactory; import org.apache.hadoop.ozone.debug.RocksDBUtils; import org.apache.hadoop.ozone.utils.Filter; import org.rocksdb.ColumnFamilyDescriptor; import org.rocksdb.ColumnFamilyHandle; import org.rocksdb.RocksDBException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import picocli.CommandLine; /** * Parser for scm.db, om.db or container db file. */ @CommandLine.Command( name = "scan", description = "Parse specified metadataTable" ) public class DBScanner extends AbstractSubcommand implements Callable<Void> { private static final Logger LOG = LoggerFactory.getLogger(DBScanner.class); private static final String SCHEMA_V3 = "V3"; @CommandLine.ParentCommand private RDBParser parent; @CommandLine.Option(names = {"--column_family", "--column-family", "--cf"}, required = true, description = "Table name") private String tableName; @CommandLine.Option(names = {"--with-keys"}, description = "Print a JSON object of key->value pairs (default)" + " instead of a JSON array of only values.", defaultValue = "true", fallbackValue = "true") private boolean withKey; @CommandLine.Option(names = {"--length", "--limit", "-l"}, description = "Maximum number of items to list.", defaultValue = "-1") private long limit; @CommandLine.Option(names = {"--out", "-o"}, description = "File to dump table scan data") private String fileName; @CommandLine.Option(names = {"--startkey", "--sk", "-s"}, description = "Key from which to iterate the DB") private String startKey; @CommandLine.Option(names = {"--endkey", "--ek", "-e"}, description = "Key at which iteration of the DB ends") private String endKey; @CommandLine.Option(names = {"--fields"}, description = "Comma-separated list of fields needed for each value. " + "eg.) \"name,acls.type\" for showing name and type under acls.") private String fieldsFilter; @CommandLine.Option(names = {"--filter"}, description = "Comma-separated list of \"<field>:<operator>:<value>\" where " + "<field> is any valid field of the record, " + "<operator> is [EQUALS,LESSER, GREATER or REGEX]. (EQUALS compares the exact string, " + "REGEX compares with a valid regular expression passed, and LESSER/GREATER works with numeric values), " + "<value> is the value of the field. \n" + "eg.) \"dataSize:equals:1000\" for showing records having the value 1000 for dataSize, \n" + " \"keyName:regex:^key.*$\" for showing records having keyName that matches the given regex.") private String filter; @CommandLine.Option(names = {"--dnSchema", "--dn-schema", "-d"}, description = "Datanode DB Schema Version: V1/V2/V3", defaultValue = "V3") private String dnDBSchemaVersion; @CommandLine.Option(names = {"--container-id", "--cid"}, description = "Container ID. Applicable if datanode DB Schema is V3", defaultValue = "-1") private long containerId; @CommandLine.Option(names = { "--show-count", "--count" }, description = "Get estimated key count for the given DB column family", defaultValue = "false", showDefaultValue = CommandLine.Help.Visibility.ALWAYS) private boolean showCount; @CommandLine.Option(names = {"--compact"}, description = "disable the pretty print the output", defaultValue = "false") private static boolean compact; @CommandLine.Option(names = {"--batch-size"}, description = "Batch size for processing DB data.", defaultValue = "10000") private int batchSize; @CommandLine.Option(names = {"--thread-count"}, description = "Thread count for concurrent processing.", defaultValue = "10") private int threadCount; @CommandLine.Option(names = {"--max-records-per-file"}, description = "The number of records to print per file.", defaultValue = "0") private long recordsPerFile; private int fileSuffix = 0; private long globalCount = 0; private static final String KEY_SEPARATOR_SCHEMA_V3 = new OzoneConfiguration().getObject(DatanodeConfiguration.class) .getContainerSchemaV3KeySeparator(); private static volatile boolean exception; private static final long FIRST_SEQUENCE_ID = 0L; @Override public Void call() throws Exception { fileSuffix = 0; globalCount = 0; List<ColumnFamilyDescriptor> cfDescList = RocksDBUtils.getColumnFamilyDescriptors(parent.getDbPath()); final List<ColumnFamilyHandle> cfHandleList = new ArrayList<>(); final boolean schemaV3 = dnDBSchemaVersion != null && dnDBSchemaVersion.equalsIgnoreCase(SCHEMA_V3) && parent.getDbPath().contains(OzoneConsts.CONTAINER_DB_NAME); boolean success; try (ManagedRocksDB db = ManagedRocksDB.openReadOnly( parent.getDbPath(), cfDescList, cfHandleList)) { success = printTable(cfHandleList, db, parent.getDbPath(), schemaV3); } if (!success) { // Trick to set exit code to 1 on error. // TODO: Properly set exit code hopefully by refactoring GenericCli throw new Exception( "Exit code is non-zero. Check the error message above"); } return null; } public byte[] getValueObject(DBColumnFamilyDefinition dbColumnFamilyDefinition, String key) { Class<?> keyType = dbColumnFamilyDefinition.getKeyType(); if (keyType.equals(String.class)) { return key.getBytes(UTF_8); } else if (keyType.equals(ContainerID.class)) { return ContainerID.getBytes(Long.parseLong(key)); } else if (keyType.equals(Long.class)) { return LongCodec.get().toPersistedFormat(Long.parseLong(key)); } else if (keyType.equals(PipelineID.class)) { return PipelineID.valueOf(UUID.fromString(key)).getProtobuf() .toByteArray(); } else { throw new IllegalArgumentException( "StartKey and EndKey is not supported for this table."); } } private boolean displayTable(ManagedRocksIterator iterator, DBColumnFamilyDefinition dbColumnFamilyDef, boolean schemaV3) throws IOException { if (fileName == null) { // Print to stdout return displayTable(iterator, dbColumnFamilyDef, out(), schemaV3); } // If there are no parent directories, create them File file = new File(fileName); File parentFile = file.getParentFile(); if (!parentFile.exists()) { boolean flg = parentFile.mkdirs(); if (!flg) { throw new IOException("An exception occurred while creating " + "the directory. Directory: " + parentFile.getAbsolutePath()); } } // Write to file output while (iterator.get().isValid() && withinLimit(globalCount)) { String fileNameTarget = recordsPerFile > 0 ? fileName + "." + fileSuffix++ : fileName; try (PrintWriter out = new PrintWriter(new BufferedWriter( new PrintWriter(fileNameTarget, UTF_8.name())))) { if (!displayTable(iterator, dbColumnFamilyDef, out, schemaV3)) { return false; } } } return true; } private boolean displayTable(ManagedRocksIterator iterator, DBColumnFamilyDefinition dbColumnFamilyDef, PrintWriter printWriter, boolean schemaV3) { exception = false; ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat("DBScanner-%d") .build(); ExecutorService threadPool = new ThreadPoolExecutor( threadCount, threadCount, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), factory, new ThreadPoolExecutor.CallerRunsPolicy()); LogWriter logWriter = new LogWriter(printWriter); try { // Start JSON object (map) or array printWriter.print(withKey ? "{ " : "[ "); logWriter.start(); processRecords(iterator, dbColumnFamilyDef, logWriter, threadPool, schemaV3); } catch (InterruptedException | IOException e) { exception = true; Thread.currentThread().interrupt(); } finally { threadPool.shutdownNow(); logWriter.stop(); logWriter.join(); // End JSON object (map) or array printWriter.println(withKey ? " }" : " ]"); } return !exception; } private void processRecords(ManagedRocksIterator iterator, DBColumnFamilyDefinition dbColumnFamilyDef, LogWriter logWriter, ExecutorService threadPool, boolean schemaV3) throws InterruptedException, IOException { if (startKey != null) { iterator.get().seek(getValueObject(dbColumnFamilyDef, startKey)); } ArrayList<ByteArrayKeyValue> batch = new ArrayList<>(batchSize); // Used to ensure that the output of a multi-threaded parsed Json is in // the same order as the RocksDB iterator. long sequenceId = FIRST_SEQUENCE_ID; // Count number of keys printed so far long count = 0; List<Future<Void>> futures = new ArrayList<>(); boolean reachedEnd = false; Map<String, Filter> fieldsFilterSplitMap = new HashMap<>(); if (filter != null) { for (String field : filter.split(",")) { String[] fieldValue = field.split(":"); if (fieldValue.length != 3) { err().println("Error: Invalid format for filter \"" + field + "\". Usage: <field>:<operator>:<value>. Ignoring filter passed"); } else { Filter filterValue = new Filter(fieldValue[1], fieldValue[2]); if (filterValue.getOperator() == null) { err().println("Error: Invalid operator for filter \"" + filterValue + "\". <operator> can be one of [EQUALS,LESSER,GREATER]. Ignoring filter passed"); } else { String[] subfields = fieldValue[0].split("\\."); getFilterSplit(Arrays.asList(subfields), fieldsFilterSplitMap, filterValue); } } } } while (withinLimit(globalCount) && iterator.get().isValid() && !exception && !reachedEnd) { // if invalid endKey is given, it is ignored if (null != endKey && Arrays.equals(iterator.get().key(), getValueObject(dbColumnFamilyDef, endKey))) { reachedEnd = true; } Object o = dbColumnFamilyDef.getValueCodec().fromPersistedFormat(iterator.get().value()); if (filter == null || checkFilteredObject(o, dbColumnFamilyDef.getValueType(), fieldsFilterSplitMap)) { // the record passes the filter batch.add(new ByteArrayKeyValue( iterator.get().key(), iterator.get().value())); globalCount++; count++; if (batch.size() >= batchSize) { while (logWriter.getInflightLogCount() > threadCount * 10L && !exception) { // Prevents too many unfinished Tasks from // consuming too much memory. Thread.sleep(100); } Future<Void> future = threadPool.submit( new Task(dbColumnFamilyDef, batch, logWriter, sequenceId, withKey, schemaV3, fieldsFilter)); futures.add(future); batch = new ArrayList<>(batchSize); sequenceId++; } } iterator.get().next(); if ((recordsPerFile > 0) && (count >= recordsPerFile)) { break; } } if (!batch.isEmpty()) { Future<Void> future = threadPool.submit(new Task(dbColumnFamilyDef, batch, logWriter, sequenceId, withKey, schemaV3, fieldsFilter)); futures.add(future); } for (Future<Void> future : futures) { try { future.get(); } catch (ExecutionException e) { LOG.error("Task execution failed", e); } } } private void getFilterSplit(List<String> fields, Map<String, Filter> fieldMap, Filter leafValue) throws IOException { int len = fields.size(); if (len == 1) { Filter currentValue = fieldMap.get(fields.get(0)); if (currentValue != null) { err().println("Cannot pass multiple values for the same field and " + "cannot have filter for both parent and child"); throw new IOException("Invalid filter passed"); } fieldMap.put(fields.get(0), leafValue); } else { Filter fieldMapGet = fieldMap.computeIfAbsent(fields.get(0), k -> new Filter()); if (fieldMapGet.getValue() != null) { err().println("Cannot pass multiple values for the same field and " + "cannot have filter for both parent and child"); throw new IOException("Invalid filter passed"); } Map<String, Filter> nextLevel = fieldMapGet.getNextLevel(); if (nextLevel == null) { fieldMapGet.setNextLevel(new HashMap<>()); } getFilterSplit(fields.subList(1, len), fieldMapGet.getNextLevel(), leafValue); } } private boolean checkFilteredObject(Object obj, Class<?> clazz, Map<String, Filter> fieldsSplitMap) { for (Map.Entry<String, Filter> field : fieldsSplitMap.entrySet()) { try { Field valueClassField = getRequiredFieldFromAllFields(clazz, field.getKey()); Object valueObject = valueClassField.get(obj); Filter fieldValue = field.getValue(); if (valueObject == null) { // there is no such field in the record. This filter will be ignored for the current record. continue; } if (fieldValue == null) { err().println("Malformed filter. Check input"); throw new IOException("Invalid filter passed"); } else if (fieldValue.getNextLevel() == null) { // reached the end of fields hierarchy, check if they match the filter try { switch (fieldValue.getOperator()) { case EQUALS: if (!String.valueOf(valueObject).equals(fieldValue.getValue())) { return false; } break; case GREATER: if (Double.parseDouble(String.valueOf(valueObject)) < Double.parseDouble(String.valueOf(fieldValue.getValue()))) { return false; } break; case LESSER: if (Double.parseDouble(String.valueOf(valueObject)) > Double.parseDouble(String.valueOf(fieldValue.getValue()))) { return false; } break; case REGEX: Pattern p = Pattern.compile(String.valueOf(fieldValue.getValue())); Matcher m = p.matcher(String.valueOf(valueObject)); if (!m.find()) { return false; } break; default: err().println("Only EQUALS/LESSER/GREATER/REGEX operator is supported currently."); throw new IOException("Invalid filter passed"); } } catch (NumberFormatException ex) { err().println("LESSER or GREATER operation can be performed only on numeric values."); throw new IOException("Invalid filter passed"); } } else { Map<String, Filter> subfields = fieldValue.getNextLevel(); if (Collection.class.isAssignableFrom(valueObject.getClass())) { if (!checkFilteredObjectCollection((Collection) valueObject, subfields)) { return false; } } else if (Map.class.isAssignableFrom(valueObject.getClass())) { Map<?, ?> valueObjectMap = (Map<?, ?>) valueObject; boolean flag = false; for (Map.Entry<?, ?> ob : valueObjectMap.entrySet()) { boolean subflag; if (Collection.class.isAssignableFrom(ob.getValue().getClass())) { subflag = checkFilteredObjectCollection((Collection)ob.getValue(), subfields); } else { subflag = checkFilteredObject(ob.getValue(), ob.getValue().getClass(), subfields); } if (subflag) { // atleast one item in the map/list of the record has matched the filter, // so record passes the filter. flag = true; break; } } if (!flag) { // none of the items in the map/list passed the filter => record doesn't pass the filter return false; } } else { if (!checkFilteredObject(valueObject, valueClassField.getType(), subfields)) { return false; } } } } catch (NoSuchFieldException ex) { err().println("ERROR: no such field: " + field); exception = true; return false; } catch (IllegalAccessException e) { err().println("ERROR: Cannot get field \"" + field + "\" from record."); exception = true; return false; } catch (Exception ex) { err().println("ERROR: field: " + field + ", ex: " + ex); exception = true; return false; } } return true; } private boolean checkFilteredObjectCollection(Collection<?> valueObject, Map<String, Filter> fields) throws NoSuchFieldException, IllegalAccessException, IOException { for (Object ob : valueObject) { if (checkFilteredObject(ob, ob.getClass(), fields)) { return true; } } return false; } Field getRequiredFieldFromAllFields(Class clazz, String fieldName) throws NoSuchFieldException { List<Field> classFieldList = ValueSchema.getAllFields(clazz); Field classField = null; for (Field f : classFieldList) { if (f.getName().equals(fieldName)) { classField = f; break; } } if (classField == null) { err().println("Error: Invalid field \"" + fieldName + "\" passed for filter"); throw new NoSuchFieldException(); } classField.setAccessible(true); return classField; } private boolean withinLimit(long i) { return limit == -1L || i < limit; } private ColumnFamilyHandle getColumnFamilyHandle( byte[] name, List<ColumnFamilyHandle> columnFamilyHandles) { return columnFamilyHandles .stream() .filter( handle -> { try { return Arrays.equals(handle.getName(), name); } catch (Exception ex) { throw new RuntimeException(ex); } }) .findAny() .orElse(null); } /** * Main table printing logic. * User-provided args are not in the arg list. Those are instance variables * parsed by picocli. */ private boolean printTable(List<ColumnFamilyHandle> columnFamilyHandleList, ManagedRocksDB rocksDB, String dbPath, boolean schemaV3) throws IOException, RocksDBException { if (limit < 1 && limit != -1) { throw new IllegalArgumentException( "List length should be a positive number. Only allowed negative" + " number is -1 which is to dump entire table"); } dbPath = removeTrailingSlashIfNeeded(dbPath); DBDefinitionFactory.setDnDBSchemaVersion(dnDBSchemaVersion); DBDefinition dbDefinition = DBDefinitionFactory.getDefinition( Paths.get(dbPath), new OzoneConfiguration()); if (dbDefinition == null) { err().println("Error: Incorrect DB Path"); return false; } final DBColumnFamilyDefinition<?, ?> columnFamilyDefinition = dbDefinition.getColumnFamily(tableName); if (columnFamilyDefinition == null) { err().print("Error: Table with name '" + tableName + "' not found"); return false; } ColumnFamilyHandle columnFamilyHandle = getColumnFamilyHandle( columnFamilyDefinition.getName().getBytes(UTF_8), columnFamilyHandleList); if (columnFamilyHandle == null) { throw new IllegalStateException("columnFamilyHandle is null"); } if (showCount) { // Only prints estimates key count long keyCount = rocksDB.get() .getLongProperty(columnFamilyHandle, RocksDatabase.ESTIMATE_NUM_KEYS); out().println(keyCount); return true; } ManagedRocksIterator iterator = null; ManagedReadOptions readOptions = null; ManagedSlice slice = null; try { if (containerId > 0L && schemaV3) { // Handle SchemaV3 DN DB readOptions = new ManagedReadOptions(); slice = new ManagedSlice( DatanodeSchemaThreeDBDefinition.getContainerKeyPrefixBytes( containerId + 1L)); readOptions.setIterateUpperBound(slice); iterator = new ManagedRocksIterator( rocksDB.get().newIterator(columnFamilyHandle, readOptions)); iterator.get().seek( DatanodeSchemaThreeDBDefinition.getContainerKeyPrefixBytes( containerId)); } else { iterator = new ManagedRocksIterator( rocksDB.get().newIterator(columnFamilyHandle)); iterator.get().seekToFirst(); } return displayTable(iterator, columnFamilyDefinition, schemaV3); } finally { IOUtils.closeQuietly(iterator, readOptions, slice); } } private String removeTrailingSlashIfNeeded(String dbPath) { if (dbPath.endsWith(OzoneConsts.OZONE_URI_DELIMITER)) { dbPath = dbPath.substring(0, dbPath.length() - 1); } return dbPath; } /** * Utility for centralized JSON serialization using Jackson. */ @VisibleForTesting public static class JsonSerializationHelper { /** * In order to maintain consistency with the original Gson output to do * this setup makes the output from Jackson closely match the * output of Gson. */ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() .registerModule(new JavaTimeModule()) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) // Ignore standard getters. .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) // Ignore boolean "is" getters. .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) // Exclude null values. .setSerializationInclusion(JsonInclude.Include.NON_NULL) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); public static final ObjectWriter WRITER; static { if (compact) { WRITER = OBJECT_MAPPER.writer(); } else { WRITER = OBJECT_MAPPER.writerWithDefaultPrettyPrinter(); } } public static ObjectWriter getWriter() { return WRITER; } } private class Task implements Callable<Void> { private final DBColumnFamilyDefinition dbColumnFamilyDefinition; private final ArrayList<ByteArrayKeyValue> batch; private final LogWriter logWriter; private final ObjectWriter writer = JsonSerializationHelper.getWriter(); private final long sequenceId; private final boolean withKey; private final boolean schemaV3; private String valueFields; @SuppressWarnings("checkstyle:parameternumber") Task(DBColumnFamilyDefinition dbColumnFamilyDefinition, ArrayList<ByteArrayKeyValue> batch, LogWriter logWriter, long sequenceId, boolean withKey, boolean schemaV3, String valueFields) { this.dbColumnFamilyDefinition = dbColumnFamilyDefinition; this.batch = batch; this.logWriter = logWriter; this.sequenceId = sequenceId; this.withKey = withKey; this.schemaV3 = schemaV3; this.valueFields = valueFields; } Map<String, Object> getFieldSplit(List<String> fields, Map<String, Object> fieldMap) { int len = fields.size(); if (fieldMap == null) { fieldMap = new HashMap<>(); } if (len == 1) { fieldMap.putIfAbsent(fields.get(0), null); } else { Map<String, Object> fieldMapGet = (Map<String, Object>) fieldMap.get(fields.get(0)); if (fieldMapGet == null) { fieldMap.put(fields.get(0), getFieldSplit(fields.subList(1, len), null)); } else { fieldMap.put(fields.get(0), getFieldSplit(fields.subList(1, len), fieldMapGet)); } } return fieldMap; } @Override public Void call() { try { ArrayList<String> results = new ArrayList<>(batch.size()); Map<String, Object> fieldsSplitMap = new HashMap<>(); if (valueFields != null) { for (String field : valueFields.split(",")) { String[] subfields = field.split("\\."); fieldsSplitMap = getFieldSplit(Arrays.asList(subfields), fieldsSplitMap); } } for (ByteArrayKeyValue byteArrayKeyValue : batch) { StringBuilder sb = new StringBuilder(); if (!(sequenceId == FIRST_SEQUENCE_ID && results.isEmpty())) { // Add a comma before each output entry, starting from the second // one, to ensure valid JSON format. sb.append(", "); } if (withKey) { Object key = dbColumnFamilyDefinition.getKeyCodec() .fromPersistedFormat(byteArrayKeyValue.getKey()); if (schemaV3) { int index = DatanodeSchemaThreeDBDefinition.getContainerKeyPrefixLength(); String keyStr = key.toString(); if (index > keyStr.length()) { err().println("Error: Invalid SchemaV3 table key length. " + "Is this a V2 table? Try again with --dn-schema=V2"); exception = true; break; } String cid = key.toString().substring(0, index); String blockId = key.toString().substring(index); sb.append(writer.writeValueAsString(LongCodec.get() .fromPersistedFormat( FixedLengthStringCodec.string2Bytes(cid)) + KEY_SEPARATOR_SCHEMA_V3 + blockId)); } else { sb.append(writer.writeValueAsString(key)); } sb.append(": "); } Object o = dbColumnFamilyDefinition.getValueCodec() .fromPersistedFormat(byteArrayKeyValue.getValue()); if (valueFields != null) { Map<String, Object> filteredValue = new HashMap<>(); filteredValue.putAll(getFieldsFilteredObject(o, dbColumnFamilyDefinition.getValueType(), fieldsSplitMap)); sb.append(writer.writeValueAsString(filteredValue)); } else { sb.append(writer.writeValueAsString(o)); } results.add(sb.toString()); } logWriter.log(results, sequenceId); } catch (IOException e) { exception = true; LOG.error("Exception parse Object", e); } return null; } Map<String, Object> getFieldsFilteredObject(Object obj, Class<?> clazz, Map<String, Object> fieldsSplitMap) { Map<String, Object> valueMap = new HashMap<>(); for (Map.Entry<String, Object> field : fieldsSplitMap.entrySet()) { try { Field valueClassField = getRequiredFieldFromAllFields(clazz, field.getKey()); Object valueObject = valueClassField.get(obj); Map<String, Object> subfields = (Map<String, Object>) field.getValue(); if (subfields == null) { valueMap.put(field.getKey(), valueObject); } else { if (Collection.class.isAssignableFrom(valueObject.getClass())) { List<Object> subfieldObjectsList = getFieldsFilteredObjectCollection((Collection) valueObject, subfields); valueMap.put(field.getKey(), subfieldObjectsList); } else if (Map.class.isAssignableFrom(valueObject.getClass())) { Map<Object, Object> subfieldObjectsMap = new HashMap<>(); Map<?, ?> valueObjectMap = (Map<?, ?>) valueObject; for (Map.Entry<?, ?> ob : valueObjectMap.entrySet()) { Object subfieldValue; if (Collection.class.isAssignableFrom(ob.getValue().getClass())) { subfieldValue = getFieldsFilteredObjectCollection((Collection)ob.getValue(), subfields); } else { subfieldValue = getFieldsFilteredObject(ob.getValue(), ob.getValue().getClass(), subfields); } subfieldObjectsMap.put(ob.getKey(), subfieldValue); } valueMap.put(field.getKey(), subfieldObjectsMap); } else { valueMap.put(field.getKey(), getFieldsFilteredObject(valueObject, valueClassField.getType(), subfields)); } } } catch (NoSuchFieldException ex) { err().println("ERROR: no such field: " + field); } catch (IllegalAccessException e) { err().println("ERROR: Cannot get field from object: " + field); } } return valueMap; } List<Object> getFieldsFilteredObjectCollection(Collection<?> valueObject, Map<String, Object> fields) throws NoSuchFieldException, IllegalAccessException { List<Object> subfieldObjectsList = new ArrayList<>(); for (Object ob : valueObject) { Object subfieldValue = getFieldsFilteredObject(ob, ob.getClass(), fields); subfieldObjectsList.add(subfieldValue); } return subfieldObjectsList; } } private static class ByteArrayKeyValue { private final byte[] key; private final byte[] value; ByteArrayKeyValue(byte[] key, byte[] value) { this.key = key; this.value = value; } public byte[] getKey() { return key; } public byte[] getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ByteArrayKeyValue that = (ByteArrayKeyValue) o; return Arrays.equals(key, that.key); } @Override public int hashCode() { return Arrays.hashCode(key); } @Override public String toString() { return "ByteArrayKeyValue{" + "key=" + Arrays.toString(key) + ", value=" + Arrays.toString(value) + '}'; } } private static class LogWriter { private final Map<Long, ArrayList<String>> logs; private final PrintWriter printWriter; private final Thread writerThread; private volatile boolean stop = false; private long expectedSequenceId = FIRST_SEQUENCE_ID; private final Object lock = new Object(); private final AtomicLong inflightLogCount = new AtomicLong(); LogWriter(PrintWriter printWriter) { this.logs = new HashMap<>(); this.printWriter = printWriter; this.writerThread = new Thread(new WriterTask()); } void start() { writerThread.start(); } public void log(ArrayList<String> msg, long sequenceId) { synchronized (lock) { if (!stop) { logs.put(sequenceId, msg); inflightLogCount.incrementAndGet(); lock.notify(); } } } private final class WriterTask implements Runnable { @Override public void run() { try { while (!stop) { synchronized (lock) { // The sequenceId is incrementally generated as the RocksDB // iterator. Thus, based on the sequenceId, we can strictly ensure // that the output order here is consistent with the order of the // RocksDB iterator. // Note that the order here not only requires the sequenceId to be // incremental, but also demands that the sequenceId of the // next output is the current sequenceId + 1. ArrayList<String> results = logs.get(expectedSequenceId); if (results != null) { for (String result : results) { printWriter.println(result); } inflightLogCount.decrementAndGet(); logs.remove(expectedSequenceId); // sequenceId of the next output must be the current // sequenceId + 1 expectedSequenceId++; } else { lock.wait(1000); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { LOG.error("Exception while output", e); } finally { stop = true; synchronized (lock) { drainRemainingMessages(); } } } } private void drainRemainingMessages() { ArrayList<String> results; while ((results = logs.get(expectedSequenceId)) != null) { for (String result : results) { printWriter.println(result); } expectedSequenceId++; } } public void stop() { if (!stop) { stop = true; writerThread.interrupt(); } } public void join() { try { writerThread.join(); } catch (InterruptedException e) { LOG.error("InterruptedException while output", e); Thread.currentThread().interrupt(); } } public long getInflightLogCount() { return inflightLogCount.get(); } } }
apache/maven-surefire
37,015
surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilderTest.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.maven.surefire.junitcore.pc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import net.jcip.annotations.NotThreadSafe; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.RunNotifier; import org.junit.runners.ParentRunner; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import static org.apache.maven.surefire.junitcore.pc.RangeMatcher.between; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** * @author Tibor Digana (tibor17) * @since 2.16 */ @SuppressWarnings("checkstyle:magicnumber") public class ParallelComputerBuilderTest { private static final int DELAY_MULTIPLIER = 7; private static final Object CLASS1BLOCK = new Object(); private static volatile boolean beforeShutdown; private static volatile Runnable shutdownTask; private static final ConsoleLogger LOGGER = mock(ConsoleLogger.class); private static void testKeepBeforeAfter(ParallelComputerBuilder builder, Class<?>... classes) { JUnitCore core = new JUnitCore(); for (int round = 0; round < 5; round++) { NothingDoingTest1.METHODS.clear(); Result result = core.run(builder.buildComputer(), classes); assertTrue(result.wasSuccessful()); Iterator<String> methods = NothingDoingTest1.METHODS.iterator(); for (Class<?> clazz : classes) { String a = clazz.getName() + "#a()"; String b = clazz.getName() + "#b()"; assertThat(methods.next(), is("init")); assertThat(methods.next(), anyOf(is(a), is(b))); assertThat(methods.next(), anyOf(is(a), is(b))); assertThat(methods.next(), is("deinit")); } } } @BeforeClass public static void cleanup() throws InterruptedException { System.gc(); Thread.sleep(500L); } @Before public void beforeTest() { Class1.maxConcurrentMethods = 0; Class1.concurrentMethods = 0; shutdownTask = null; NotThreadSafeTest1.t = null; NotThreadSafeTest2.t = null; NotThreadSafeTest3.t = null; NormalTest1.t = null; NormalTest2.t = null; } @Test public void testsWithoutChildrenShouldAlsoBeRun() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); Result result = new JUnitCore().run(computer, TestWithoutPrecalculatedChildren.class); assertThat(result.getRunCount(), is(1)); } @Test public void parallelMethodsReuseOneOrTwoThreads() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.useOnePool(4); // One thread because one suite: TestSuite, however the capacity is 5. parallelComputerBuilder.parallelSuites(5); // Two threads because TestSuite has two classes, however the capacity is 5. parallelComputerBuilder.parallelClasses(5); // One or two threads because one threads comes from '#useOnePool(4)' // and next thread may be reused from finished class, however the capacity is 3. parallelComputerBuilder.parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); // final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class); // final long t2 = systemMillis(); // final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(0)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(4)); assertTrue(result.wasSuccessful()); // this is flaky as depending on hardware so comment this // if (Class1.maxConcurrentMethods == 1) { // assertThat(timeSpent, between(2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER)); // } else if (Class1.maxConcurrentMethods == 2) { // assertThat(timeSpent, between(1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER)); // } else { // fail(); // } } @Test public void suiteAndClassInOnePool() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.useOnePool(5); parallelComputerBuilder.parallelSuites(5); parallelComputerBuilder.parallelClasses(5); parallelComputerBuilder.parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(1)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(5)); assertTrue(result.wasSuccessful()); assertThat(Class1.maxConcurrentMethods, is(2)); assertThat( timeSpent, anyOf( between(1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER), between(2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER), between(2500 * DELAY_MULTIPLIER - 50, 2750 * DELAY_MULTIPLIER))); } @Test public void onePoolWithUnlimitedParallelMethods() { // see ParallelComputerBuilder Javadoc ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.useOnePool(8); parallelComputerBuilder.parallelSuites(2); parallelComputerBuilder.parallelClasses(4); parallelComputerBuilder.parallelMethods(); assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(1)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(8)); assertTrue(result.wasSuccessful()); assertThat(Class1.maxConcurrentMethods, is(4)); assertThat(timeSpent, between(1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test public void underflowParallelism() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.useOnePool(3); // One thread because one suite: TestSuite. parallelComputerBuilder.parallelSuites(5); // One thread because of the limitation which is bottleneck. parallelComputerBuilder.parallelClasses(1); // One thread remains from '#useOnePool(3)'. parallelComputerBuilder.parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(0)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(3)); assertTrue(result.wasSuccessful()); assertThat(Class1.maxConcurrentMethods, is(1)); assertThat(timeSpent, between(2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER)); } @Test public void separatePoolsWithSuite() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.parallelSuites(5); parallelComputerBuilder.parallelClasses(5); parallelComputerBuilder.parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(0)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertTrue(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED)); assertTrue(result.wasSuccessful()); assertThat(Class1.maxConcurrentMethods, is(3)); assertThat(timeSpent, between(1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test public void separatePoolsWithSuiteAndClass() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.parallelSuites(5); parallelComputerBuilder.parallelClasses(5); parallelComputerBuilder.parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); // 6 methods altogether. // 2 groups with 3 threads. // Each group takes 0.5 s. ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(1)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertTrue(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED)); assertTrue(result.wasSuccessful()); assertThat(Class1.maxConcurrentMethods, is(3)); assertThat(timeSpent, between(1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test public void separatePoolsWithSuiteAndSequentialClasses() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.parallelSuites(5); parallelComputerBuilder.parallelClasses(1); parallelComputerBuilder.parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertThat(computer.getSuites().size(), is(1)); assertThat(computer.getClasses().size(), is(1)); assertThat(computer.getNestedClasses().size(), is(2)); assertThat(computer.getNestedSuites().size(), is(0)); assertTrue(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED)); assertTrue(result.wasSuccessful()); assertThat(Class1.maxConcurrentMethods, is(2)); assertThat(timeSpent, between(1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER)); } @Test(timeout = 2000 * DELAY_MULTIPLIER) public void shutdown() { final long t1 = systemMillis(); final Result result = new ShutdownTest().run(false); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertTrue(result.wasSuccessful()); assertTrue(beforeShutdown); assertThat(timeSpent, between(500 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test(timeout = 2000 * DELAY_MULTIPLIER) public void shutdownWithInterrupt() { final long t1 = systemMillis(); new ShutdownTest().run(true); final long t2 = systemMillis(); final long timeSpent = t2 - t1; assertTrue(beforeShutdown); assertThat(timeSpent, between(500 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test public void nothingParallel() { JUnitCore core = new JUnitCore(); ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); assertFalse(builder.isOptimized()); Result result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingTest2.class); assertTrue(result.wasSuccessful()); result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class); assertTrue(result.wasSuccessful()); builder.useOnePool(1); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingTest2.class); assertTrue(result.wasSuccessful()); builder.useOnePool(1); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class); assertTrue(result.wasSuccessful()); builder.useOnePool(2); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class); assertTrue(result.wasSuccessful()); Class<?>[] classes = {NothingDoingTest1.class, NothingDoingSuite.class}; builder.useOnePool(2).parallelSuites(1).parallelClasses(1); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), classes); assertTrue(result.wasSuccessful()); builder.useOnePool(2).parallelSuites(1).parallelClasses(); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), classes); assertTrue(result.wasSuccessful()); classes = new Class<?>[] { NothingDoingSuite.class, NothingDoingSuite.class, NothingDoingTest1.class, NothingDoingTest2.class, NothingDoingTest3.class }; builder.useOnePool(2).parallelSuites(1).parallelClasses(1); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), classes); assertTrue(result.wasSuccessful()); builder.useOnePool(2).parallelSuites(1).parallelClasses(); assertFalse(builder.isOptimized()); result = core.run(builder.buildComputer(), classes); assertTrue(result.wasSuccessful()); } @Test public void keepBeforeAfterOneClass() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); builder.parallelMethods(); assertFalse(builder.isOptimized()); testKeepBeforeAfter(builder, NothingDoingTest1.class); } @Test public void keepBeforeAfterTwoClasses() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); builder.useOnePool(5).parallelClasses(1).parallelMethods(2); assertFalse(builder.isOptimized()); testKeepBeforeAfter(builder, NothingDoingTest1.class, NothingDoingTest2.class); } @Test public void keepBeforeAfterTwoParallelClasses() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); builder.useOnePool(8).parallelClasses(2).parallelMethods(2); assertFalse(builder.isOptimized()); JUnitCore core = new JUnitCore(); NothingDoingTest1.METHODS.clear(); Class<?>[] classes = {NothingDoingTest1.class, NothingDoingTest2.class, NothingDoingTest3.class}; Result result = core.run(builder.buildComputer(), classes); assertTrue(result.wasSuccessful()); ArrayList<String> methods = new ArrayList<>(NothingDoingTest1.METHODS); assertThat(methods.size(), is(12)); assertThat(methods.subList(9, 12), is(not(Arrays.asList("deinit", "deinit", "deinit")))); } @Test public void notThreadSafeTest() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) .useOnePool(6) .optimize(true) .parallelClasses(3) .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); Result result = new JUnitCore().run(computer, NotThreadSafeTest1.class, NotThreadSafeTest2.class); assertTrue(result.wasSuccessful()); assertThat(result.getRunCount(), is(2)); assertNotNull(NotThreadSafeTest1.t); assertNotNull(NotThreadSafeTest2.t); assertSame(NotThreadSafeTest1.t, NotThreadSafeTest2.t); assertThat(computer.getNotParallelRunners().size(), is(2)); assertTrue(computer.getSuites().isEmpty()); assertTrue(computer.getClasses().isEmpty()); assertTrue(computer.getNestedClasses().isEmpty()); assertTrue(computer.getNestedSuites().isEmpty()); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(6)); } @Test public void mixedThreadSafety() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) .useOnePool(6) .optimize(true) .parallelClasses(3) .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); Result result = new JUnitCore().run(computer, NotThreadSafeTest1.class, NormalTest1.class); assertTrue(result.wasSuccessful()); assertThat(result.getRunCount(), is(2)); assertNotNull(NotThreadSafeTest1.t); assertNotNull(NormalTest1.t); assertThat(NormalTest1.t.getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); assertNotSame(NotThreadSafeTest1.t, NormalTest1.t); assertThat(computer.getNotParallelRunners().size(), is(1)); assertTrue(computer.getSuites().isEmpty()); assertThat(computer.getClasses().size(), is(1)); assertTrue(computer.getNestedClasses().isEmpty()); assertTrue(computer.getNestedSuites().isEmpty()); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(6)); } @Test public void notThreadSafeTestsInSuite() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER).useOnePool(5).parallelMethods(3); assertFalse(builder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); Result result = new JUnitCore().run(computer, NotThreadSafeTestSuite.class); assertTrue(result.wasSuccessful()); assertNotNull(NormalTest1.t); assertNotNull(NormalTest2.t); assertSame(NormalTest1.t, NormalTest2.t); assertThat(NormalTest1.t.getName(), is("maven-surefire-plugin@NotThreadSafe")); assertThat(NormalTest2.t.getName(), is("maven-surefire-plugin@NotThreadSafe")); assertThat(computer.getNotParallelRunners().size(), is(1)); assertTrue(computer.getSuites().isEmpty()); assertTrue(computer.getClasses().isEmpty()); assertTrue(computer.getNestedClasses().isEmpty()); assertTrue(computer.getNestedSuites().isEmpty()); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(5)); } @Test public void mixedThreadSafetyInSuite() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) .useOnePool(10) .optimize(true) .parallelSuites(2) .parallelClasses(3) .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); Result result = new JUnitCore().run(computer, MixedSuite.class); assertTrue(result.wasSuccessful()); assertThat(result.getRunCount(), is(2)); assertNotNull(NotThreadSafeTest1.t); assertNotNull(NormalTest1.t); assertThat(NormalTest1.t.getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); assertNotSame(NotThreadSafeTest1.t, NormalTest1.t); assertTrue(computer.getNotParallelRunners().isEmpty()); assertThat(computer.getSuites().size(), is(1)); assertTrue(computer.getClasses().isEmpty()); assertThat(computer.getNestedClasses().size(), is(1)); assertTrue(computer.getNestedSuites().isEmpty()); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(10)); } @Test public void inheritanceWithNotThreadSafe() { ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) .useOnePool(10) .optimize(true) .parallelSuites(2) .parallelClasses(3) .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); Result result = new JUnitCore().run(computer, OverMixedSuite.class); assertTrue(result.wasSuccessful()); assertThat(result.getRunCount(), is(2)); assertNotNull(NotThreadSafeTest3.t); assertNotNull(NormalTest1.t); assertThat(NormalTest1.t.getName(), is("maven-surefire-plugin@NotThreadSafe")); assertSame(NotThreadSafeTest3.t, NormalTest1.t); assertThat(computer.getNotParallelRunners().size(), is(1)); assertTrue(computer.getSuites().isEmpty()); assertTrue(computer.getClasses().isEmpty()); assertTrue(computer.getNestedClasses().isEmpty()); assertTrue(computer.getNestedSuites().isEmpty()); assertFalse(computer.isSplitPool()); assertThat(computer.getPoolCapacity(), is(10)); } @Test public void beforeAfterThreadChanges() throws InterruptedException { // try to GC dead Thread objects from previous tests for (int i = 0; i < 5; i++) { System.gc(); TimeUnit.MILLISECONDS.sleep(500L); } Collection<Thread> expectedThreads = jvmThreads(); ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); parallelComputerBuilder.parallelMethods(3); ParallelComputer computer = parallelComputerBuilder.buildComputer(); Result result = new JUnitCore().run(computer, TestWithBeforeAfter.class); assertTrue(result.wasSuccessful()); // try to GC dead Thread objects for (int i = 0; i < 5 && expectedThreads.size() != jvmThreads().size(); i++) { System.gc(); TimeUnit.MILLISECONDS.sleep(500L); } assertThat(jvmThreads(), is(expectedThreads)); } private static Collection<Thread> jvmThreads() { Thread[] t = new Thread[1000]; Thread.enumerate(t); ArrayList<Thread> appThreads = new ArrayList<>(t.length); Collections.addAll(appThreads, t); appThreads.removeAll(Collections.singleton((Thread) null)); Collections.sort(appThreads, new Comparator<Thread>() { @Override public int compare(Thread t1, Thread t2) { return (int) Math.signum(t1.getId() - t2.getId()); } }); return appThreads; } private static class ShutdownTest { Result run(final boolean useInterrupt) { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER) .useOnePool(8) .parallelSuites(2) .parallelClasses(3) .parallelMethods(3); assertFalse(parallelComputerBuilder.isOptimized()); final ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); shutdownTask = new Runnable() { @Override public void run() { Collection<Description> startedTests = computer.describeStopped(useInterrupt).getTriggeredTests(); assertThat(startedTests.size(), is(not(0))); } }; return new JUnitCore().run(computer, TestSuite.class, Class2.class, Class3.class); } } /** * */ public static class Class1 { static volatile int concurrentMethods = 0; static volatile int maxConcurrentMethods = 0; @Test public void test1() throws InterruptedException { synchronized (CLASS1BLOCK) { ++concurrentMethods; CLASS1BLOCK.wait(DELAY_MULTIPLIER * 500L); maxConcurrentMethods = Math.max(maxConcurrentMethods, concurrentMethods--); } } @Test public void test2() throws InterruptedException { test1(); Runnable shutdownTask = ParallelComputerBuilderTest.shutdownTask; if (shutdownTask != null) { beforeShutdown = true; shutdownTask.run(); } } } /** * */ public static class Class2 extends Class1 {} /** * */ public static class Class3 extends Class1 {} /** * */ public static class NothingDoingTest1 { private static final Collection<String> METHODS = new ConcurrentLinkedQueue<>(); @BeforeClass public static void init() { METHODS.add("init"); } @AfterClass public static void deinit() { METHODS.add("deinit"); } @Test public void a() throws InterruptedException { Thread.sleep(5); METHODS.add(getClass().getName() + "#a()"); } @Test public void b() throws InterruptedException { Thread.sleep(5); METHODS.add(getClass().getName() + "#b()"); } } /** * */ public static class NothingDoingTest2 extends NothingDoingTest1 {} /** * */ public static class NothingDoingTest3 extends NothingDoingTest1 {} /** * */ @RunWith(Suite.class) @Suite.SuiteClasses({NothingDoingTest1.class, NothingDoingTest2.class}) public static class NothingDoingSuite {} /** * */ @RunWith(Suite.class) @Suite.SuiteClasses({Class2.class, Class1.class}) public static class TestSuite {} /** * */ public static class Test2 { @Test public void test() {} } /** * */ @RunWith(ReportOneTestAtRuntimeRunner.class) public static class TestWithoutPrecalculatedChildren {} /** * */ public static class ReportOneTestAtRuntimeRunner extends ParentRunner { private final Class<?> testClass; private final Description suiteDescription; private final Description myTestMethodDescr; @SuppressWarnings("unchecked") public ReportOneTestAtRuntimeRunner(Class<?> testClass) throws InitializationError { super(Object.class); this.testClass = testClass; suiteDescription = Description.createSuiteDescription(testClass); myTestMethodDescr = Description.createTestDescription(testClass, "my_test"); // suiteDescription.addChild(myTestMethodDescr); // let it be not known at start time } protected List getChildren() { throw new UnsupportedOperationException("workflow from ParentRunner not supported"); } protected Description describeChild(Object child) { throw new UnsupportedOperationException("workflow from ParentRunner not supported"); } protected void runChild(Object child, RunNotifier notifier) { throw new UnsupportedOperationException("workflow from ParentRunner not supported"); } public Description getDescription() { return suiteDescription; } public void run(RunNotifier notifier) { notifier.fireTestStarted(myTestMethodDescr); notifier.fireTestFinished(Description.createTestDescription(testClass, "my_test")); } } /** * */ @NotThreadSafe public static class NotThreadSafeTest1 { static volatile Thread t; @BeforeClass public static void beforeSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass public static void afterSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @Test public void test() { t = Thread.currentThread(); assertThat(t.getName(), is("maven-surefire-plugin@NotThreadSafe")); } } /** * */ @NotThreadSafe public static class NotThreadSafeTest2 { static volatile Thread t; @BeforeClass public static void beforeSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass public static void afterSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @Test public void test() { t = Thread.currentThread(); assertThat(t.getName(), is("maven-surefire-plugin@NotThreadSafe")); } } /** * */ @NotThreadSafe public static class NotThreadSafeTest3 { static volatile Thread t; @Test public void test() { t = Thread.currentThread(); assertThat(t.getName(), is("maven-surefire-plugin@NotThreadSafe")); } } /** * */ @RunWith(Suite.class) @Suite.SuiteClasses({NormalTest1.class, NormalTest2.class}) @NotThreadSafe public static class NotThreadSafeTestSuite { @BeforeClass public static void beforeSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass public static void afterSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } } /** * */ public static class NormalTest1 { static volatile Thread t; @Test public void test() { t = Thread.currentThread(); } } /** * */ public static class NormalTest2 { static volatile Thread t; @Test public void test() { t = Thread.currentThread(); } } /** * */ @RunWith(Suite.class) @Suite.SuiteClasses({NotThreadSafeTest1.class, NormalTest1.class}) public static class MixedSuite { @BeforeClass public static void beforeSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass public static void afterSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } } /** * */ @RunWith(Suite.class) @Suite.SuiteClasses({NotThreadSafeTest3.class, NormalTest1.class}) @NotThreadSafe public static class OverMixedSuite { @BeforeClass public static void beforeSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass public static void afterSuite() { assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } } /** * */ public static class TestWithBeforeAfter { @BeforeClass public static void beforeClass() throws InterruptedException { System.out.println(new Date() + " BEG: beforeClass"); sleepSeconds(1); System.out.println(new Date() + " END: beforeClass"); } @Before public void before() throws InterruptedException { System.out.println(new Date() + " BEG: before"); sleepSeconds(1); System.out.println(new Date() + " END: before"); } @Test public void test() throws InterruptedException { System.out.println(new Date() + " BEG: test"); sleepSeconds(1); System.out.println(new Date() + " END: test"); } @After public void after() throws InterruptedException { System.out.println(new Date() + " BEG: after"); sleepSeconds(1); System.out.println(new Date() + " END: after"); } @AfterClass public static void afterClass() throws InterruptedException { System.out.println(new Date() + " BEG: afterClass"); sleepSeconds(1); System.out.println(new Date() + " END: afterClass"); } } private static long systemMillis() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } private static void sleepSeconds(int seconds) throws InterruptedException { TimeUnit.SECONDS.sleep(seconds); } }
googleapis/google-cloud-java
36,821
java-discoveryengine/proto-google-cloud-discoveryengine-v1/src/main/java/com/google/cloud/discoveryengine/v1/PurgeUserEventsMetadata.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/purge_config.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1; /** * * * <pre> * Metadata related to the progress of the PurgeUserEvents operation. * This will be returned by the google.longrunning.Operation.metadata field. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.PurgeUserEventsMetadata} */ public final class PurgeUserEventsMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) PurgeUserEventsMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use PurgeUserEventsMetadata.newBuilder() to construct. private PurgeUserEventsMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PurgeUserEventsMetadata() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new PurgeUserEventsMetadata(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.PurgeConfigProto .internal_static_google_cloud_discoveryengine_v1_PurgeUserEventsMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.PurgeConfigProto .internal_static_google_cloud_discoveryengine_v1_PurgeUserEventsMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.class, com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.Builder.class); } private int bitField0_; public static final int CREATE_TIME_FIELD_NUMBER = 1; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } public static final int UPDATE_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp updateTime_; /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return Whether the updateTime field is set. */ @java.lang.Override public boolean hasUpdateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return The updateTime. */ @java.lang.Override public com.google.protobuf.Timestamp getUpdateTime() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } public static final int SUCCESS_COUNT_FIELD_NUMBER = 3; private long successCount_ = 0L; /** * * * <pre> * Count of entries that were deleted successfully. * </pre> * * <code>int64 success_count = 3;</code> * * @return The successCount. */ @java.lang.Override public long getSuccessCount() { return successCount_; } public static final int FAILURE_COUNT_FIELD_NUMBER = 4; private long failureCount_ = 0L; /** * * * <pre> * Count of entries that encountered errors while processing. * </pre> * * <code>int64 failure_count = 4;</code> * * @return The failureCount. */ @java.lang.Override public long getFailureCount() { return failureCount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateTime()); } if (successCount_ != 0L) { output.writeInt64(3, successCount_); } if (failureCount_ != 0L) { output.writeInt64(4, failureCount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateTime()); } if (successCount_ != 0L) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(3, successCount_); } if (failureCount_ != 0L) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(4, failureCount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata other = (com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) obj; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasUpdateTime() != other.hasUpdateTime()) return false; if (hasUpdateTime()) { if (!getUpdateTime().equals(other.getUpdateTime())) return false; } if (getSuccessCount() != other.getSuccessCount()) return false; if (getFailureCount() != other.getFailureCount()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasUpdateTime()) { hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getUpdateTime().hashCode(); } hash = (37 * hash) + SUCCESS_COUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSuccessCount()); hash = (37 * hash) + FAILURE_COUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getFailureCount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata 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.PurgeUserEventsMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Metadata related to the progress of the PurgeUserEvents operation. * This will be returned by the google.longrunning.Operation.metadata field. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.PurgeUserEventsMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.PurgeConfigProto .internal_static_google_cloud_discoveryengine_v1_PurgeUserEventsMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.PurgeConfigProto .internal_static_google_cloud_discoveryengine_v1_PurgeUserEventsMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.class, com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCreateTimeFieldBuilder(); getUpdateTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } successCount_ = 0L; failureCount_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.discoveryengine.v1.PurgeConfigProto .internal_static_google_cloud_discoveryengine_v1_PurgeUserEventsMetadata_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata build() { com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata buildPartial() { com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata result = new com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateTime_ = updateTimeBuilder_ == null ? updateTime_ : updateTimeBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.successCount_ = successCount_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.failureCount_ = failureCount_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) { return mergeFrom((com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata other) { if (other == com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata.getDefaultInstance()) return this; if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasUpdateTime()) { mergeUpdateTime(other.getUpdateTime()); } if (other.getSuccessCount() != 0L) { setSuccessCount(other.getSuccessCount()); } if (other.getFailureCount() != 0L) { setFailureCount(other.getFailureCount()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 24: { successCount_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { failureCount_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; } else { createTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && createTime_ != null && createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCreateTimeBuilder().mergeFrom(value); } else { createTime_ = value; } } else { createTimeBuilder_.mergeFrom(value); } if (createTime_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder clearCreateTime() { bitField0_ = (bitField0_ & ~0x00000001); createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { bitField0_ |= 0x00000001; onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.protobuf.Timestamp updateTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> updateTimeBuilder_; /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return Whether the updateTime field is set. */ public boolean hasUpdateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return The updateTime. */ public com.google.protobuf.Timestamp getUpdateTime() { if (updateTimeBuilder_ == null) { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } else { return updateTimeBuilder_.getMessage(); } } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateTime_ = value; } else { updateTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (updateTimeBuilder_ == null) { updateTime_ = builderForValue.build(); } else { updateTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateTime_ != null && updateTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getUpdateTimeBuilder().mergeFrom(value); } else { updateTime_ = value; } } else { updateTimeBuilder_.mergeFrom(value); } if (updateTime_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder clearUpdateTime() { bitField0_ = (bitField0_ & ~0x00000002); updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { if (updateTimeBuilder_ != null) { return updateTimeBuilder_.getMessageOrBuilder(); } else { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getUpdateTimeFieldBuilder() { if (updateTimeBuilder_ == null) { updateTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getUpdateTime(), getParentForChildren(), isClean()); updateTime_ = null; } return updateTimeBuilder_; } private long successCount_; /** * * * <pre> * Count of entries that were deleted successfully. * </pre> * * <code>int64 success_count = 3;</code> * * @return The successCount. */ @java.lang.Override public long getSuccessCount() { return successCount_; } /** * * * <pre> * Count of entries that were deleted successfully. * </pre> * * <code>int64 success_count = 3;</code> * * @param value The successCount to set. * @return This builder for chaining. */ public Builder setSuccessCount(long value) { successCount_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Count of entries that were deleted successfully. * </pre> * * <code>int64 success_count = 3;</code> * * @return This builder for chaining. */ public Builder clearSuccessCount() { bitField0_ = (bitField0_ & ~0x00000004); successCount_ = 0L; onChanged(); return this; } private long failureCount_; /** * * * <pre> * Count of entries that encountered errors while processing. * </pre> * * <code>int64 failure_count = 4;</code> * * @return The failureCount. */ @java.lang.Override public long getFailureCount() { return failureCount_; } /** * * * <pre> * Count of entries that encountered errors while processing. * </pre> * * <code>int64 failure_count = 4;</code> * * @param value The failureCount to set. * @return This builder for chaining. */ public Builder setFailureCount(long value) { failureCount_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Count of entries that encountered errors while processing. * </pre> * * <code>int64 failure_count = 4;</code> * * @return This builder for chaining. */ public Builder clearFailureCount() { bitField0_ = (bitField0_ & ~0x00000008); failureCount_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1.PurgeUserEventsMetadata) private static final com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata(); } public static com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PurgeUserEventsMetadata> PARSER = new com.google.protobuf.AbstractParser<PurgeUserEventsMetadata>() { @java.lang.Override public PurgeUserEventsMetadata 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<PurgeUserEventsMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PurgeUserEventsMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1.PurgeUserEventsMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/felix-dev
35,873
ipojo/runtime/core-it/ipojo-core-service-dependency-optional-test/src/test/java/org/apache/felix/ipojo/runtime/core/test/dependencies/optional/TestOptionalDependencies.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.ipojo.runtime.core.test.dependencies.optional; import org.apache.felix.ipojo.ComponentInstance; import org.apache.felix.ipojo.architecture.Architecture; import org.apache.felix.ipojo.architecture.InstanceDescription; import org.apache.felix.ipojo.runtime.core.test.dependencies.Common; import org.apache.felix.ipojo.runtime.core.test.services.CheckService; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.osgi.framework.ServiceReference; import java.util.Properties; import static org.junit.Assert.*; public class TestOptionalDependencies extends Common { ComponentInstance instance1, instance2, instance3, instance4, instance5, instance6, instance7; ComponentInstance fooProvider; @Before public void setUp() { try { Properties prov = new Properties(); prov.put("instance.name","FooProvider"); fooProvider = ipojoHelper.getFactory("FooProviderType-1").createComponentInstance(prov); fooProvider.stop(); Properties i1 = new Properties(); i1.put("instance.name","Simple"); instance1 = ipojoHelper.getFactory("SimpleOptionalCheckServiceProvider").createComponentInstance(i1); Properties i2 = new Properties(); i2.put("instance.name","Void"); instance2 = ipojoHelper.getFactory("VoidOptionalCheckServiceProvider").createComponentInstance(i2); Properties i3 = new Properties(); i3.put("instance.name","Object"); instance3 = ipojoHelper.getFactory("ObjectOptionalCheckServiceProvider").createComponentInstance(i3); Properties i4 = new Properties(); i4.put("instance.name","Ref"); instance4 = ipojoHelper.getFactory("RefOptionalCheckServiceProvider").createComponentInstance(i4); Properties i5 = new Properties(); i5.put("instance.name","Both"); instance5 = ipojoHelper.getFactory("BothOptionalCheckServiceProvider").createComponentInstance(i5); Properties i6 = new Properties(); i6.put("instance.name","Map"); instance6 = ipojoHelper.getFactory("MapOptionalCheckServiceProvider").createComponentInstance(i6); Properties i7 = new Properties(); i7.put("instance.name","Dictionary"); instance7 = ipojoHelper.getFactory("DictOptionalCheckServiceProvider").createComponentInstance(i7); } catch(Exception e) { fail(e.getMessage()); } } @After public void tearDown() { instance1.dispose(); instance2.dispose(); instance3.dispose(); instance4.dispose(); instance5.dispose(); instance6.dispose(); instance7.dispose(); fooProvider.dispose(); instance1 = null; instance2 = null; instance3 = null; instance4 = null; instance5 = null; instance6 = null; instance7 = null; fooProvider = null; } @Test public void testSimple() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance1.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance1.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation - 1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation - 1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation - 1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation - 1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation - 1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation - 1", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation - 1", ((Integer)props.get("refU")).intValue(), 0); assertNull("Check FS invocation (object) - 1 ("+props.get("object")+")", props.get("object")); assertEquals("Check FS invocation (int) - 1", ((Integer)props.get("int")).intValue(), 0); assertEquals("Check FS invocation (long) - 1", ((Long)props.get("long")).longValue(), 0); assertEquals("Check FS invocation (double) - 1", ((Double)props.get("double")).doubleValue(), 0.0, 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation - 2", ((Boolean)props.get("result")).booleanValue()); // True, a provider is there assertEquals("check void bind invocation - 2", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation - 2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation - 2", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation - 2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation - 2", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation - 2", ((Integer)props.get("refU")).intValue(), 0); assertNotNull("Check FS invocation (object) - 2", props.get("object")); assertEquals("Check FS invocation (int) - 2", ((Integer)props.get("int")).intValue(), 1); assertEquals("Check FS invocation (long) - 2", ((Long)props.get("long")).longValue(), 1); assertEquals("Check FS invocation (double) - 2", ((Double)props.get("double")).doubleValue(), 1.0, 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } @Test public void testVoid() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance2.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation - 1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation - 1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation - 1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation - 1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation - 1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation - 1", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation - 1", ((Integer)props.get("refU")).intValue(), 0); assertNull("Check FS invocation (object) - 1", props.get("object")); assertEquals("Check FS invocation (int) - 1", ((Integer)props.get("int")).intValue(), 0); assertEquals("Check FS invocation (long) - 1", ((Long)props.get("long")).longValue(), 0); assertEquals("Check FS invocation (double) - 1", ((Double)props.get("double")).doubleValue(), 0.0, 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation -2", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -2", ((Integer)props.get("voidB")).intValue(), 1); assertEquals("check void unbind callback invocation -2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -2", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -2", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -2", ((Integer)props.get("refU")).intValue(), 0); assertNotNull("Check FS invocation (object) - 2", props.get("object")); assertEquals("Check FS invocation (int) - 2", ((Integer)props.get("int")).intValue(), 1); assertEquals("Check FS invocation (long) - 2", ((Long)props.get("long")).longValue(), 1); assertEquals("Check FS invocation (double) - 2", ((Double)props.get("double")).doubleValue(), 1.0, 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -3", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -3", ((Integer)props.get("voidB")).intValue(), 1); assertEquals("check void unbind callback invocation -3 ("+((Integer)props.get("voidU")) + ")", ((Integer)props.get("voidU")).intValue(), 1); assertEquals("check object bind callback invocation -3", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -3", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -3", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -3", ((Integer)props.get("refU")).intValue(), 0); assertNull("Check FS invocation (object) - 3", props.get("object")); assertEquals("Check FS invocation (int) - 3", ((Integer)props.get("int")).intValue(), 0); assertEquals("Check FS invocation (long) - 3", ((Long)props.get("long")).longValue(), 0); assertEquals("Check FS invocation (double) - 3", ((Double)props.get("double")).doubleValue(), 0.0, 0); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } @Test public void testObject() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance3.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance3.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation -1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -1", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -1", ((Integer)props.get("refU")).intValue(), 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation -2", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -2", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -2 (" + ((Integer)props.get("objectB")).intValue() + ")", ((Integer)props.get("objectB")).intValue(), 1); assertEquals("check object unbind callback invocation -2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -2", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -2", ((Integer)props.get("refU")).intValue(), 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -3", ((Boolean)props.get("result")).booleanValue()); // Nullable object. assertEquals("check void bind invocation -3", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -3", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -3", ((Integer)props.get("objectB")).intValue(), 1); assertEquals("check object unbind callback invocation -3", ((Integer)props.get("objectU")).intValue(), 1); assertEquals("check ref bind callback invocation -3", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -3", ((Integer)props.get("refU")).intValue(), 0); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } @Test public void testRef() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance4.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance4.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation -1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -1", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -1", ((Integer)props.get("refU")).intValue(), 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation -2", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -2", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -2", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -2", ((Integer)props.get("refB")).intValue(), 1); assertEquals("check ref unbind callback invocation -2", ((Integer)props.get("refU")).intValue(), 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -3", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -3", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -3", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -3", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -3", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -3", ((Integer)props.get("refB")).intValue(), 1); assertEquals("check ref unbind callback invocation -3", ((Integer)props.get("refU")).intValue(), 1); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } @Test public void testBoth() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance5.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance5.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation -1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check both bind callback invocation -1", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -1", ((Integer)props.get("bothU")).intValue(), 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation -2", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -2", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -2", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -2", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -2", ((Integer)props.get("refU")).intValue(), 0); assertEquals("check both bind callback invocation -2", ((Integer)props.get("bothB")).intValue(), 1); assertEquals("check both unbind callback invocation -2", ((Integer)props.get("bothU")).intValue(), 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -3", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -3", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -3", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -3", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -3", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -3", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -3", ((Integer)props.get("refU")).intValue(), 0); assertEquals("check both bind callback invocation -3", ((Integer)props.get("bothB")).intValue(), 1); assertEquals("check both unbind callback invocation -3", ((Integer)props.get("bothU")).intValue(), 1); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } @Test public void testMap() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance6.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance6.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation -1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check both bind callback invocation -1", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -1", ((Integer)props.get("bothU")).intValue(), 0); assertEquals("check map bind callback invocation -1", ((Integer)props.get("mapB")).intValue(), 0); assertEquals("check map unbind callback invocation -1", ((Integer)props.get("mapU")).intValue(), 0); assertEquals("check dict bind callback invocation -1", ((Integer)props.get("dictB")).intValue(), 0); assertEquals("check dict unbind callback invocation -1", ((Integer)props.get("dictU")).intValue(), 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation -2", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -2", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -2", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -2", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -2", ((Integer)props.get("refU")).intValue(), 0); assertEquals("check both bind callback invocation -2", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -2", ((Integer)props.get("bothU")).intValue(), 0); assertEquals("check map bind callback invocation -2", ((Integer)props.get("mapB")).intValue(), 1); assertEquals("check map unbind callback invocation -2", ((Integer)props.get("mapU")).intValue(), 0); assertEquals("check dict bind callback invocation -2", ((Integer)props.get("dictB")).intValue(), 0); assertEquals("check dict unbind callback invocation -2", ((Integer)props.get("dictU")).intValue(), 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -3", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -3", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -3", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -3", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -3", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -3", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -3", ((Integer)props.get("refU")).intValue(), 0); assertEquals("check both bind callback invocation -3", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -3", ((Integer)props.get("bothU")).intValue(), 0); assertEquals("check map bind callback invocation -3", ((Integer)props.get("mapB")).intValue(), 1); assertEquals("check map unbind callback invocation -3", ((Integer)props.get("mapU")).intValue(), 1); assertEquals("check dict bind callback invocation -3", ((Integer)props.get("dictB")).intValue(), 0); assertEquals("check dict unbind callback invocation -3", ((Integer)props.get("dictU")).intValue(), 0); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } @Test public void testDict() { ServiceReference arch_ref = ipojoHelper.getServiceReferenceByName(Architecture.class.getName(), instance7.getInstanceName()); assertNotNull("Check architecture availability", arch_ref); InstanceDescription id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 1", id.getState() == ComponentInstance.VALID); ServiceReference cs_ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance7.getInstanceName()); assertNotNull("Check CheckService availability", cs_ref); CheckService cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); Properties props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -1", ((Boolean)props.get("result")).booleanValue()); // False is returned (nullable) assertEquals("check void bind invocation -1", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -1", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -1", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -1", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check both bind callback invocation -1", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -1", ((Integer)props.get("bothU")).intValue(), 0); assertEquals("check map bind callback invocation -1", ((Integer)props.get("mapB")).intValue(), 0); assertEquals("check map unbind callback invocation -1", ((Integer)props.get("mapU")).intValue(), 0); assertEquals("check dict bind callback invocation -1", ((Integer)props.get("dictB")).intValue(), 0); assertEquals("check dict unbind callback invocation -1", ((Integer)props.get("dictU")).intValue(), 0); fooProvider.start(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 2", id.getState() == ComponentInstance.VALID); assertNotNull("Check CheckService availability", cs_ref); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertTrue("check CheckService invocation -2", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -2", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -2", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -2", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -2", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -2", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -2", ((Integer)props.get("refU")).intValue(), 0); assertEquals("check both bind callback invocation -2", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -2", ((Integer)props.get("bothU")).intValue(), 0); assertEquals("check map bind callback invocation -2", ((Integer)props.get("mapB")).intValue(), 0); assertEquals("check map unbind callback invocation -2", ((Integer)props.get("mapU")).intValue(), 0); assertEquals("check dict bind callback invocation -2", ((Integer)props.get("dictB")).intValue(), 1); assertEquals("check dict unbind callback invocation -2", ((Integer)props.get("dictU")).intValue(), 0); fooProvider.stop(); id = ((Architecture) osgiHelper.getRawServiceObject(arch_ref)).getInstanceDescription(); assertTrue("Check instance validity - 3", id.getState() == ComponentInstance.VALID); cs = (CheckService) osgiHelper.getRawServiceObject(cs_ref); props = cs.getProps(); //Check properties assertFalse("check CheckService invocation -3", ((Boolean)props.get("result")).booleanValue()); assertEquals("check void bind invocation -3", ((Integer)props.get("voidB")).intValue(), 0); assertEquals("check void unbind callback invocation -3", ((Integer)props.get("voidU")).intValue(), 0); assertEquals("check object bind callback invocation -3", ((Integer)props.get("objectB")).intValue(), 0); assertEquals("check object unbind callback invocation -3", ((Integer)props.get("objectU")).intValue(), 0); assertEquals("check ref bind callback invocation -3", ((Integer)props.get("refB")).intValue(), 0); assertEquals("check ref unbind callback invocation -3", ((Integer)props.get("refU")).intValue(), 0); assertEquals("check both bind callback invocation -3", ((Integer)props.get("bothB")).intValue(), 0); assertEquals("check both unbind callback invocation -3", ((Integer)props.get("bothU")).intValue(), 0); assertEquals("check map bind callback invocation -3", ((Integer)props.get("mapB")).intValue(), 0); assertEquals("check map unbind callback invocation -3", ((Integer)props.get("mapU")).intValue(), 0); assertEquals("check dict bind callback invocation -3", ((Integer)props.get("dictB")).intValue(), 1); assertEquals("check dict unbind callback invocation -3", ((Integer)props.get("dictU")).intValue(), 1); id = null; cs = null; getContext().ungetService(arch_ref); getContext().ungetService(cs_ref); } }
apache/incubator-retired-wave
36,881
wave/src/main/java/org/waveprotocol/wave/model/document/operation/NindoAutomaton.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.waveprotocol.wave.model.document.operation; import org.waveprotocol.wave.model.document.indexed.IndexedDocument; import org.waveprotocol.wave.model.document.indexed.NodeType; import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.OperationIllFormed; import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.OperationInvalid; import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.SchemaViolation; import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.ValidationResult; import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.ViolationCollector; import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema; import org.waveprotocol.wave.model.document.util.DocHelper; import org.waveprotocol.wave.model.document.util.Point; import org.waveprotocol.wave.model.util.Preconditions; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * A state machine that can be used to accept or generate valid or invalid document * operations. * * The basic usage model is as follows: An automaton is parameterized by a * document and a set of constraints based on an XML schema, and will * accept/generate all valid operations for that document and those constraints. * * Every possible mutation component (such as "elementStart(...)") corresponds * to a potential transition of the automaton. The checkXXX methods * (such as checkElementStart(...)) determine whether a given transition exists * and is valid, or whether it is invalid, or ill-formed. The doXXX methods * will perform the transition. Ill-formed transitions must not be performed. * Invalid transitions are permitted, but after performing an invalid transition, * the validity of any further mutation components is not clearly specified. * * The checkFinish() method determines whether ending an operation is acceptable, * or whether any opening components are missing the corresponding closing * component. * * The checkXXX methods accept a ViolationsAccu object where they will record * details about any violations. If a proposed transition is invalid for more * than one reason, the checkXXX method may detect only one (or any subset) of * the reasons and record only those violations. The ViolationsAccu parameter * may also be null, in which case details about the violations will not be * recorded. * * To validate an operation, the automaton needs to be driven according to * the mutation components in that operation. DocumentOperationValidator does * this. * * To generate a random operation, the automaton needs to be driven based on * a random document mutation component generator. * RandomDocumentMutationGenerator does this. * * @author ohler@google.com (Christian Ohler) */ // TODO(ohler/danilatos): Incorporate initial required elements schema checks public final class NindoAutomaton<N, E extends N, T extends N> { /** * An object containing information about one individual reason why an * operation is not valid, e.g. "skip past end" or "deletion inside insertion". */ public abstract static class Violation { private final String description; private final int originalDocumentPos; private final int resultingDocumentPos; Violation(String description, int originalPos, int resultingPos) { this.description = description; this.originalDocumentPos = originalPos; this.resultingDocumentPos = resultingPos; } protected abstract ValidationResult validationResult(); /** * @return a developer-readable description of the violation */ public String description() { return description + " at original document position " + originalDocumentPos + " / resulting document position " + resultingDocumentPos; } } // http://www.w3.org/TR/xml/#NT-NameStartChar private static boolean isXmlNameStartChar(char c) { // NameStartChar ::= ":" | [A-Z] | "_" | [a-z] return c == ':' || ('A' <= c && c <= 'Z') || c == '_' | ('a' <= c && c <= 'z') // | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] || (0xC0 <= c && c <= 0xD6) || (0xD8 <= c && c <= 0xF6) || (0xF8 <= c && c <= 0x2FF) // | [#x370-#x37D] | [#x37F-#x1FFF] || (0x370 <= c && c <= 0x37D) || (0x37F <= c && c <= 0x1FFF) // | [#x200C-#x200D] | [#x2070-#x218F] || (0x200C <= c && c <= 0x200D) || (0x2070 <= c && c <= 0x218F) // | [#x2C00-#x2FEF] | [#x3001-#xD7FF] || (0x2C00 <= c && c <= 0x2FEF) || (0x3001 <= c && c <= 0xD7FF) // | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] || (0xF900 <= c && c <= 0xFDCF) || (0xFDF0 <= c && c <= 0xFFFD) // | [#x10000-#xEFFFF] // Ha, ha. || (0x10000 <= c && c <= 0xEFFFF); } private static boolean isXmlNameChar(char c) { // NameChar ::= NameStartChar | "-" | "." | [0-9] return isXmlNameStartChar(c) || c == '-' || c == '.' || ('0' <= c && c <= '9') // | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] || c == 0xB7 || (0x0300 <= c && c <= 0x036F) || (0x203F <= c && c <= 0x2040); } private static boolean isXmlName(String s) { // Name ::= NameStartChar (NameChar)* assert s != null; if (s.length() == 0) { return false; } if (!isXmlNameStartChar(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { if (!isXmlNameChar(s.charAt(i))) { return false; } } return true; } private ValidationResult addViolation(ViolationCollector a, OperationIllFormed v) { if (a != null) { a.add(v); } return v.validationResult(); } private ValidationResult addViolation(ViolationCollector a, OperationInvalid v) { if (a != null) { a.add(v); } return v.validationResult(); } private ValidationResult addViolation(ViolationCollector a, SchemaViolation v) { if (a != null) { a.add(v); } return v.validationResult(); } private OperationIllFormed illFormedOperation(String description) { return new OperationIllFormed(description, effectivePos(), resultingPos); } private OperationInvalid invalidOperation(String description) { return new OperationInvalid(description, effectivePos(), resultingPos); } private SchemaViolation schemaViolation(String description) { return new SchemaViolation(description, effectivePos(), resultingPos); } private ValidationResult valid() { return ValidationResult.VALID; } private ValidationResult mismatchedElementStart(ViolationCollector v) { return addViolation(v, illFormedOperation("elementStart with no elementEnd")); } private ValidationResult mismatchedDeleteElementStart(ViolationCollector v) { return addViolation(v, illFormedOperation("deleteElementStart with no deleteElementEnd")); } private ValidationResult mismatchedElementEnd(ViolationCollector v) { return addViolation(v, illFormedOperation("elementEnd with no elementStart")); } private ValidationResult mismatchedDeleteElementEnd(ViolationCollector v) { return addViolation(v, illFormedOperation("deleteElementEnd with no deleteElementStart")); } private ValidationResult mismatchedStartAnnotation(ViolationCollector v, String key) { return addViolation(v, illFormedOperation("startAnnotation of key " + key + " with no endAnnotation")); } private ValidationResult mismatchedEndAnnotation(ViolationCollector v, String key) { return addViolation(v, illFormedOperation("endAnnotation of key " + key + " with no startAnnotation")); } private ValidationResult skipDistanceNotPositive(ViolationCollector v) { return addViolation(v, illFormedOperation("skip distance not positive")); } private ValidationResult skipInsideInsertOrDelete(ViolationCollector v) { return addViolation(v, illFormedOperation("skip inside insert or delete")); } private ValidationResult attributeChangeInsideInsertOrDelete(ViolationCollector v) { return addViolation(v, illFormedOperation("attribute change inside insert or delete")); } private ValidationResult skipPastEnd(ViolationCollector v) { return addViolation(v, invalidOperation("skip past end of document")); } private ValidationResult nullCharacters(ViolationCollector v) { return addViolation(v, illFormedOperation("characters is null")); } private ValidationResult emptyCharacters(ViolationCollector v) { return addViolation(v, illFormedOperation("characters is empty")); } private ValidationResult insertInsideDelete(ViolationCollector v) { return addViolation(v, illFormedOperation("insertion inside deletion")); } private ValidationResult deleteInsideInsert(ViolationCollector v) { return addViolation(v, illFormedOperation("deletion inside insertion")); } private ValidationResult nullTag(ViolationCollector v) { return addViolation(v, illFormedOperation("element type is null")); } private ValidationResult elementTypeNotXmlName(ViolationCollector v, String name) { return addViolation(v, illFormedOperation("element type is not an XML name: \"" + name + "\"")); } private ValidationResult nullAttributes(ViolationCollector v) { return addViolation(v, illFormedOperation("attributes is null")); } private ValidationResult nullAttributeKey(ViolationCollector v) { return addViolation(v, illFormedOperation("attribute key is null")); } private ValidationResult attributeKeyNotXmlName(ViolationCollector v, String name) { return addViolation(v, illFormedOperation("attribute key is not an XML name: \"" + name + "\"")); } private ValidationResult nullAttributeValue(ViolationCollector v) { return addViolation(v, illFormedOperation("attribute value is null")); } private ValidationResult nullAnnotationKey(ViolationCollector v) { return addViolation(v, illFormedOperation("annotation key is null")); } private ValidationResult textNotAllowedInElement(ViolationCollector v, String tag) { return addViolation(v, schemaViolation("element type " + tag + " does not allow text content")); } private ValidationResult tooLong(ViolationCollector v) { return addViolation(v, invalidOperation("intermediate or final document too long")); } private ValidationResult deleteLengthNotPositive(ViolationCollector v) { return addViolation(v, illFormedOperation("delete length not positive")); } private ValidationResult cannotDeleteSoManyCharacters(ViolationCollector v, int attempted, int available) { return addViolation(v, invalidOperation("cannot delete " + attempted + " characters," + " only " + available + " available")); } private ValidationResult invalidAttribute(ViolationCollector v, String type, String attr) { return addViolation(v, schemaViolation("type " + type + " does not permit attribute " + attr)); } private ValidationResult invalidAttribute(ViolationCollector v, String type, String attr, String value) { return addViolation(v, schemaViolation("type " + type + " does not permit attribute " + attr + " with value " + value)); } private ValidationResult typeInvalidRoot(ViolationCollector v) { return addViolation(v, schemaViolation("type not permitted as root element")); } private ValidationResult invalidChild(ViolationCollector v, String parentTag, String childTag) { return addViolation(v, schemaViolation("element type " + parentTag + " does not permit subelement type " + childTag)); } private ValidationResult noElementStartToDelete(ViolationCollector v) { return addViolation(v, invalidOperation("no element start to delete here")); } private ValidationResult noElementEndToDelete(ViolationCollector v) { return addViolation(v, invalidOperation("no element end to delete here")); } private ValidationResult noElementStartToChangeAttributes(ViolationCollector v) { return addViolation(v, invalidOperation("no element start to change attributes here")); } private final DocumentSchema schemaConstraints; private enum DocSymbol { CHARACTER, OPEN, CLOSE, END } private abstract static class StackEntry { abstract ValidationResult notClosed(NindoAutomaton<?, ?, ?> a, ViolationCollector v); InsertElement asInsertElement() { return null; } DeleteElement asDeleteElement() { return null; } } private static class InsertElement extends StackEntry { final String tag; InsertElement(String tag) { this.tag = tag; } static InsertElement getInstance(String tag) { return new InsertElement(tag); } @Override ValidationResult notClosed(NindoAutomaton<?, ?, ?> a, ViolationCollector v) { return a.mismatchedElementStart(v); } @Override InsertElement asInsertElement() { return this; } } private static class DeleteElement extends StackEntry { static DeleteElement instance = new DeleteElement(); static DeleteElement getInstance() { return instance; } @Override ValidationResult notClosed(NindoAutomaton<?, ?, ?> a, ViolationCollector v) { return a.mismatchedDeleteElementStart(v); } @Override DeleteElement asDeleteElement() { return this; } } /** * If effectivePos is at an element start, return that element. * Else return null. */ private E elementStartingHere() { Preconditions.checkPositionIndex(effectivePos, doc.size()); if (!(effectivePos + 1 < doc.size())) { // effectivePos + 1 is the smallest possible index of the corresponding // elementEnd; if that's beyond the end of the document, effectivePosition // can't be an elementStart. return null; } // Criterion: the enclosing element of effectivePos is the // parent of the enclosing element of effectivePos + 1 // (if the enclosing element of effectivePos + 1 exists) (this // also covers the corner case of the enclosing element of // effectivePos being null). E elementHere = // can't create point for location 0 effectivePos == 0 ? doc.getDocumentElement() : Point.enclosingElement(doc, doc.locate(effectivePos)); E elementNext = Point.enclosingElement(doc, doc.locate(effectivePos + 1)); if (elementNext == null) { return null; } if (elementHere != doc.getParentElement(elementNext)) { return null; } else { return elementNext; } } /** * If effectivePos is at an element end, return that element. * Else return null. */ private E elementEndingNext() { Preconditions.checkPositionIndex(effectivePos, doc.size()); if (effectivePos == 0) { return null; } if (effectivePos == doc.size()) { return null; } if (effectivePos == doc.size() - 1) { // Root element ends here. E root = doc.getDocumentElement(); assert root != null; return root; } Point<N> point = doc.locate(effectivePos); // Criterion: the enclosing element of effectivePos + 1 is the // parent of the enclosing element of effectivePos // (if the enclosing element of effectivePos exists) (this // also covers the corner case of the enclosing element of // effectivePos being null). E elementHere = Point.enclosingElement(doc, doc.locate(effectivePos)); E elementNext = Point.enclosingElement(doc, doc.locate(effectivePos + 1)); if (elementHere == null) { return null; } if (doc.getParentElement(elementHere) != elementNext) { return null; } else { return elementHere; } } // depth = 0 means enclosing element, depth = 1 means its parent, etc. private static <N, E extends N, T extends N> E nthEnclosingElement(IndexedDocument<N, E, T> doc, int pos, int depth) { assert depth >= 0; E e = Point.enclosingElement(doc, doc.locate(pos)); for (int i = 0; i < depth; i++) { assert e != null; e = doc.getParentElement(e); } return e; } private static <N, E extends N, T extends N> int remainingCharactersInElement( IndexedDocument<N, E, T> doc, int pos) { if (pos >= doc.size()) { return 0; } Point<N> deletionPoint = doc.locate(pos); if (!deletionPoint.isInTextNode()) { return 0; } int offsetWithinNode = deletionPoint.getTextOffset(); N container = deletionPoint.getContainer(); assert doc.getNodeType(container) == NodeType.TEXT_NODE; int nodeLength = DocHelper.getItemSize(doc, container); int remainingChars = nodeLength - offsetWithinNode; assert remainingChars >= 0; while (true) { N next = doc.getNextSibling(container); if (next == null || doc.getNodeType(next) != NodeType.TEXT_NODE) { break; } remainingChars += DocHelper.getItemSize(doc, next); container = next; } return remainingChars; } private boolean tagAllowsText(String tag) { switch (schemaConstraints.permittedCharacters(tag)) { case ANY: return true; case BLIP_TEXT: return true; case NONE: return false; default: throw new AssertionError("unexpected return value from permittedCharacters"); } } private boolean elementAllowedAsRoot(String tag) { return schemaConstraints.permitsChild(null, tag); } private boolean elementAllowsAttribute(String tag, String attributeName) { return schemaConstraints.permitsAttribute(tag, attributeName); } private boolean elementAllowsAttribute(String tag, String attributeName, String attributeValue) { return schemaConstraints.permitsAttribute(tag, attributeName, attributeValue); } private boolean elementAllowsChild(String parentType, String childType) { return schemaConstraints.permitsChild(parentType, childType); } // current state private final IndexedDocument<N, E, T> doc; private int effectivePos = 0; private int resultingLength; // first item is bottom of stack, last is top private final ArrayList<StackEntry> stack = new ArrayList<StackEntry>(); private final Set<String> openAnnotationKeys = new HashSet<String>(); // more state to track for debugging private int resultingPos = 0; /** * Creates an automaton that corresponds to the set of all possible operations * on the given document under the given schema constraints. */ public NindoAutomaton(DocumentSchema schemaConstraints, IndexedDocument<N, E, T> doc) { this.schemaConstraints = schemaConstraints; this.doc = doc; this.resultingLength = doc.size(); } // current state primitive readers private int resultingLength() { return resultingLength; } // note that effectivePos() is not, in general, <= resultingLength(). The // values are basically unrelated. private int effectivePos() { return effectivePos; } private DocSymbol effectiveDocSymbol() { if (effectivePos >= doc.size()) { return DocSymbol.END; } { E e = elementStartingHere(); if (e != null) { return DocSymbol.OPEN; } } { E e = elementEndingNext(); if (e != null) { return DocSymbol.CLOSE; } } return DocSymbol.CHARACTER; } // only defined for open and close private String effectiveDocSymbolTag() { switch (effectiveDocSymbol()) { case OPEN: { String tag = doc.getTagName(elementStartingHere()); assert tag != null; return tag; } case CLOSE: { String tag = doc.getTagName(elementEndingNext()); assert tag != null; return tag; } default: throw new IllegalStateException("not at tag"); } } private boolean stackIsEmpty() { return stack.isEmpty(); } // undefined if stack is empty private StackEntry topOfStack() { assert !stack.isEmpty(); return stack.get(stack.size() - 1); } // null if outside root; must not be called if inserting private E effectiveEnclosingElement() { // need to take stack into account // stack may be deleting, which does not affect level (semantics // actually don't matter in this case, since no call sites call us during // deletions) // stack may be joining, which does not affect level (nested join needs // to know tag that it is joining) // stack may be splitting, which means we go down // stack may be adding elements, which means we add levels // if top of stack is insert element, that tells us the // tag already if (effectivePos == 0 || effectivePos >= doc.size()) { return null; } if (stackIsEmpty()) { return nthEnclosingElement(doc, effectivePos, 0); } else { if (topOfStack().asInsertElement() != null) { assert false; } if (topOfStack().asDeleteElement() != null) { { boolean foundDeleteElement = false; // TODO(ohler): Simplify this logic now that we no longer have anti elements. // Even better, merge/consolidate with DocOpAutomaton // The stack, when looking at it from bottom to top, must consist of a // sequence of deleteAntiElements followed by a sequence deleteElements. for (StackEntry e : stack) { if (e.asDeleteElement() != null) { foundDeleteElement = true; } else { assert false; } } } E e = nthEnclosingElement(doc, effectivePos, 0); assert e != null; // cannot delete root return e; } throw new RuntimeException("unexpected top of stack: " + topOfStack()); } } private String effectiveEnclosingElementTag() { if (!stackIsEmpty() && topOfStack().asInsertElement() != null) { return topOfStack().asInsertElement().tag; } else { E e = effectiveEnclosingElement(); if (e == null) { return null; } else { return doc.getTagName(e); } } } // only defined if effective enclosing element is not null. // null if effective enclosing element is root. private String effectiveEnclosingElementParentTag() { if (!stackIsEmpty() && topOfStack().asInsertElement() != null) { if (stack.size() > 1) { StackEntry s = stack.get(stack.size() - 2); assert s != null; assert s.asInsertElement() != null; return s.asInsertElement().tag; } else { return topOfStack().asInsertElement().tag; } } else { E e = effectiveEnclosingElement(); assert e != null; E p = doc.getParentElement(e); if (p == null) { return null; } else { return doc.getTagName(p); } } } private boolean isAnnotationOpen(String key) { return openAnnotationKeys.contains(key); } // Note that this is inclusive. // // NOTE(ohler): Some annotation-related indexing tricks may require // storing 4 times the index in an int. Dividing by 5 just for some // headroom. // // TODO(ohler): make sure the size limit for intermediate document states // is compatible with composition. private static final int MAX_DOC_LENGTH = Integer.MAX_VALUE / 5; /** * If an inserting mutation component is permitted as the next mutation * component, returns the maximum number of items that can be added to the * document in that component without exceeding any document size limits. * Otherwise, the return value is undefined. */ // Need to be careful with potential overflows here in case we ever // increase maxLength to Integer.MAX_VALUE. public int maxLengthIncrease() { int result = MAX_DOC_LENGTH - resultingLength; assert result >= 0; return result; } /** * If a skip mutation component is permitted as the next mutation component, * returns the maximum skip distance. * Otherwise, the return value is undefined. */ public int maxSkipDistance() { if (effectivePos >= doc.size()) { return 0; } else { return doc.size() - effectivePos; } } private boolean canIncreaseLength(int delta) { assert delta >= 0; return delta <= maxLengthIncrease(); } private boolean canSkip(int distance) { assert distance >= 0; assert doc.size() <= MAX_DOC_LENGTH; return distance <= maxSkipDistance(); } /** * If a deleteCharacters mutation component is permitted as the next mutation * component, returns the maximum number of characters that it can delete. * Otherwise, the return value is undefined. */ public int maxCharactersToDelete() { return remainingCharactersInElement(doc, effectivePos); } private boolean topOfStackIsDeletion() { return !stackIsEmpty() && topOfStack().asDeleteElement() != null; } private boolean topOfStackIsInsertion() { return !stackIsEmpty() && topOfStack().asInsertElement() != null; } private boolean topOfStackIsInsertElement() { return !stackIsEmpty() && (topOfStack().asInsertElement() != null); } private boolean topOfStackIsDeleteElement() { return !stackIsEmpty() && (topOfStack().asDeleteElement() != null); } // current state manipulators private void advance(int distance) { // we're not asserting canIncreaseLength() or similar here, since // the driver may be generating an invalid op deliberately. assert distance >= 0; effectivePos += distance; } private void increaseLength(int delta) { resultingLength += delta; } private void decreaseLength(int delta){ resultingLength -= delta; } private void pushOntoStack(StackEntry e) { stack.add(e); } private void popStack() { assert !stack.isEmpty(); stack.remove(stack.size() - 1); } private void setAnnotationOpen(String key) { openAnnotationKeys.add(key); } private void setAnnotationClosed(String key) { openAnnotationKeys.remove(key); } // check/do methods /** * Checks if a skip transition with the given parameters would be valid. */ public ValidationResult checkSkip(int distance, ViolationCollector v) { if (distance <= 0) { return skipDistanceNotPositive(v); } if (!stackIsEmpty()) { return skipInsideInsertOrDelete(v); } if (!canSkip(distance)) { return skipPastEnd(v); } return valid(); } /** * Performs a skip transition with the given parameters. */ public void doSkip(int distance) { assert checkSkip(distance, null) != ValidationResult.ILL_FORMED; advance(distance); resultingPos += distance; } /** * Checks if a characters transition with the given parameters would be valid. */ public ValidationResult checkCharacters(String characters, ViolationCollector v) { // TODO(danilatos/ohler): Check schema and surrogates if (characters == null) { return nullCharacters(v); } if (characters.length() == 0) { return emptyCharacters(v); } if (topOfStackIsDeletion()) { return insertInsideDelete(v); } String enclosingTag = effectiveEnclosingElementTag(); if (!tagAllowsText(enclosingTag)) { return textNotAllowedInElement(v, enclosingTag); } if (!canIncreaseLength(characters.length())) { return tooLong(v); } return valid(); } /** * Performs a characters transition with the given parameters. */ public void doCharacters(String characters) { assert checkCharacters(characters, null) != ValidationResult.ILL_FORMED; increaseLength(characters.length()); resultingPos += characters.length(); } /** * Checks if a deleteCharacters transition with the given parameters would be valid. */ public ValidationResult checkDeleteCharacters(int count, ViolationCollector v) { if (count <= 0) { return deleteLengthNotPositive(v); } if (topOfStackIsInsertion()) { return deleteInsideInsert(v); } int available = maxCharactersToDelete(); if (count > available) { return cannotDeleteSoManyCharacters(v, count, available); } return valid(); } /** * Performs a deleteCharacters transition with the given parameters. */ public void doDeleteCharacters(int count) { assert checkDeleteCharacters(count, null) != ValidationResult.ILL_FORMED; advance(count); decreaseLength(count); } private ValidationResult validateAttributes(String tag, Map<String, String> attr, ViolationCollector v, boolean allowRemovals) { if (attr == null) { return nullAttributes(v); } for (Map.Entry<String, String> e : attr.entrySet()) { String key = e.getKey(); String value = e.getValue(); if (key == null) { return nullAttributeKey(v); } if (!isXmlName(key)) { return attributeKeyNotXmlName(v, key); } if (value == null) { if (!allowRemovals) { return nullAttributeValue(v); } if (!elementAllowsAttribute(tag, key)) { return invalidAttribute(v, tag, key); } } else { if (!elementAllowsAttribute(tag, key, value)) { return invalidAttribute(v, tag, key, value); } } } return ValidationResult.VALID; } /** * Checks if an elementStart with the given parameters would be valid. */ public ValidationResult checkElementStart(String tag, Map<String, String> attr, ViolationCollector v) { if (tag == null) { return nullTag(v); } if (!isXmlName(tag)) { return elementTypeNotXmlName(v, tag); } { ValidationResult attrViolation = validateAttributes(tag, attr, v, false); if (attrViolation != ValidationResult.VALID) { return attrViolation; } } if (topOfStackIsDeletion()) { return insertInsideDelete(v); } if (!canIncreaseLength(2)) { return tooLong(v); } if (effectiveDocSymbol() == DocSymbol.END && effectiveEnclosingElementTag() == null && stackIsEmpty() && resultingLength() == 0) { if (elementAllowedAsRoot(tag)) { return valid(); } else { return typeInvalidRoot(v); } } String parentTag = effectiveEnclosingElementTag(); if (parentTag == null) { if (!elementAllowedAsRoot(tag)) { return typeInvalidRoot(v); } } else { if (!elementAllowsChild(parentTag, tag)) { return invalidChild(v, parentTag, tag); } } return valid(); } /** * Performs an elementStart transition with the given parameters. */ public void doElementStart(String tag, Map<String, String> attr) { assert checkElementStart(tag, attr, null) != ValidationResult.ILL_FORMED; pushOntoStack(InsertElement.getInstance(tag)); increaseLength(2); resultingPos += 1; } /** * Checks if an elementEnd transition with the given parameters would be valid. */ public ValidationResult checkElementEnd(ViolationCollector v) { if (!topOfStackIsInsertElement()) { return mismatchedElementEnd(v); } return valid(); } /** * Performs an elementEnd transition with the given parameters. */ public void doElementEnd() { assert checkElementEnd(null) != ValidationResult.ILL_FORMED; popStack(); // size increase happens in element start resultingPos += 1; } /** * Checks if a deleteElementStart with the given parameters would be valid. */ public ValidationResult checkDeleteElementStart(ViolationCollector v) { if (topOfStackIsInsertion()) { return deleteInsideInsert(v); } if (effectiveDocSymbol() != DocSymbol.OPEN) { return noElementStartToDelete(v); } return valid(); } /** * Performs a deleteElementStart transition with the given parameters. */ public void doDeleteElementStart() { assert checkDeleteElementStart(null) != ValidationResult.ILL_FORMED; pushOntoStack(DeleteElement.getInstance()); advance(1); // size decrease happens in delete element end } /** * Checks if a deleteElementEnd with the given parameters would be valid. */ public ValidationResult checkDeleteElementEnd(ViolationCollector v) { if (!topOfStackIsDeleteElement()) { return mismatchedDeleteElementEnd(v); } if (effectiveDocSymbol() != DocSymbol.CLOSE) { return noElementEndToDelete(v); } return valid(); } /** * Performs a deleteElementEnd transition with the given parameters. */ public void doDeleteElementEnd() { assert checkDeleteElementEnd(null) != ValidationResult.ILL_FORMED; popStack(); decreaseLength(2); advance(1); } private ValidationResult checkChangeAttributes(Map<String, String> attr, ViolationCollector v, boolean allowNullValues) { if (!stackIsEmpty()) { return attributeChangeInsideInsertOrDelete(v); } if (effectiveDocSymbol() != DocSymbol.OPEN) { return noElementStartToChangeAttributes(v); } String actualTag = effectiveDocSymbolTag(); assert actualTag != null; return validateAttributes(actualTag, attr, v, allowNullValues); } /** * Checks if a setAttributes with the given parameters would be valid. */ public ValidationResult checkSetAttributes(Map<String, String> attr, ViolationCollector v) { return checkChangeAttributes(attr, v, false); } /** * Performs a setAttributes transition with the given parameters. */ public void doSetAttributes(Map<String, String> attr) { assert checkSetAttributes(attr, null) != ValidationResult.ILL_FORMED; advance(1); resultingPos += 1; } /** * Checks if an updateAttributes with the given parameters would be valid. */ public ValidationResult checkUpdateAttributes(Map<String, String> attr, ViolationCollector v) { return checkChangeAttributes(attr, v, true); } /** * Performs an updateAttributes transition with the given parameters. */ public void doUpdateAttributes(Map<String, String> attr) { assert checkUpdateAttributes(attr, null) != ValidationResult.ILL_FORMED; advance(1); resultingPos += 1; } private ValidationResult validateAnnotationKey(String key, ViolationCollector v) { if (key == null) { return nullAnnotationKey(v); } return ValidationResult.VALID; } /** * Checks if a startAnnotation with the given parameters would be valid. */ public ValidationResult checkStartAnnotation(String key, String value, ViolationCollector v) { { ValidationResult r = validateAnnotationKey(key, v); if (r != ValidationResult.VALID) { return r; } } return valid(); } /** * Performs a startAnnotation transition with the given parameters. */ public void doStartAnnotation(String key, String value) { assert checkStartAnnotation(key, value, null) != ValidationResult.ILL_FORMED; setAnnotationOpen(key); } /** * Checks if an endAnnotation with the given parameters would be valid. */ public ValidationResult checkEndAnnotation(String key, ViolationCollector v) { { ValidationResult r = validateAnnotationKey(key, v); if (r != ValidationResult.VALID) { return r; } } if (!isAnnotationOpen(key)) { return mismatchedEndAnnotation(v, key); } return valid(); } /** * Performs an endAnnotation transition with the given parameters. */ public void doEndAnnotation(String key) { assert checkEndAnnotation(key, null) != ValidationResult.ILL_FORMED; setAnnotationClosed(key); } /** * Checks whether the automaton is in an accepting state, i.e., whether the * operation would be valid if no further mutation components follow. */ public ValidationResult checkFinish(ViolationCollector v) { for (StackEntry e : stack) { return e.notClosed(this, v); } for (String key : openAnnotationKeys) { return mismatchedStartAnnotation(v, key); } return ValidationResult.VALID; } /** * Notifies the automaton that no further mutation components follow. */ // This doesn't actually do anything important. It's here for symmetry only. public void doFinish() { assert checkFinish(null) != ValidationResult.ILL_FORMED; } }
googleapis/google-cloud-java
37,069
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SourceInstanceParams.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 specification of the parameters to use when creating the instance template from a source instance. * </pre> * * Protobuf type {@code google.cloud.compute.v1.SourceInstanceParams} */ public final class SourceInstanceParams extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.SourceInstanceParams) SourceInstanceParamsOrBuilder { private static final long serialVersionUID = 0L; // Use SourceInstanceParams.newBuilder() to construct. private SourceInstanceParams(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SourceInstanceParams() { diskConfigs_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SourceInstanceParams(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SourceInstanceParams_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SourceInstanceParams_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.SourceInstanceParams.class, com.google.cloud.compute.v1.SourceInstanceParams.Builder.class); } public static final int DISK_CONFIGS_FIELD_NUMBER = 235580623; @SuppressWarnings("serial") private java.util.List<com.google.cloud.compute.v1.DiskInstantiationConfig> diskConfigs_; /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.compute.v1.DiskInstantiationConfig> getDiskConfigsList() { return diskConfigs_; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder> getDiskConfigsOrBuilderList() { return diskConfigs_; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ @java.lang.Override public int getDiskConfigsCount() { return diskConfigs_.size(); } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.DiskInstantiationConfig getDiskConfigs(int index) { return diskConfigs_.get(index); } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder getDiskConfigsOrBuilder( int index) { return diskConfigs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < diskConfigs_.size(); i++) { output.writeMessage(235580623, diskConfigs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < diskConfigs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(235580623, diskConfigs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.SourceInstanceParams)) { return super.equals(obj); } com.google.cloud.compute.v1.SourceInstanceParams other = (com.google.cloud.compute.v1.SourceInstanceParams) obj; if (!getDiskConfigsList().equals(other.getDiskConfigsList())) 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 (getDiskConfigsCount() > 0) { hash = (37 * hash) + DISK_CONFIGS_FIELD_NUMBER; hash = (53 * hash) + getDiskConfigsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.SourceInstanceParams parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.SourceInstanceParams 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.SourceInstanceParams parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.SourceInstanceParams 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.SourceInstanceParams parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.SourceInstanceParams 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.SourceInstanceParams parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.SourceInstanceParams 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.SourceInstanceParams parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.SourceInstanceParams 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.SourceInstanceParams 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.SourceInstanceParams 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.SourceInstanceParams 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 specification of the parameters to use when creating the instance template from a source instance. * </pre> * * Protobuf type {@code google.cloud.compute.v1.SourceInstanceParams} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.SourceInstanceParams) com.google.cloud.compute.v1.SourceInstanceParamsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SourceInstanceParams_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SourceInstanceParams_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.SourceInstanceParams.class, com.google.cloud.compute.v1.SourceInstanceParams.Builder.class); } // Construct using com.google.cloud.compute.v1.SourceInstanceParams.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (diskConfigsBuilder_ == null) { diskConfigs_ = java.util.Collections.emptyList(); } else { diskConfigs_ = null; diskConfigsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SourceInstanceParams_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.SourceInstanceParams getDefaultInstanceForType() { return com.google.cloud.compute.v1.SourceInstanceParams.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.SourceInstanceParams build() { com.google.cloud.compute.v1.SourceInstanceParams result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.SourceInstanceParams buildPartial() { com.google.cloud.compute.v1.SourceInstanceParams result = new com.google.cloud.compute.v1.SourceInstanceParams(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.compute.v1.SourceInstanceParams result) { if (diskConfigsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { diskConfigs_ = java.util.Collections.unmodifiableList(diskConfigs_); bitField0_ = (bitField0_ & ~0x00000001); } result.diskConfigs_ = diskConfigs_; } else { result.diskConfigs_ = diskConfigsBuilder_.build(); } } private void buildPartial0(com.google.cloud.compute.v1.SourceInstanceParams result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.SourceInstanceParams) { return mergeFrom((com.google.cloud.compute.v1.SourceInstanceParams) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.SourceInstanceParams other) { if (other == com.google.cloud.compute.v1.SourceInstanceParams.getDefaultInstance()) return this; if (diskConfigsBuilder_ == null) { if (!other.diskConfigs_.isEmpty()) { if (diskConfigs_.isEmpty()) { diskConfigs_ = other.diskConfigs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDiskConfigsIsMutable(); diskConfigs_.addAll(other.diskConfigs_); } onChanged(); } } else { if (!other.diskConfigs_.isEmpty()) { if (diskConfigsBuilder_.isEmpty()) { diskConfigsBuilder_.dispose(); diskConfigsBuilder_ = null; diskConfigs_ = other.diskConfigs_; bitField0_ = (bitField0_ & ~0x00000001); diskConfigsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDiskConfigsFieldBuilder() : null; } else { diskConfigsBuilder_.addAllMessages(other.diskConfigs_); } } } 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 1884644986: { com.google.cloud.compute.v1.DiskInstantiationConfig m = input.readMessage( com.google.cloud.compute.v1.DiskInstantiationConfig.parser(), extensionRegistry); if (diskConfigsBuilder_ == null) { ensureDiskConfigsIsMutable(); diskConfigs_.add(m); } else { diskConfigsBuilder_.addMessage(m); } break; } // case 1884644986 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.compute.v1.DiskInstantiationConfig> diskConfigs_ = java.util.Collections.emptyList(); private void ensureDiskConfigsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { diskConfigs_ = new java.util.ArrayList<com.google.cloud.compute.v1.DiskInstantiationConfig>( diskConfigs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.DiskInstantiationConfig, com.google.cloud.compute.v1.DiskInstantiationConfig.Builder, com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder> diskConfigsBuilder_; /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public java.util.List<com.google.cloud.compute.v1.DiskInstantiationConfig> getDiskConfigsList() { if (diskConfigsBuilder_ == null) { return java.util.Collections.unmodifiableList(diskConfigs_); } else { return diskConfigsBuilder_.getMessageList(); } } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public int getDiskConfigsCount() { if (diskConfigsBuilder_ == null) { return diskConfigs_.size(); } else { return diskConfigsBuilder_.getCount(); } } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public com.google.cloud.compute.v1.DiskInstantiationConfig getDiskConfigs(int index) { if (diskConfigsBuilder_ == null) { return diskConfigs_.get(index); } else { return diskConfigsBuilder_.getMessage(index); } } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder setDiskConfigs( int index, com.google.cloud.compute.v1.DiskInstantiationConfig value) { if (diskConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDiskConfigsIsMutable(); diskConfigs_.set(index, value); onChanged(); } else { diskConfigsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder setDiskConfigs( int index, com.google.cloud.compute.v1.DiskInstantiationConfig.Builder builderForValue) { if (diskConfigsBuilder_ == null) { ensureDiskConfigsIsMutable(); diskConfigs_.set(index, builderForValue.build()); onChanged(); } else { diskConfigsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder addDiskConfigs(com.google.cloud.compute.v1.DiskInstantiationConfig value) { if (diskConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDiskConfigsIsMutable(); diskConfigs_.add(value); onChanged(); } else { diskConfigsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder addDiskConfigs( int index, com.google.cloud.compute.v1.DiskInstantiationConfig value) { if (diskConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDiskConfigsIsMutable(); diskConfigs_.add(index, value); onChanged(); } else { diskConfigsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder addDiskConfigs( com.google.cloud.compute.v1.DiskInstantiationConfig.Builder builderForValue) { if (diskConfigsBuilder_ == null) { ensureDiskConfigsIsMutable(); diskConfigs_.add(builderForValue.build()); onChanged(); } else { diskConfigsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder addDiskConfigs( int index, com.google.cloud.compute.v1.DiskInstantiationConfig.Builder builderForValue) { if (diskConfigsBuilder_ == null) { ensureDiskConfigsIsMutable(); diskConfigs_.add(index, builderForValue.build()); onChanged(); } else { diskConfigsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder addAllDiskConfigs( java.lang.Iterable<? extends com.google.cloud.compute.v1.DiskInstantiationConfig> values) { if (diskConfigsBuilder_ == null) { ensureDiskConfigsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, diskConfigs_); onChanged(); } else { diskConfigsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder clearDiskConfigs() { if (diskConfigsBuilder_ == null) { diskConfigs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { diskConfigsBuilder_.clear(); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public Builder removeDiskConfigs(int index) { if (diskConfigsBuilder_ == null) { ensureDiskConfigsIsMutable(); diskConfigs_.remove(index); onChanged(); } else { diskConfigsBuilder_.remove(index); } return this; } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public com.google.cloud.compute.v1.DiskInstantiationConfig.Builder getDiskConfigsBuilder( int index) { return getDiskConfigsFieldBuilder().getBuilder(index); } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder getDiskConfigsOrBuilder( int index) { if (diskConfigsBuilder_ == null) { return diskConfigs_.get(index); } else { return diskConfigsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public java.util.List<? extends com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder> getDiskConfigsOrBuilderList() { if (diskConfigsBuilder_ != null) { return diskConfigsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(diskConfigs_); } } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public com.google.cloud.compute.v1.DiskInstantiationConfig.Builder addDiskConfigsBuilder() { return getDiskConfigsFieldBuilder() .addBuilder(com.google.cloud.compute.v1.DiskInstantiationConfig.getDefaultInstance()); } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public com.google.cloud.compute.v1.DiskInstantiationConfig.Builder addDiskConfigsBuilder( int index) { return getDiskConfigsFieldBuilder() .addBuilder( index, com.google.cloud.compute.v1.DiskInstantiationConfig.getDefaultInstance()); } /** * * * <pre> * Attached disks configuration. If not provided, defaults are applied: For boot disk and any other R/W disks, the source images for each disk will be used. For read-only disks, they will be attached in read-only mode. Local SSD disks will be created as blank volumes. * </pre> * * <code>repeated .google.cloud.compute.v1.DiskInstantiationConfig disk_configs = 235580623; * </code> */ public java.util.List<com.google.cloud.compute.v1.DiskInstantiationConfig.Builder> getDiskConfigsBuilderList() { return getDiskConfigsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.DiskInstantiationConfig, com.google.cloud.compute.v1.DiskInstantiationConfig.Builder, com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder> getDiskConfigsFieldBuilder() { if (diskConfigsBuilder_ == null) { diskConfigsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.DiskInstantiationConfig, com.google.cloud.compute.v1.DiskInstantiationConfig.Builder, com.google.cloud.compute.v1.DiskInstantiationConfigOrBuilder>( diskConfigs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); diskConfigs_ = null; } return diskConfigsBuilder_; } @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.SourceInstanceParams) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.SourceInstanceParams) private static final com.google.cloud.compute.v1.SourceInstanceParams DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.SourceInstanceParams(); } public static com.google.cloud.compute.v1.SourceInstanceParams getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SourceInstanceParams> PARSER = new com.google.protobuf.AbstractParser<SourceInstanceParams>() { @java.lang.Override public SourceInstanceParams 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<SourceInstanceParams> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SourceInstanceParams> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.SourceInstanceParams getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/felix-dev
36,739
ipojo/handler/eventadmin/eventadmin-handler-it/src/it/event-admin-it/src/test/java/org/apache/felix/ipojo/handler/eventadmin/test/TestBadConfigurations.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.ipojo.handler.eventadmin.test; import org.apache.felix.ipojo.*; import org.apache.felix.ipojo.handler.eventadmin.test.donut.Donut; import org.apache.felix.ipojo.handler.eventadmin.test.donut.DonutConsumer; import org.apache.felix.ipojo.handler.eventadmin.test.donut.DonutProvider; import org.apache.felix.ipojo.metadata.Attribute; import org.apache.felix.ipojo.metadata.Element; import org.apache.felix.ipojo.parser.ManifestMetadataParser; import org.apache.felix.ipojo.parser.ParseException; import org.junit.Before; import org.junit.Test; import org.osgi.framework.ServiceReference; import java.util.Dictionary; import java.util.Hashtable; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.fail; /** * Test the good behaviour of the EventAdminHandler. * * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a> */ public class TestBadConfigurations extends Common { /** * The namespace of the Event admin handler. */ private static final String NAMESPACE = "org.apache.felix.ipojo.handlers.event"; /** * The utility class instance. */ public EahTestUtils m_utils; /** * The available components. */ private Element[] m_components; /** * The description of a component that uses an event publisher. */ private Element m_provider; /** * The event publisher description. */ private Element m_publisher; /** * The name attribute of the event publisher. */ private Attribute m_publisherName; /** * The field attribute of the event publisher. */ private Attribute m_publisherField; /** * The topics attribute of the event publisher. */ private Attribute m_publisherTopics; /** * The data-key attribute of the event publisher. */ private Attribute m_publisherDataKey; /** * The synchronous attribute of the event publisher. */ private Attribute m_publisherSynchronous; /** * The description of a component that uses an event subscriber. */ private Element m_consumer; /** * The event subscriber description. */ private Element m_subscriber; /** * The name attribute of the event subscriber. */ private Attribute m_subscriberName; /** * The callback attribute of the event subscriber. */ private Attribute m_subscriberCallback; /** * The topics attribute of the event subscriber. */ private Attribute m_subscriberTopics; /** * The data-key attribute of the event subscriber. */ private Attribute m_subscriberDataKey; /** * The data-type attribute of the event subscriber. */ private Attribute m_subscriberDataType; private Element getManipulationForComponent(String compName) { for (int i = 0; i < m_components.length; i++) { if (m_components[i].containsAttribute("name") && m_components[i].getAttribute("name").equals(compName)) { return m_components[i].getElements("manipulation")[0]; } } return null; } /** * Initialization before test cases. * <p/> * Create all the instances */ @Before public void setUp() { m_utils = new EahTestUtils(bc, ipojoHelper); /** * Get the list of available components. */ try { String header = (String) getTestBundle().getHeaders().get( "iPOJO-Components"); m_components = ManifestMetadataParser.parseHeaderMetadata(header) .getElements("component"); } catch (ParseException e) { fail("Parse Exception when parsing iPOJO-Component"); } /** * Initialize the standard publishing component (based on the * asynchronous donut provider). */ m_provider = new Element("component", ""); m_provider.addAttribute(new Attribute("className", "org.apache.felix.ipojo.handler.eventadmin.test.donut.DonutProviderImpl")); m_provider.addAttribute(new Attribute("name", "standard donut provider for bad tests")); // The provided service of the publisher Element providesDonutProvider = new Element("provides", ""); providesDonutProvider.addAttribute(new Attribute("interface", "org.apache.felix.ipojo.handler.eventadmin.test.donut.DonutProvider")); Element providesDonutProviderProperty = new Element("property", ""); providesDonutProviderProperty .addAttribute(new Attribute("name", "name")); providesDonutProviderProperty.addAttribute(new Attribute("field", "m_name")); providesDonutProviderProperty.addAttribute(new Attribute("value", "Unknown donut vendor")); providesDonutProvider.addElement(providesDonutProviderProperty); m_provider.addElement(providesDonutProvider); // The event publisher, corresponding to the following description : // <ev:publisher name="donut-publisher" field="m_publisher" // topics="food/donuts" data-key="food" synchronous="false"/> m_publisher = new Element("publisher", NAMESPACE); m_publisherName = new Attribute("name", "donut-publisher"); m_publisherField = new Attribute("field", "m_publisher"); m_publisherTopics = new Attribute("topics", "food/donuts"); m_publisherDataKey = new Attribute("data-key", "food"); m_publisherSynchronous = new Attribute("synchronous", "false"); m_publisher.addAttribute(m_publisherName); m_publisher.addAttribute(m_publisherField); m_publisher.addAttribute(m_publisherTopics); m_publisher.addAttribute(m_publisherDataKey); m_publisher.addAttribute(m_publisherSynchronous); m_provider.addElement(m_publisher); m_provider.addElement(getManipulationForComponent("donut-provider")); /** * Initialize the standard subscribing component (based on the donut * consumer). */ m_consumer = new Element("component", ""); m_consumer.addAttribute(new Attribute("className", "org.apache.felix.ipojo.handler.eventadmin.test.donut.DonutConsumerImpl")); m_consumer.addAttribute(new Attribute("name", "standard donut consumer for bad tests")); // The provided service of the publisher Element providesDonutConsumer = new Element("provides", ""); providesDonutConsumer.addAttribute(new Attribute("interface", "org.apache.felix.ipojo.handler.eventadmin.test.donut.DonutConsumer")); Element providesDonutConsumerNameProperty = new Element("property", ""); providesDonutConsumerNameProperty.addAttribute(new Attribute("name", "name")); providesDonutConsumerNameProperty.addAttribute(new Attribute("field", "m_name")); providesDonutConsumerNameProperty.addAttribute(new Attribute("value", "Unknown donut consumer")); providesDonutConsumer.addElement(providesDonutConsumerNameProperty); Element providesDonutConsumerSlowProperty = new Element("property", ""); providesDonutConsumerSlowProperty.addAttribute(new Attribute("name", "slow")); providesDonutConsumerSlowProperty.addAttribute(new Attribute("field", "m_isSlow")); providesDonutConsumerSlowProperty.addAttribute(new Attribute("value", "false")); providesDonutConsumer.addElement(providesDonutConsumerSlowProperty); m_consumer.addElement(providesDonutConsumer); // The event publisher, corresponding to the following description : // <ev:subscriber name="donut-subscriber" callback="receiveDonut" // topics="food/donuts" data-key="food" // data-type="org.apache.felix.ipojo.handler.eventadmin.test.donut.Donut"/> m_subscriber = new Element("subscriber", NAMESPACE); m_subscriberName = new Attribute("name", "donut-subscriber"); m_subscriberCallback = new Attribute("callback", "receiveDonut"); m_subscriberTopics = new Attribute("topics", "food/donuts"); m_subscriberDataKey = new Attribute("data-key", "food"); m_subscriberDataType = new Attribute("data-type", "org.apache.felix.ipojo.handler.eventadmin.test.donut.Donut"); m_subscriber.addAttribute(m_subscriberName); m_subscriber.addAttribute(m_subscriberCallback); m_subscriber.addAttribute(m_subscriberTopics); m_subscriber.addAttribute(m_subscriberDataKey); m_subscriber.addAttribute(m_subscriberDataType); m_consumer.addElement(m_subscriber); m_consumer.addElement(getManipulationForComponent("donut-consumer")); } /** * Test the base configuration is correct to be sure the bad tests will fail * because of they are really bad, and not because of an other application * error. * <p/> * This test simply create a provider and a consumer instance, send one * event and check it is received. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testGoodConfig() throws ConfigurationException, UnacceptableConfiguration, MissingHandlerException { /** * Create the provider and the consumer instances. */ Dictionary properties = new Hashtable(); // Provider ComponentFactory providerFactory = new ComponentFactory(bc, m_provider); providerFactory.start(); properties.put("instance.name", "Emperor of donuts"); ComponentInstance providerInstance = providerFactory .createComponentInstance(properties); ServiceReference providerService = ipojoHelper .getServiceReferenceByName(DonutProvider.class .getName(), providerInstance.getInstanceName()); DonutProvider provider = (DonutProvider) bc .getService(providerService); // The consumer properties = new Hashtable(); ComponentFactory consumerFactory = new ComponentFactory(bc, m_consumer); consumerFactory.start(); properties.put("instance.name", "Homer Simpson"); properties.put("slow", "false"); ComponentInstance consumerInstance = consumerFactory .createComponentInstance(properties); ServiceReference consumerService = ipojoHelper .getServiceReferenceByName(DonutConsumer.class .getName(), consumerInstance.getInstanceName()); DonutConsumer consumer = (DonutConsumer) bc .getService(consumerService); /** * Test the normal behaviour of the instances. */ consumer.clearDonuts(); Donut sentDonut = provider.sellDonut(); Donut receivedDonut = consumer.waitForDonut(); assertEquals("The received donut must be the same as the sent one.", sentDonut, receivedDonut); /** * Destroy component's instances. */ bc.ungetService(providerService); providerInstance.dispose(); bc.ungetService(consumerService); consumerInstance.dispose(); providerFactory.stop(); consumerFactory.stop(); } /** * Try to create a publisher with no name. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithoutName() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the name attribute of the publisher m_publisher.removeAttribute(m_publisherName); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_provider); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when no name is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_publisher.addAttribute(m_publisherName); } } /** * Try to create a publisher with no field. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithoutField() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the name attribute of the publisher m_publisher.removeAttribute(m_publisherField); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_provider); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when no field is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_publisher.addAttribute(m_publisherField); } } /** * Try to create a publisher with an unexisting field. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithUnexistingField() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the name attribute of the publisher and replace with an // unexisting field name m_publisher.removeAttribute(m_publisherField); Attribute unexistingField = new Attribute("field", "m_unexistingField"); m_publisher.addAttribute(unexistingField); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_provider); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when an unexisting field is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_publisher.removeAttribute(unexistingField); m_publisher.addAttribute(m_publisherField); } } /** * Try to create a publisher with a bad typed field. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithBadTypedField() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the name attribute of the publisher and replace with an // bad typed field name m_publisher.removeAttribute(m_publisherField); Attribute badTypedField = new Attribute("field", "m_name"); m_publisher.addAttribute(badTypedField); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_provider); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when an bad typed field is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_publisher.removeAttribute(badTypedField); m_publisher.addAttribute(m_publisherField); } } /** * Try to create a publisher instance without topics. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithoutTopics() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the publisher m_publisher.removeAttribute(m_publisherTopics); ComponentFactory fact = new ComponentFactory(bc, m_provider); fact.start(); // Try to create an instance without specified topics Dictionary conf = new Hashtable(); conf.put("instance.name", "provider without topics"); ComponentInstance instance; try { instance = fact.createComponentInstance(conf); // Should not be executed instance.dispose(); fail("The factory must not create instance without specified topics."); } catch (ConfigurationException e) { // OK } finally { fact.stop(); // Restore the original state of the publisher m_publisher.addAttribute(m_publisherTopics); } } /** * Try to create a publisher with malformed topics. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithMalformedTopics() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the publisher and replace with a // malformed one m_publisher.removeAttribute(m_publisherTopics); Attribute malformedTopics = new Attribute("topics", "| |\\| \\/ /-\\ |_ | |)"); m_publisher.addAttribute(malformedTopics); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_provider); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when invalid topics are specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_publisher.removeAttribute(malformedTopics); m_publisher.addAttribute(m_publisherTopics); } } /** * Try to create a publisher with a pattern topic (ending with '*') instead of a fixed topic. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithPatternTopic() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the publisher and replace with a // malformed one m_publisher.removeAttribute(m_publisherTopics); Attribute malformedTopics = new Attribute("topics", "a/pattern/topic/*"); m_publisher.addAttribute(malformedTopics); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_provider); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when invalid topics are specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_publisher.removeAttribute(malformedTopics); m_publisher.addAttribute(m_publisherTopics); } } /** * Try to create a publisher with malformed instance topics. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testPublisherWithMalformedInstanceTopics() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the publisher and replace with a // malformed one m_publisher.removeAttribute(m_publisherTopics); ComponentFactory fact = new ComponentFactory(bc, m_provider); fact.start(); // Try to create an instance with malformed specified topics Dictionary conf = new Hashtable(); conf.put("instance.name", "provider with malformed topics"); Dictionary topics = new Hashtable(); topics.put("donut-publisher", "| |\\| \\/ /-\\ |_ | |)"); conf.put("event.topics", topics); ComponentInstance instance; try { instance = fact.createComponentInstance(conf); // Should not be executed instance.dispose(); fail("The factory must not create instance with invalid specified topics."); } catch (ConfigurationException e) { // OK } finally { fact.stop(); // Restore the original state of the publisher m_publisher.addAttribute(m_publisherTopics); } } /** * Try to create a subscriber with no name. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithoutName() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the name attribute of the publisher m_subscriber.removeAttribute(m_subscriberName); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_consumer); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when no name is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_subscriber.addAttribute(m_subscriberName); } } /** * Try to create a subscriber with no callback. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithoutCallback() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the name attribute of the publisher m_subscriber.removeAttribute(m_subscriberCallback); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_consumer); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when no callback is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the publisher m_subscriber.addAttribute(m_subscriberCallback); } } /** * Try to create a subscriber instance without topics. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithoutTopics() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the subscriber m_subscriber.removeAttribute(m_subscriberTopics); ComponentFactory fact = new ComponentFactory(bc, m_consumer); fact.start(); // Try to create an instance without specified topics Dictionary conf = new Hashtable(); conf.put("instance.name", "consumer without topics"); conf.put("slow", "false"); ComponentInstance instance; try { instance = fact.createComponentInstance(conf); // Should not be executed instance.dispose(); fail("The factory must not create instance without specified topics."); } catch (ConfigurationException e) { // OK } finally { fact.stop(); // Restore the original state of the subscriber m_subscriber.addAttribute(m_subscriberTopics); } } /** * Try to create a subscriber with malformed topics. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithMalformedTopics() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the subscriber and replace with a // malformed one m_subscriber.removeAttribute(m_subscriberTopics); Attribute malformedTopics = new Attribute("topics", "| |\\| \\/ /-\\ |_ | |)"); m_subscriber.addAttribute(malformedTopics); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_consumer); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when invalid topics are specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the subscriber m_subscriber.removeAttribute(malformedTopics); m_subscriber.addAttribute(m_subscriberTopics); } } /** * Try to create a subscriber with malformed instance topics. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithMalformedInstanceTopics() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the topics attribute of the subscriber and replace with a // malformed one m_subscriber.removeAttribute(m_subscriberTopics); ComponentFactory fact = new ComponentFactory(bc, m_consumer); fact.start(); // Try to create an instance with malformed specified topics Dictionary conf = new Hashtable(); conf.put("instance.name", "consumer with malformed topics"); Dictionary topics = new Hashtable(); topics.put("donut-subscriber", "| |\\| \\/ /-\\ |_ | |)"); conf.put("event.topics", topics); ComponentInstance instance; try { instance = fact.createComponentInstance(conf); // Should not be executed instance.dispose(); fail("The factory must not create instance with invalid specified topics."); } catch (ConfigurationException e) { // OK } finally { fact.stop(); // Restore the original state of the subscriber m_subscriber.addAttribute(m_subscriberTopics); } } /** * Try to create a subscriber with unknown data type. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithUnknownDataType() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the data-type attribute of the subscriber and replace with a // malformed one m_subscriber.removeAttribute(m_subscriberDataType); Attribute unknownType = new Attribute("data-type", "org.unknown.Clazz"); m_subscriber.addAttribute(unknownType); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_consumer); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when unknown data type is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the subscriber m_subscriber.removeAttribute(unknownType); m_subscriber.addAttribute(m_subscriberDataType); } } /** * Try to create a subscriber with a data type that does not match with the * callback parameter type. * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened */ @Test public void testSubscriberWithUnappropriatedDataType() throws ConfigurationException, MissingHandlerException, UnacceptableConfiguration { // Remove the data-type attribute of the subscriber and replace with a // malformed one m_subscriber.removeAttribute(m_subscriberDataType); Attribute unknownType = new Attribute("data-type", "java.lang.String"); m_subscriber.addAttribute(unknownType); // Create and try to start the factory ComponentFactory fact = new ComponentFactory(bc, m_consumer); try { fact.start(); // Should not be executed fact.stop(); fail("The factory must not start when unappropriated data type is specified."); } catch (IllegalStateException e) { // OK } finally { // Restore the original state of the subscriber m_subscriber.removeAttribute(unknownType); m_subscriber.addAttribute(m_subscriberDataType); } } // DEBUG public void dumpElement(String message, Element root) { System.err.println(message + "\n" + dumpElement(0, root)); } // DEBUG private String dumpElement(int level, Element element) { StringBuilder sb = new StringBuilder(); // Enter tag for (int i = 0; i < level; i++) { sb.append(" "); } sb.append('<'); sb.append(element.getName()); Attribute[] attributes = element.getAttributes(); for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; sb.append(' '); sb.append(attribute.getName()); sb.append('='); sb.append(attribute.getValue()); } sb.append(">\n"); // Children Element[] elements = element.getElements(); for (int i = 0; i < elements.length; i++) { sb.append(dumpElement(level + 1, elements[i])); } // Exit tag for (int i = 0; i < level; i++) { sb.append(" "); } sb.append("</" + element.getName() + ">\n"); return sb.toString(); } /** * Creates a subscriber listening on a pattern topic (ending with '*'). * * @throws org.apache.felix.ipojo.ConfigurationException * something bad happened. * @throws org.apache.felix.ipojo.MissingHandlerException * something bad happened. * @throws org.apache.felix.ipojo.UnacceptableConfiguration * something bad happened. */ @Test public void testSubscriberWithPatternTopic() throws UnacceptableConfiguration, MissingHandlerException, ConfigurationException { Dictionary properties = new Hashtable(); Dictionary topics = new Hashtable(); // Create the donut consumer instance, listening on a pattern topic properties.put("instance.name", "subscriber with pattern topic"); topics.put("donut-subscriber", "a/pattern/topic/*rf"); properties.put("event.topics", topics); ComponentInstance instance = null; try { instance = m_utils.getDonutConsumerFactory() .createComponentInstance(properties); // Should not been executed instance.dispose(); fail("An invalid topic scope was accepted)"); } catch (ConfigurationException e) { // Nothing to do } properties = new Hashtable(); topics = new Hashtable(); // Create the donut consumer instance, listening on a pattern topic properties.put("instance.name", "subscriber with pattern topic"); topics.put("donut-subscriber", "a/pattern/*topic/rf"); properties.put("event.topics", topics); try { instance = m_utils.getDonutConsumerFactory() .createComponentInstance(properties); instance.dispose(); fail("An invalid topic scope was accepted (2)"); } catch (ConfigurationException e) { // Nothing to do } } }
apache/ranger
36,900
agents-audit/core/src/main/java/org/apache/ranger/audit/queue/AuditFileQueueSpool.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.ranger.audit.queue; import org.apache.ranger.audit.model.AuditEventBase; import org.apache.ranger.audit.model.AuditIndexRecord; import org.apache.ranger.audit.model.AuthzAuditEvent; import org.apache.ranger.audit.model.SPOOL_FILE_STATUS; import org.apache.ranger.audit.provider.AuditHandler; import org.apache.ranger.audit.provider.MiscUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * This class temporarily stores logs in Local file system before it despatches each logs in file to the AuditBatchQueue Consumer. * This gets instantiated only when AuditFileCacheProvider is enabled (xasecure.audit.provider.filecache.is.enabled). * When AuditFileCacheProvider is enabled all the logs are stored in local file system before sent to destination. */ public class AuditFileQueueSpool implements Runnable { private static final Logger logger = LoggerFactory.getLogger(AuditFileQueueSpool.class); public static final String PROP_FILE_SPOOL_LOCAL_DIR = "filespool.dir"; public static final String PROP_FILE_SPOOL_LOCAL_FILE_NAME = "filespool.filename.format"; public static final String PROP_FILE_SPOOL_ARCHIVE_DIR = "filespool.archive.dir"; public static final String PROP_FILE_SPOOL_ARCHIVE_MAX_FILES_COUNT = "filespool.archive.max.files"; public static final String PROP_FILE_SPOOL_FILENAME_PREFIX = "filespool.file.prefix"; public static final String PROP_FILE_SPOOL_FILE_ROLLOVER = "filespool.file.rollover.sec"; public static final String PROP_FILE_SPOOL_INDEX_FILE = "filespool.index.filename"; public static final String PROP_FILE_SPOOL_DEST_RETRY_MS = "filespool.destination.retry.ms"; public static final String PROP_FILE_SPOOL_BATCH_SIZE = "filespool.buffer.size"; public static final String FILE_QUEUE_PROVIDER_NAME = "AuditFileQueueSpool"; public static final String DEFAULT_AUDIT_FILE_TYPE = "json"; AuditHandler consumerProvider; BlockingQueue<AuditIndexRecord> indexQueue = new LinkedBlockingQueue<>(); List<AuditIndexRecord> indexRecords = new ArrayList<>(); // Folder and File attributes File logFolder; String logFileNameFormat; File archiveFolder; String fileNamePrefix; String indexFileName; File indexFile; String indexDoneFileName; String auditFileType; File indexDoneFile; long bufferSize = 1000; int retryDestinationMS = 30 * 1000; // Default 30 seconds int fileRolloverSec = 24 * 60 * 60; // In seconds int maxArchiveFiles = 100; int errorLogIntervalMS = 30 * 1000; // Every 30 seconds long lastErrorLogMS; boolean closeFile; boolean isPending; long lastAttemptTime; boolean initDone; PrintWriter logWriter; AuditIndexRecord currentWriterIndexRecord; AuditIndexRecord currentConsumerIndexRecord; Thread destinationThread; boolean isDrain; boolean isDestDown; boolean isWriting = true; boolean isSpoolingSuccessful = true; public AuditFileQueueSpool(AuditHandler consumerProvider) { this.consumerProvider = consumerProvider; } public void init(Properties prop) { init(prop, null); } public boolean init(Properties props, String basePropertyName) { logger.debug("==> AuditFileQueueSpool.init()"); if (initDone) { logger.error("init() called more than once. queueProvider=, consumerProvider={}", consumerProvider.getName()); return true; } String propPrefix = "xasecure.audit.filespool"; if (basePropertyName != null) { propPrefix = basePropertyName; } try { // Initial folder and file properties String logFolderProp = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_FILE_SPOOL_LOCAL_DIR); String archiveFolderProp = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_FILE_SPOOL_ARCHIVE_DIR); logFileNameFormat = MiscUtil.getStringProperty(props, basePropertyName + "." + PROP_FILE_SPOOL_LOCAL_FILE_NAME); fileNamePrefix = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_FILE_SPOOL_FILENAME_PREFIX); indexFileName = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_FILE_SPOOL_INDEX_FILE); retryDestinationMS = MiscUtil.getIntProperty(props, propPrefix + "." + PROP_FILE_SPOOL_DEST_RETRY_MS, retryDestinationMS); fileRolloverSec = MiscUtil.getIntProperty(props, propPrefix + "." + PROP_FILE_SPOOL_FILE_ROLLOVER, fileRolloverSec); maxArchiveFiles = MiscUtil.getIntProperty(props, propPrefix + "." + PROP_FILE_SPOOL_ARCHIVE_MAX_FILES_COUNT, maxArchiveFiles); logger.info("retryDestinationMS={}, queueName={}", retryDestinationMS, FILE_QUEUE_PROVIDER_NAME); logger.info("fileRolloverSec={}, queueName={}", fileRolloverSec, FILE_QUEUE_PROVIDER_NAME); logger.info("maxArchiveFiles={}, queueName={}", maxArchiveFiles, FILE_QUEUE_PROVIDER_NAME); if (logFolderProp == null || logFolderProp.isEmpty()) { logger.error("Audit spool folder is not configured. Please set {}.{}. queueName={}", propPrefix, PROP_FILE_SPOOL_LOCAL_DIR, FILE_QUEUE_PROVIDER_NAME); return false; } logFolder = new File(logFolderProp); if (!logFolder.isDirectory()) { boolean result = logFolder.mkdirs(); if (!logFolder.isDirectory() || !result) { logger.error("File Spool folder not found and can't be created. folder={}, queueName={}", logFolder.getAbsolutePath(), FILE_QUEUE_PROVIDER_NAME); return false; } } logger.info("logFolder={}, queueName={}", logFolder, FILE_QUEUE_PROVIDER_NAME); if (logFileNameFormat == null || logFileNameFormat.isEmpty()) { logFileNameFormat = "spool_" + "%app-type%" + "_" + "%time:yyyyMMdd-HHmm.ss%.log"; } logger.info("logFileNameFormat={}, queueName={}", logFileNameFormat, FILE_QUEUE_PROVIDER_NAME); if (archiveFolderProp == null || archiveFolderProp.isEmpty()) { archiveFolder = new File(logFolder, "archive"); } else { archiveFolder = new File(archiveFolderProp); } if (!archiveFolder.isDirectory()) { boolean result = archiveFolder.mkdirs(); if (!archiveFolder.isDirectory() || !result) { logger.error("File Spool archive folder not found and can't be created. folder={}, queueName={}", archiveFolder.getAbsolutePath(), FILE_QUEUE_PROVIDER_NAME); return false; } } logger.info("archiveFolder={}, queueName={}", archiveFolder, FILE_QUEUE_PROVIDER_NAME); if (indexFileName == null || indexFileName.isEmpty()) { if (fileNamePrefix == null || fileNamePrefix.isEmpty()) { fileNamePrefix = FILE_QUEUE_PROVIDER_NAME + "_" + consumerProvider.getName(); } indexFileName = "index_" + fileNamePrefix + "_" + "%app-type%" + ".json"; indexFileName = MiscUtil.replaceTokens(indexFileName, System.currentTimeMillis()); } indexFile = new File(logFolder, indexFileName); if (!indexFile.exists()) { boolean ret = indexFile.createNewFile(); if (!ret) { logger.error("Error creating index file. fileName={}", indexFile.getPath()); return false; } } logger.info("indexFile={}, queueName={}", indexFile, FILE_QUEUE_PROVIDER_NAME); int lastDot = indexFileName.lastIndexOf('.'); if (lastDot < 0) { lastDot = indexFileName.length() - 1; } indexDoneFileName = indexFileName.substring(0, lastDot) + "_closed.json"; indexDoneFile = new File(logFolder, indexDoneFileName); if (!indexDoneFile.exists()) { boolean ret = indexDoneFile.createNewFile(); if (!ret) { logger.error("Error creating index done file. fileName={}", indexDoneFile.getPath()); return false; } } logger.info("indexDoneFile={}, queueName={}", indexDoneFile, FILE_QUEUE_PROVIDER_NAME); // Load index file loadIndexFile(); for (AuditIndexRecord auditIndexRecord : indexRecords) { if (!auditIndexRecord.getStatus().equals(SPOOL_FILE_STATUS.done)) { isPending = true; } if (auditIndexRecord.getStatus().equals(SPOOL_FILE_STATUS.write_inprogress)) { currentWriterIndexRecord = auditIndexRecord; logger.info("currentWriterIndexRecord={}, queueName={}", currentWriterIndexRecord.getFilePath(), FILE_QUEUE_PROVIDER_NAME); } if (auditIndexRecord.getStatus().equals(SPOOL_FILE_STATUS.read_inprogress)) { indexQueue.add(auditIndexRecord); } } printIndex(); for (AuditIndexRecord auditIndexRecord : indexRecords) { if (auditIndexRecord.getStatus().equals(SPOOL_FILE_STATUS.pending)) { File consumerFile = new File(auditIndexRecord.getFilePath()); if (!consumerFile.exists()) { logger.error("INIT: Consumer file={} not found.", consumerFile.getPath()); } else { indexQueue.add(auditIndexRecord); } } } auditFileType = MiscUtil.getStringProperty(props, propPrefix + ".filetype", DEFAULT_AUDIT_FILE_TYPE); if (auditFileType == null) { auditFileType = DEFAULT_AUDIT_FILE_TYPE; } } catch (Throwable t) { logger.error("Error initializing File Spooler. queue={}", FILE_QUEUE_PROVIDER_NAME, t); return false; } bufferSize = MiscUtil.getLongProperty(props, propPrefix + "." + PROP_FILE_SPOOL_BATCH_SIZE, bufferSize); initDone = true; logger.debug("<== AuditFileQueueSpool.init()"); return true; } /** * Start looking for outstanding logs and update status according. */ public void start() { if (!initDone) { logger.error("Cannot start Audit File Spooler. Initilization not done yet. queueName={}", FILE_QUEUE_PROVIDER_NAME); return; } logger.info("Starting writerThread, queueName={}, consumer={}", FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); // Let's start the thread to read destinationThread = new Thread(this, FILE_QUEUE_PROVIDER_NAME + "_" + consumerProvider.getName() + "_destWriter"); destinationThread.setDaemon(true); destinationThread.start(); } public void stop() { if (!initDone) { logger.error("Cannot stop Audit File Spooler. Initilization not done. queueName={}", FILE_QUEUE_PROVIDER_NAME); return; } logger.info("Stop called, queueName={}, consumer={}", FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); isDrain = true; flush(); PrintWriter out = getOpenLogFileStream(); if (out != null) { // If write is still going on, then let's give it enough time to complete for (int i = 0; i < 3; i++) { if (isWriting) { try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore } continue; } try { logger.info("Closing open file, queueName={}, consumer={}", FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); out.flush(); out.close(); break; } catch (Throwable t) { logger.debug("Error closing spool out file.", t); } } } try { if (destinationThread != null) { destinationThread.interrupt(); } destinationThread = null; } catch (Throwable e) { // ignore } } public void flush() { if (!initDone) { logger.error("Cannot flush Audit File Spooler. Initilization not done. queueName={}", FILE_QUEUE_PROVIDER_NAME); return; } PrintWriter out = getOpenLogFileStream(); if (out != null) { out.flush(); } } /** * If any files are still not processed. Also, if the destination is not * reachable * * @return */ public boolean isPending() { if (!initDone) { logError("isPending(): File Spooler not initialized. queueName=" + FILE_QUEUE_PROVIDER_NAME); return false; } return isPending; } /** * Milliseconds from last attempt time * * @return */ public long getLastAttemptTimeDelta() { if (lastAttemptTime == 0) { return 0; } return System.currentTimeMillis() - lastAttemptTime; } public synchronized void stashLogs(AuditEventBase event) { if (isDrain) { // Stop has been called, so this method shouldn't be called logger.error("stashLogs() is called after stop is called. event={}", event); return; } try { isWriting = true; PrintWriter logOut = getLogFileStream(); String jsonStr = MiscUtil.stringify(event); logOut.println(jsonStr); logOut.flush(); isPending = true; isSpoolingSuccessful = true; } catch (Throwable t) { isSpoolingSuccessful = false; logger.error("Error writing to file. event={}", event, t); } finally { isWriting = false; } } public synchronized void stashLogs(Collection<AuditEventBase> events) { for (AuditEventBase event : events) { stashLogs(event); } flush(); } public synchronized void stashLogsString(String event) { if (isDrain) { // Stop has been called, so this method shouldn't be called logger.error("stashLogs() is called after stop is called. event={}", event); return; } try { isWriting = true; PrintWriter logOut = getLogFileStream(); logOut.println(event); } catch (Exception ex) { logger.error("Error writing to file. event={}", event, ex); } finally { isWriting = false; } } public synchronized boolean isSpoolingSuccessful() { return isSpoolingSuccessful; } public synchronized void stashLogsString(Collection<String> events) { for (String event : events) { stashLogsString(event); } flush(); } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { try { //This is done to clear the MDC context to avoid issue with Ranger Auditing for Knox MDC.clear(); runLogAudit(); } catch (Throwable t) { logger.error("Exited thread without abnormaly. queue={}", consumerProvider.getName(), t); } } public void runLogAudit() { // boolean isResumed = false; while (true) { try { if (isDestDown) { logger.info("Destination is down. sleeping for {} milli seconds. indexQueue={}, queueName={}, consumer={}", retryDestinationMS, indexQueue.size(), FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); Thread.sleep(retryDestinationMS); } // Let's pause between each iteration if (currentConsumerIndexRecord == null) { currentConsumerIndexRecord = indexQueue.poll(retryDestinationMS, TimeUnit.MILLISECONDS); } else { Thread.sleep(retryDestinationMS); } if (isDrain) { // Need to exit break; } if (currentConsumerIndexRecord == null) { closeFileIfNeeded(); continue; } boolean isRemoveIndex = false; File consumerFile = new File(currentConsumerIndexRecord.getFilePath()); if (!consumerFile.exists()) { logger.error("Consumer file={} not found.", consumerFile.getPath()); printIndex(); isRemoveIndex = true; } else { // Let's open the file to write try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(currentConsumerIndexRecord.getFilePath()), StandardCharsets.UTF_8))) { if (auditFileType.equalsIgnoreCase(DEFAULT_AUDIT_FILE_TYPE)) { // if Audit File format is JSON each audit file in the Local Spool Location will be copied // to HDFS location as JSON File srcFile = new File(currentConsumerIndexRecord.getFilePath()); logFile(srcFile); } else { // If Audit File format is ORC, each records in audit files in the Local Spool Location will be // read and converted into ORC format and pushed into an ORC file. logEvent(br); } logger.info("Done reading file. file={}, queueName={}, consumer={}", currentConsumerIndexRecord.getFilePath(), FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); // The entire file is read currentConsumerIndexRecord.setStatus(SPOOL_FILE_STATUS.done); currentConsumerIndexRecord.setDoneCompleteTime(new Date()); currentConsumerIndexRecord.setLastAttempt(true); isRemoveIndex = true; } catch (Exception ex) { isDestDown = true; logError("Destination down. queueName=" + FILE_QUEUE_PROVIDER_NAME + ", consumer=" + consumerProvider.getName()); lastAttemptTime = System.currentTimeMillis(); // Update the index file currentConsumerIndexRecord.setLastFailedTime(new Date()); currentConsumerIndexRecord.setFailedAttemptCount(currentConsumerIndexRecord.getFailedAttemptCount() + 1); currentConsumerIndexRecord.setLastAttempt(false); saveIndexFile(); } } if (isRemoveIndex) { // Remove this entry from index removeIndexRecord(currentConsumerIndexRecord); currentConsumerIndexRecord = null; closeFileIfNeeded(); } } catch (InterruptedException e) { logger.info("Caught exception in consumer thread. Shutdown might be in progress"); } catch (Throwable t) { logger.error("Exception in destination writing thread.", t); } } logger.info("Exiting file spooler. provider={}, consumer={}", FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); } /** * Load the index file * * @throws IOException */ void loadIndexFile() throws IOException { logger.info("Loading index file. fileName={}", indexFile.getPath()); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(indexFile), StandardCharsets.UTF_8))) { indexRecords.clear(); for (String line = br.readLine(); line != null; line = br.readLine()) { if (!line.isEmpty() && !line.startsWith("#")) { try { AuditIndexRecord record = MiscUtil.fromJson(line, AuditIndexRecord.class); indexRecords.add(record); } catch (Exception e) { logger.error("Error parsing following JSON: {}", line, e); } } } } } synchronized void printIndex() { logger.info("INDEX printIndex() ==== START"); for (AuditIndexRecord record : indexRecords) { logger.info("INDEX={}, isFileExist={}", record, (new File(record.getFilePath()).exists())); } logger.info("INDEX printIndex() ==== END"); } synchronized void removeIndexRecord(AuditIndexRecord indexRecord) throws IOException { for (Iterator<AuditIndexRecord> iter = indexRecords.iterator(); iter.hasNext(); ) { AuditIndexRecord record = iter.next(); if (record.getId().equals(indexRecord.getId())) { logger.info("Removing file from index. file={}, queueName={}, consumer={}", record.getFilePath(), FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); iter.remove(); appendToDoneFile(record); } } saveIndexFile(); // If there are no more files in the index, then let's assume the destination is now available if (indexRecords.isEmpty()) { isPending = false; } } synchronized void saveIndexFile() throws IOException { try (PrintWriter out = new PrintWriter(indexFile, "UTF-8")) { for (AuditIndexRecord auditIndexRecord : indexRecords) { out.println(MiscUtil.stringify(auditIndexRecord)); } } } void appendToDoneFile(AuditIndexRecord indexRecord) throws IOException { logger.info("Moving to done file. {}, queueName={}, consumer={}", indexRecord.getFilePath(), FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(indexDoneFile, true), StandardCharsets.UTF_8)))) { String line = MiscUtil.stringify(indexRecord); out.println(line); out.flush(); } // After Each file is read and audit events are pushed into pipe, we flush to reach the destination immediate. consumerProvider.flush(); // Move to archive folder File logFile = null; File archiveFile = null; try { logFile = new File(indexRecord.getFilePath()); archiveFile = new File(archiveFolder, logFile.getName()); logger.info("Moving logFile {} to {}", logFile, archiveFile); boolean result = logFile.renameTo(archiveFile); if (!result) { logger.error("Error moving log file to archive folder. Unable to rename={} to archiveFile={}", logFile, archiveFile); } } catch (Throwable t) { logger.error("Error moving log file to archive folder. logFile={}, archiveFile={}", logFile, archiveFile, t); } // After archiving the file flush the pipe consumerProvider.flush(); archiveFile = null; try { // Remove old files File[] logFiles = archiveFolder.listFiles(pathname -> pathname.getName().toLowerCase().endsWith(".log")); if (logFiles != null && logFiles.length > maxArchiveFiles) { int filesToDelete = logFiles.length - maxArchiveFiles; try (BufferedReader br = new BufferedReader(new FileReader(indexDoneFile))) { int filesDeletedCount = 0; for (String line = br.readLine(); line != null; line = br.readLine()) { if (!line.isEmpty() && !line.startsWith("#")) { try { AuditIndexRecord record = MiscUtil.fromJson(line, AuditIndexRecord.class); if (record == null) { continue; } logFile = new File(record.getFilePath()); archiveFile = new File(archiveFolder, logFile.getName()); if (archiveFile.exists()) { logger.info("Deleting archive file {}", archiveFile); boolean ret = archiveFile.delete(); if (!ret) { logger.error("Error deleting archive file. archiveFile={}", archiveFile); } filesDeletedCount++; if (filesDeletedCount >= filesToDelete) { logger.info("Deleted {} files", filesDeletedCount); break; } } } catch (Exception e) { logger.error("Error parsing following JSON: {}", line, e); } } } } } } catch (Throwable t) { logger.error("Error deleting older archive file. archiveFile={}", archiveFile, t); } } void logError(String msg) { long currTimeMS = System.currentTimeMillis(); if (currTimeMS - lastErrorLogMS > errorLogIntervalMS) { logger.error(msg); lastErrorLogMS = currTimeMS; } } /** * This return the current file. If there are not current open output file, * then it will return null * * @return */ private synchronized PrintWriter getOpenLogFileStream() { return logWriter; } /** * @return * @throws Exception */ private synchronized PrintWriter getLogFileStream() throws Exception { closeFileIfNeeded(); // Either there are no open log file or the previous one has been rolled over if (currentWriterIndexRecord == null) { Date currentTime = new Date(); // Create a new file String fileName = MiscUtil.replaceTokens(logFileNameFormat, currentTime.getTime()); String newFileName = fileName; File outLogFile; int i = 0; while (true) { outLogFile = new File(logFolder, newFileName); File archiveLogFile = new File(archiveFolder, newFileName); if (!outLogFile.exists() && !archiveLogFile.exists()) { break; } i++; int lastDot = fileName.lastIndexOf('.'); String baseName = fileName.substring(0, lastDot); String extension = fileName.substring(lastDot); newFileName = baseName + "." + i + extension; } fileName = newFileName; logger.info("Creating new file. queueName={}, fileName={}", FILE_QUEUE_PROVIDER_NAME, fileName); // Open the file logWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outLogFile), StandardCharsets.UTF_8))); AuditIndexRecord tmpIndexRecord = new AuditIndexRecord(); tmpIndexRecord.setId(MiscUtil.generateUniqueId()); tmpIndexRecord.setFilePath(outLogFile.getPath()); tmpIndexRecord.setStatus(SPOOL_FILE_STATUS.write_inprogress); tmpIndexRecord.setFileCreateTime(currentTime); tmpIndexRecord.setLastAttempt(true); currentWriterIndexRecord = tmpIndexRecord; indexRecords.add(currentWriterIndexRecord); saveIndexFile(); } else { if (logWriter == null) { // This means the process just started. We need to open the file in append mode. logger.info("Opening existing file for append. queueName={}, fileName={}", FILE_QUEUE_PROVIDER_NAME, currentWriterIndexRecord.getFilePath()); logWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(currentWriterIndexRecord.getFilePath(), true), StandardCharsets.UTF_8))); } } return logWriter; } private synchronized void closeFileIfNeeded() throws IOException { // Is there file open to write or there are no pending file, then close // the active file if (currentWriterIndexRecord != null) { // Check whether the file needs to rolled rollOverSpoolFileByTime(); if (closeFile) { // Roll the file if (logWriter != null) { logWriter.flush(); logWriter.close(); logWriter = null; closeFile = false; } currentWriterIndexRecord.setStatus(SPOOL_FILE_STATUS.pending); currentWriterIndexRecord.setWriteCompleteTime(new Date()); saveIndexFile(); logger.info("Adding file to queue. queueName={}, fileName={}", FILE_QUEUE_PROVIDER_NAME, currentWriterIndexRecord.getFilePath()); indexQueue.add(currentWriterIndexRecord); currentWriterIndexRecord = null; } } } private void rollOverSpoolFileByTime() { if (System.currentTimeMillis() - currentWriterIndexRecord.getFileCreateTime().getTime() > (fileRolloverSec * 1000L)) { closeFile = true; logger.info("Closing file. Rolling over. queueName={}, fileName={}", FILE_QUEUE_PROVIDER_NAME, currentWriterIndexRecord.getFilePath()); } } private void logEvent(BufferedReader br) throws Exception { int currLine = 0; int startLine = currentConsumerIndexRecord.getLinePosition(); List<AuditEventBase> events = new ArrayList<>(); for (String line = br.readLine(); line != null; line = br.readLine()) { currLine++; if (currLine < startLine) { continue; } AuditEventBase event = MiscUtil.fromJson(line, AuthzAuditEvent.class); events.add(event); if (events.size() == bufferSize) { boolean ret = sendEvent(events, currentConsumerIndexRecord, currLine); if (!ret) { throw new Exception("Destination down"); } events.clear(); } } if (!events.isEmpty()) { boolean ret = sendEvent(events, currentConsumerIndexRecord, currLine); if (!ret) { throw new Exception("Destination down"); } events.clear(); } } private boolean sendEvent(List<AuditEventBase> events, AuditIndexRecord indexRecord, int currLine) { boolean ret = true; try { ret = consumerProvider.log(events); if (!ret) { // Need to log error after fixed interval logError("Error sending logs to consumer. provider=" + FILE_QUEUE_PROVIDER_NAME + ", consumer=" + consumerProvider.getName()); } else { // Update index and save indexRecord.setLinePosition(currLine); indexRecord.setStatus(SPOOL_FILE_STATUS.read_inprogress); indexRecord.setLastSuccessTime(new Date()); indexRecord.setLastAttempt(true); saveIndexFile(); if (isDestDown) { isDestDown = false; logger.info("Destination up now. {}, queueName={}, consumer={}", indexRecord.getFilePath(), FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); } } } catch (Throwable t) { logger.error("Error while sending logs to consumer. provider={}, consumer={}, log={}", FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName(), events, t); } return ret; } private void logFile(File file) throws Exception { logger.debug("==> AuditFileQueueSpool.logFile()"); int currLine = 0; int startLine = currentConsumerIndexRecord.getLinePosition(); if (currLine < startLine) { currLine++; } boolean ret = sendFile(file, currentConsumerIndexRecord, currLine); if (!ret) { throw new Exception("Destination down"); } logger.debug("<== AuditFileQueueSpool.logFile()"); } private boolean sendFile(File file, AuditIndexRecord indexRecord, int currLine) { boolean ret = true; logger.debug("==> AuditFileQueueSpool.sendFile()"); try { ret = consumerProvider.logFile(file); if (!ret) { // Need to log error after fixed interval logError("Error sending log file to consumer. provider=" + FILE_QUEUE_PROVIDER_NAME + ", consumer=" + consumerProvider.getName() + ", logFile=" + file.getName()); } else { // Update index and save indexRecord.setLinePosition(currLine); indexRecord.setStatus(SPOOL_FILE_STATUS.read_inprogress); indexRecord.setLastSuccessTime(new Date()); indexRecord.setLastAttempt(true); saveIndexFile(); if (isDestDown) { isDestDown = false; logger.info("Destination up now. {}, queueName={}, consumer={}", indexRecord.getFilePath(), FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName()); } } } catch (Throwable t) { logger.error("Error sending log file to consumer. provider={}, consumer={}, logFile={}", FILE_QUEUE_PROVIDER_NAME, consumerProvider.getName(), file.getName(), t); } logger.debug("<== AuditFileQueueSpool.sendFile() {}", ret); return ret; } }
apache/hadoop
36,654
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/yarn/server/scheduler/TestDistributedOpportunisticContainerAllocator.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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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.scheduler; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ExecutionType; import org.apache.hadoop.yarn.api.records.ExecutionTypeRequest; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceBlacklistRequest; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.api.protocolrecords.RemoteNode; import org.apache.hadoop.yarn.server.api.records.MasterKey; import org.apache.hadoop.yarn.server.metrics.OpportunisticSchedulerMetrics; import org.apache.hadoop.yarn.server.security.BaseContainerTokenSecretManager; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; 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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test cases for DistributedOpportunisticContainerAllocator. */ public class TestDistributedOpportunisticContainerAllocator { private static final Logger LOG = LoggerFactory.getLogger( TestDistributedOpportunisticContainerAllocator.class); private static final int GB = 1024; private DistributedOpportunisticContainerAllocator allocator = null; private OpportunisticContainerContext oppCntxt = null; private static final Priority PRIORITY_NORMAL = Priority.newInstance(1); private static final Resource CAPABILITY_1GB = Resources.createResource(1 * GB); private static final ExecutionTypeRequest OPPORTUNISTIC_REQ = ExecutionTypeRequest.newInstance(ExecutionType.OPPORTUNISTIC, true); @BeforeEach public void setup() { SecurityUtil.setTokenServiceUseIp(false); final MasterKey mKey = new MasterKey() { @Override public int getKeyId() { return 1; } @Override public void setKeyId(int keyId) {} @Override public ByteBuffer getBytes() { return ByteBuffer.allocate(8); } @Override public void setBytes(ByteBuffer bytes) {} }; BaseContainerTokenSecretManager secMan = new BaseContainerTokenSecretManager(new Configuration()) { @Override public MasterKey getCurrentKey() { return mKey; } @Override public byte[] createPassword(ContainerTokenIdentifier identifier) { return new byte[]{1, 2}; } }; allocator = new DistributedOpportunisticContainerAllocator(secMan); oppCntxt = new OpportunisticContainerContext(); oppCntxt.getAppParams().setMinResource(Resource.newInstance(1024, 1)); oppCntxt.getAppParams().setIncrementResource(Resource.newInstance(512, 1)); oppCntxt.getAppParams().setMaxResource(Resource.newInstance(1024, 10)); } @Test public void testSimpleAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList(ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 1, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); assertEquals(1, containers.size()); assertEquals(0, oppCntxt.getOutstandingOpReqs().size()); } @Test public void testBlacklistRejection() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( Arrays.asList("h1", "h2"), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList(ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 1, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); assertEquals(0, containers.size()); assertEquals(1, oppCntxt.getOutstandingOpReqs().size()); } @Test public void testRoundRobinSimpleAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().allocationRequestId(1) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(3) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); LOG.info("Containers: {}", containers); Set<String> allocatedHosts = new HashSet<>(); for (Container c : containers) { allocatedHosts.add(c.getNodeHttpAddress()); } assertTrue(allocatedHosts.contains("h1:1234")); assertTrue(allocatedHosts.contains("h2:1234")); assertTrue(allocatedHosts.contains("h3:1234")); assertEquals(3, containers.size()); } @Test public void testNodeLocalAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().allocationRequestId(1) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName("/r1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(3) .priority(PRIORITY_NORMAL) .resourceName("/r1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(3) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(3) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); LOG.info("Containers: {}", containers); // all 3 containers should be allocated. assertEquals(3, containers.size()); // container with allocation id 2 and 3 should be allocated on node h1 for (Container c : containers) { if (c.getAllocationRequestId() == 2 || c.getAllocationRequestId() == 3) { assertEquals("h1:1234", c.getNodeHttpAddress()); } } } @Test public void testNodeLocalAllocationSameSchedKey() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().allocationRequestId(2) .numContainers(2) .priority(PRIORITY_NORMAL) .resourceName("/r1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .numContainers(2) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .numContainers(2) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); LOG.info("Containers: {}", containers); Set<String> allocatedHosts = new HashSet<>(); for (Container c : containers) { allocatedHosts.add(c.getNodeHttpAddress()); } assertEquals(2, containers.size()); assertTrue(allocatedHosts.contains("h1:1234")); assertFalse(allocatedHosts.contains("h2:1234")); assertFalse(allocatedHosts.contains("h3:1234")); } @Test public void testSimpleRackLocalAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 1, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "h1", CAPABILITY_1GB, 1, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "/r1", CAPABILITY_1GB, 1, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); Set<String> allocatedHosts = new HashSet<>(); for (Container c : containers) { allocatedHosts.add(c.getNodeHttpAddress()); } assertTrue(allocatedHosts.contains("h2:1234")); assertFalse(allocatedHosts.contains("h3:1234")); assertFalse(allocatedHosts.contains("h4:1234")); assertEquals(1, containers.size()); } @Test public void testRoundRobinRackLocalAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().allocationRequestId(1) .priority(PRIORITY_NORMAL) .resourceName("/r1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(1) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(1) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName("/r1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build(), ResourceRequest.newBuilder().allocationRequestId(2) .priority(PRIORITY_NORMAL) .resourceName(ResourceRequest.ANY) .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); Set<String> allocatedHosts = new HashSet<>(); for (Container c : containers) { allocatedHosts.add(c.getNodeHttpAddress()); } LOG.info("Containers: {}", containers); assertTrue(allocatedHosts.contains("h2:1234")); assertTrue(allocatedHosts.contains("h5:1234")); assertFalse(allocatedHosts.contains("h3:1234")); assertFalse(allocatedHosts.contains("h4:1234")); assertEquals(2, containers.size()); } @Test public void testRoundRobinRackLocalAllocationSameSchedKey() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "h1", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "/r1", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); Set<String> allocatedHosts = new HashSet<>(); for (Container c : containers) { allocatedHosts.add(c.getNodeHttpAddress()); } LOG.info("Containers: {}", containers); assertTrue(allocatedHosts.contains("h2:1234")); assertTrue(allocatedHosts.contains("h5:1234")); assertFalse(allocatedHosts.contains("h3:1234")); assertFalse(allocatedHosts.contains("h4:1234")); assertEquals(2, containers.size()); } @Test public void testOffSwitchAllocationWhenNoNodeOrRack() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "h6", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "/r3", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); LOG.info("Containers: {}", containers); assertEquals(2, containers.size()); } @Test public void testLotsOfContainersRackLocalAllocationSameSchedKey() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 1000, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "h1", CAPABILITY_1GB, 1000, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "/r1", CAPABILITY_1GB, 1000, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = new ArrayList<>(); for (int i = 0; i < 250; i++) { containers.addAll(allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser")); } assertEquals(1000, containers.size()); } @Test public void testLotsOfContainersRackLocalAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = new ArrayList<>(); for (int i = 0; i < 100; i++) { reqs.add(ResourceRequest.newBuilder().allocationRequestId(i + 1) .priority(PRIORITY_NORMAL) .resourceName("*") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); reqs.add(ResourceRequest.newBuilder().allocationRequestId(i + 1) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); reqs.add(ResourceRequest.newBuilder().allocationRequestId(i + 1) .priority(PRIORITY_NORMAL) .resourceName("/r1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); } ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = new ArrayList<>(); for (int i = 0; i < 25; i++) { containers.addAll(allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser")); } assertEquals(100, containers.size()); } @Test public void testAllocationWithNodeLabels() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList(ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 1, true, "label", OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); /* Since there is no node satisfying node label constraints, requests won't get fulfilled. */ assertEquals(0, containers.size()); assertEquals(1, oppCntxt.getOutstandingOpReqs().size()); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1", "label"))); containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); assertEquals(1, containers.size()); assertEquals(0, oppCntxt.getOutstandingOpReqs().size()); } /** * Tests maximum number of opportunistic containers that can be allocated in * AM heartbeat. * @throws Exception */ @Test public void testMaxAllocationsPerAMHeartbeat() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); allocator.setMaxAllocationsPerAMHeartbeat(2); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 3, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "h6", CAPABILITY_1GB, 3, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "/r3", CAPABILITY_1GB, 3, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "user1"); LOG.info("Containers: {}", containers); // Although capacity is present, but only 2 containers should be allocated // as max allocation per AM heartbeat is set to 2. assertEquals(2, containers.size()); containers = allocator.allocateContainers( blacklistRequest, new ArrayList<>(), appAttId, oppCntxt, 1L, "user1"); LOG.info("Containers: {}", containers); // Remaining 1 container should be allocated. assertEquals(1, containers.size()); } /** * Tests maximum opportunistic container allocation per AM heartbeat for * allocation requests with different scheduler key. * @throws Exception */ @Test public void testMaxAllocationsPerAMHeartbeatDifferentSchedKey() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); allocator.setMaxAllocationsPerAMHeartbeat(2); final ExecutionTypeRequest oppRequest = ExecutionTypeRequest.newInstance( ExecutionType.OPPORTUNISTIC, true); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(Priority.newInstance(1), "*", CAPABILITY_1GB, 1, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(Priority.newInstance(2), "h6", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(Priority.newInstance(3), "/r3", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "user1"); LOG.info("Containers: {}", containers); // Although capacity is present, but only 2 containers should be allocated // as max allocation per AM heartbeat is set to 2. assertEquals(2, containers.size()); containers = allocator.allocateContainers( blacklistRequest, new ArrayList<>(), appAttId, oppCntxt, 1L, "user1"); LOG.info("Containers: {}", containers); // 2 more containers should be allocated from pending allocation requests. assertEquals(2, containers.size()); containers = allocator.allocateContainers( blacklistRequest, new ArrayList<>(), appAttId, oppCntxt, 1L, "user1"); LOG.info("Containers: {}", containers); // Remaining 1 container should be allocated. assertEquals(1, containers.size()); } /** * Tests maximum opportunistic container allocation per AM heartbeat when * limit is set to -1. * @throws Exception */ @Test public void testMaxAllocationsPerAMHeartbeatWithNoLimit() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); allocator.setMaxAllocationsPerAMHeartbeat(-1); List<ResourceRequest> reqs = new ArrayList<>(); for (int i = 0; i < 20; i++) { reqs.add(ResourceRequest.newBuilder().allocationRequestId(i + 1) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); } ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "user1"); // all containers should be allocated in single heartbeat. assertEquals(20, containers.size()); } /** * Tests maximum opportunistic container allocation per AM heartbeat when * limit is set to higher value. * @throws Exception */ @Test public void testMaxAllocationsPerAMHeartbeatWithHighLimit() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); allocator.setMaxAllocationsPerAMHeartbeat(100); List<ResourceRequest> reqs = new ArrayList<>(); for (int i = 0; i < 20; i++) { reqs.add(ResourceRequest.newBuilder().allocationRequestId(i + 1) .priority(PRIORITY_NORMAL) .resourceName("h1") .capability(CAPABILITY_1GB) .relaxLocality(true) .executionType(ExecutionType.OPPORTUNISTIC).build()); } ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h1", 1234), "h1:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "user1"); // all containers should be allocated in single heartbeat. assertEquals(20, containers.size()); } /** * Test opportunistic container allocation latency metrics. * @throws Exception */ @Test public void testAllocationLatencyMetrics() throws Exception { oppCntxt = spy(oppCntxt); OpportunisticSchedulerMetrics metrics = mock(OpportunisticSchedulerMetrics.class); when(oppCntxt.getOppSchedulerMetrics()).thenReturn(metrics); ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( Collections.emptyList(), Collections.emptyList()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newInstance(PRIORITY_NORMAL, "*", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "h6", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ), ResourceRequest.newInstance(PRIORITY_NORMAL, "/r3", CAPABILITY_1GB, 2, true, null, OPPORTUNISTIC_REQ)); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(0L, 1), 1); oppCntxt.updateNodeList( Arrays.asList( RemoteNode.newInstance( NodeId.newInstance("h3", 1234), "h3:1234", "/r2"), RemoteNode.newInstance( NodeId.newInstance("h2", 1234), "h2:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h5", 1234), "h5:1234", "/r1"), RemoteNode.newInstance( NodeId.newInstance("h4", 1234), "h4:1234", "/r2"))); List<Container> containers = allocator.allocateContainers( blacklistRequest, reqs, appAttId, oppCntxt, 1L, "luser"); LOG.info("Containers: {}", containers); assertEquals(2, containers.size()); // for each allocated container, latency should be added. verify(metrics, times(2)).addAllocateOLatencyEntry(anyLong()); } }
apache/ofbiz
36,198
framework/base/src/main/java/org/apache/ofbiz/base/util/test/ObjectTypeTests.java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.apache.ofbiz.base.util.test; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import org.apache.ofbiz.base.lang.SourceMonitored; import org.apache.ofbiz.base.test.GenericTestCaseBase; import org.apache.ofbiz.base.util.GeneralException; import org.apache.ofbiz.base.util.ObjectType; import org.apache.ofbiz.base.util.TimeDuration; import org.apache.ofbiz.base.util.UtilDateTime; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilXml; import org.w3c.dom.Document; import com.ibm.icu.util.Calendar; @SourceMonitored public class ObjectTypeTests extends GenericTestCaseBase { public static final String module = ObjectTypeTests.class.getName(); private static final LocaleData localeData = new LocaleData("en_US", "Pacific/Wake", "fr", "GMT"); private final TimeDuration duration = new TimeDuration(0, 0, 0, 1, 1, 1, 1); // These numbers are all based on 1 / 128, which is a binary decimal // that can be represented by both float and double private final BigDecimal dcml = new BigDecimal("781.25"); private final Double dbl = Double.valueOf("7.8125E2"); private final Float flt = Float.valueOf("7.8125E2"); private final Long lng = Long.valueOf("781"); private final Integer intg = Integer.valueOf("781"); private final Timestamp tstmp = new Timestamp(781L); private final Timestamp ntstmp; private final java.util.Date utlDt = new java.util.Date(781); private final java.sql.Date sqlDt; private final java.sql.Time sqlTm = new java.sql.Time(2096000); private final List<Object> list; private final Map<String, Object> map; private final Set<Object> set; public ObjectTypeTests(String name) { super(name); ntstmp = new Timestamp(781L); ntstmp.setNanos(123000000); list = new ArrayList<Object>(); list.add("one"); list.add("two"); list.add("three"); map = new LinkedHashMap<String, Object>(); map.put("one", "1"); map.put("two", "2"); map.put("three", "3"); set = new LinkedHashSet<Object>(list); Calendar cal = UtilDateTime.getCalendarInstance(localeData.goodTimeZone, localeData.goodLocale); cal.set(1969, Calendar.DECEMBER, 31, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); sqlDt = new java.sql.Date(cal.getTimeInMillis()); } public static class LocaleData { public final Locale goodLocale; public final TimeZone goodTimeZone; public final Locale badLocale; public final TimeZone badTimeZone; public LocaleData(String goodLocale, String goodTimeZone, String badLocale, String badTimeZone) { this.goodLocale = UtilMisc.parseLocale(goodLocale); this.goodTimeZone = TimeZone.getTimeZone(goodTimeZone); this.badLocale = UtilMisc.parseLocale(badLocale); this.badTimeZone = TimeZone.getTimeZone(badTimeZone); } } public static Object simpleTypeConvert(Object obj, String type, String format, TimeZone timeZone, Locale locale, boolean noTypeFail) throws GeneralException { return ObjectType.simpleTypeConvert(obj, type, format, timeZone, locale, noTypeFail); } public static void simpleTypeConvertTest(String label, Object toConvert, String type, Object wanted) throws GeneralException { basicTest(label, toConvert); assertEquals(label + ":null target type", toConvert, simpleTypeConvert(toConvert, null, null, null, null, true)); assertEquals(label + ":null source object", (Object) null, simpleTypeConvert(null, type, null, null, null, true)); assertEquals(label, wanted, simpleTypeConvert(toConvert, type, null, null, null, true)); if (toConvert instanceof String) { String str = (String) toConvert; Document doc = UtilXml.makeEmptyXmlDocument(); assertEquals(label + ":text-node proxy", wanted, simpleTypeConvert(doc.createTextNode(str), type, null, null, null, true)); } } public static void simpleTypeConvertTest(String label, Object toConvert, String type, String format, LocaleData localeData, Object wanted) throws GeneralException { basicTest(label, toConvert); Locale defaultLocale = Locale.getDefault(); TimeZone defaultTimeZone = TimeZone.getDefault(); try { Locale.setDefault(localeData.goodLocale); TimeZone.setDefault(localeData.goodTimeZone); assertEquals(label + ":default-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, null, null, true)); assertNotEquals(label + ":bad-passed-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, localeData.badTimeZone, localeData.badLocale, true)); Locale.setDefault(localeData.badLocale); TimeZone.setDefault(localeData.badTimeZone); assertNotEquals(label + ":bad-default-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, null, null, true)); assertEquals(label + ":passed-timezone/locale", wanted, simpleTypeConvert(toConvert, type, format, localeData.goodTimeZone, localeData.goodLocale, true)); } finally { Locale.setDefault(defaultLocale); TimeZone.setDefault(defaultTimeZone); } } public static void simpleTypeConvertTestSingleMulti(String label, Object toConvert, String[] types, Object wanted) throws GeneralException { for (int j = 0; j < types.length; j++) { simpleTypeConvertTest(label + "(:" + j + ")", toConvert, types[j], wanted); } } public static void simpleTypeConvertTestMultiMulti(String label, Object[] toConvert, String[] types, Object wanted) throws GeneralException { for (int i = 0; i < toConvert.length; i++) { for (int j = 0; j < types.length; j++) { simpleTypeConvertTest(label + "(" + i + ":" + j + ")", toConvert[i], types[j], wanted); } } } public static void simpleTypeConvertTestSingleMulti(String label, Object toConvert, String[] types, String format, LocaleData localeData, Object wanted) throws GeneralException { for (int j = 0; j < types.length; j++) { simpleTypeConvertTest(label + "(:" + j + ")", toConvert, types[j], format, localeData, wanted); } } public static void simpleTypeConvertTestMultiMulti(String label, Object[] toConvert, String[] types, String format, LocaleData localeData, Object wanted) throws GeneralException { for (int i = 0; i < toConvert.length; i++) { for (int j = 0; j < types.length; j++) { simpleTypeConvertTest(label + "(" + i + ":" + j + ")", toConvert[i], types[j], format, localeData, wanted); } } } public static void simpleTypeConvertTestError(String label, Object toConvert, String type) throws GeneralException { GeneralException caught = null; try { simpleTypeConvert(toConvert, type, null, null, null, true); } catch (GeneralException e) { caught = e; } finally { assertNotNull(label + ":caught", caught); } } public static void simpleTypeConvertTestError(String label, Object toConvert, String[] types) throws GeneralException { simpleTypeConvertTestError(label + ":this", toConvert, GeneralException.class.getName()); for (String type: types) { simpleTypeConvertTestError(label + ":" + type, toConvert, type); } } public static void simpleTypeConvertTestNoError(String label, Object toConvert, String type) throws GeneralException { assertSame(label, toConvert, simpleTypeConvert(toConvert, type, null, null, null, false)); } public static void simpleTypeConvertTestNoError(String label, Object toConvert, String[] types) throws GeneralException { simpleTypeConvertTestNoError(label + ":this", toConvert, GeneralException.class.getName()); for (String type: types) { simpleTypeConvertTestNoError(label + ":" + type, toConvert, type); } } public static void basicTest(String label, Object toConvert) throws GeneralException { assertEquals(label + ":PlainString", toConvert.toString(), simpleTypeConvert(toConvert, "PlainString", null, null, null, true)); assertSame(label + ":same", toConvert, simpleTypeConvert(toConvert, toConvert.getClass().getName(), null, null, null, true)); assertSame(label + ":to-Object", toConvert, simpleTypeConvert(toConvert, "Object", null, null, null, true)); assertSame(label + ":to-java.lang.Object", toConvert, simpleTypeConvert(toConvert, "java.lang.Object", null, null, null, true)); } public void testLoadClassWithNonExistentClass() { Exception exception = null; try { ObjectType.loadClass("foobarbaz"); } catch (Exception e) { exception = e; } assertTrue("Exception thrown by loadClass(\"foobarbaz\") is not ClassNotFoundException", exception instanceof ClassNotFoundException); } public void testLoadClassWithPrimitives() { try { Class<?> theClass; theClass = ObjectType.loadClass("boolean"); assertEquals("Wrong class returned by loadClass(\"boolean\")", (Boolean.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("short"); assertEquals("Wrong class returned by loadClass(\"short\")", (Short.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("int"); assertEquals("Wrong class returned by loadClass(\"int\")", (Integer.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("long"); assertEquals("Wrong class returned by loadClass(\"long\")", (Long.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("float"); assertEquals("Wrong class returned by loadClass(\"float\")", (Float.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("double"); assertEquals("Wrong class returned by loadClass(\"double\")", (Double.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("byte"); assertEquals("Wrong class returned by loadClass(\"byte\")", (Byte.TYPE).getName(), theClass.getName()); theClass = ObjectType.loadClass("char"); assertEquals("Wrong class returned by loadClass(\"char\")", (Character.TYPE).getName(), theClass.getName()); } catch (Exception e) { fail("Exception thrown by loadClass: " + e.getMessage()); } } public void testLoadClassWithAlias() { try { Class<?> theClass; // first try with a class full name theClass = ObjectType.loadClass("java.lang.String"); assertEquals("Wrong class returned by loadClass(\"java.lang.String\")", "java.lang.String", theClass.getName()); // now try with some aliases theClass = ObjectType.loadClass("String"); assertEquals("Wrong class returned by loadClass(\"String\")", "java.lang.String", theClass.getName()); theClass = ObjectType.loadClass("Object"); assertEquals("Wrong class returned by loadClass(\"Object\")", "java.lang.Object", theClass.getName()); theClass = ObjectType.loadClass("Date"); assertEquals("Wrong class returned by loadClass(\"Date\")", "java.sql.Date", theClass.getName()); } catch (Exception e) { fail("Exception thrown by loadClass: " + e.getMessage()); } } public void testClassNotFound() { GeneralException caught = null; try { ObjectType.simpleTypeConvert(this, "foobarbaz", null, null, null, false); } catch (GeneralException e) { caught = e; } finally { assertNotNull("class not found", caught); } } public void testArray() throws GeneralException { simpleTypeConvertTestSingleMulti("Object[]->List", new Object[] {"one", "two", "three"}, new String[] {"List", "java.util.List"}, list); simpleTypeConvertTestSingleMulti("int[]->List", new int[] {1, 2, 3}, new String[] {"List", "java.util.List"}, list(1, 2, 3)); simpleTypeConvertTestError("Object[]->error", new Object[] {"one", "two", "three"}, new String[] {"Map"}); simpleTypeConvertTestError("int[]->error", new int[] {1, 2, 3}, new String[] {"java.util.ArrayList", "Map"}); } public void testString() throws GeneralException, Exception { simpleTypeConvertTest("String->String", "one", "String", "one"); simpleTypeConvertTest("String->String", "one", "java.lang.String", "one"); simpleTypeConvertTestSingleMulti("empty-String->anything", "", new String[] {"List", "Map"}, null); simpleTypeConvertTestError("String->error", "one", new String[] {}); simpleTypeConvertTestMultiMulti("String->Boolean(true)", new String[] {"true", " true ", " TrUe"}, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.TRUE); simpleTypeConvertTestMultiMulti("String->Boolean(false)", new String[] {"false", " false ", " FaLsE"}, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.FALSE); simpleTypeConvertTestSingleMulti("String->Locale", "en_us", new String[] {"Locale", "java.util.Locale"}, localeData.goodLocale); simpleTypeConvertTestError("String->error-Locale", "o", new String[] {"Locale", "java.util.Locale"}); // TZ can never be null, will default to GMT if it can't be parsed(from the javadocs of java.util.TimeZone) simpleTypeConvertTestSingleMulti("String->TimeZone", "Pacific/Wake", new String[] {"TimeZone", "java.util.TimeZone"}, localeData.goodTimeZone); simpleTypeConvertTestSingleMulti("String->BigDecimal", "78,125E-2", new String[] {"BigDecimal", "java.math.BigDecimal"}, null, localeData, dcml); simpleTypeConvertTestError("String->error-BigDecimal", "o", new String[] {"BigDecimal", "java.math.BigDecimal"}); simpleTypeConvertTestSingleMulti("String->Double", "78,125E-2", new String[] {"Double", "java.lang.Double"}, null, localeData, dbl); simpleTypeConvertTestError("String->error-Double", "o", new String[] {"Double", "java.lang.Double"}); simpleTypeConvertTestSingleMulti("String->Float", "78,125E-2", new String[] {"Float", "java.lang.Float"}, null, localeData, flt); simpleTypeConvertTestError("String->error-Float", "o", new String[] {"Float", "java.lang.Float"}); simpleTypeConvertTestSingleMulti("String->Long", "78,125E-2", new String[] {"Long", "java.lang.Long"}, null, localeData, lng); simpleTypeConvertTestError("String->error-Long", "o", new String[] {"Long", "java.lang.Long"}); simpleTypeConvertTestSingleMulti("String->Integer", "78,125E-2", new String[] {"Integer", "java.lang.Integer"}, null, localeData, intg); simpleTypeConvertTestError("String->error-Integer", "o", new String[] {"Integer", "java.lang.Integer"}); simpleTypeConvertTestSingleMulti("String->java.sql.Date", "1969-12-31", new String[] {"Date", "java.sql.Date"}, null, localeData, sqlDt); simpleTypeConvertTestSingleMulti("String->java.sql.Date", "1969-12-31", new String[] {"Date", "java.sql.Date"}, "", localeData, sqlDt); simpleTypeConvertTestSingleMulti("String->java.sql.Date", "12-31-1969", new String[] {"Date", "java.sql.Date"}, "MM-dd-yyyy", localeData, sqlDt); simpleTypeConvertTestError("String->error-java.sql.Date", "o", new String[] {"Date", "java.sql.Date"}); simpleTypeConvertTestSingleMulti("String->java.sql.Time", "12:34:56", new String[] {"Time", "java.sql.Time"}, null, localeData, sqlTm); simpleTypeConvertTestSingleMulti("String->java.sql.Time", "12:34:56", new String[] {"Time", "java.sql.Time"}, "", localeData, sqlTm); simpleTypeConvertTestSingleMulti("String->java.sql.Time", "563412", new String[] {"Time", "java.sql.Time"}, "ssmmHH", localeData, sqlTm); simpleTypeConvertTestError("String->error-java.sql.Time", "o", new String[] {"Time", "java.sql.Time"}); simpleTypeConvertTestSingleMulti("String->Timestamp", "1970-01-01 12:00:00.123", new String[] {"Timestamp", "java.sql.Timestamp"}, null, localeData, ntstmp); simpleTypeConvertTestSingleMulti("String->Timestamp", "1970-01-01 12:00:00.123", new String[] {"Timestamp", "java.sql.Timestamp"}, "", localeData, ntstmp); simpleTypeConvertTestSingleMulti("String->Timestamp", "01-01-1970 12:00:00/123", new String[] {"Timestamp", "java.sql.Timestamp"}, "dd-MM-yyyy HH:mm:ss/SSS", localeData, ntstmp); simpleTypeConvertTestMultiMulti("String->Timestamp", new String[] {"1970-01-01", "1970-01-01 00:00:00", "1970-01-01 00:00:00.0", "1970-01-01 00:00:00.000"}, new String[] {"Timestamp", "java.sql.Timestamp"}, null, localeData, new Timestamp(-43200000)); simpleTypeConvertTestError("String->error-Timestamp", "o", new String[] {"Timestamp", "java.sql.Timestamp"}); simpleTypeConvertTestSingleMulti("String->List", "[one, two, three]", new String[] {"List", "List<java.lang.String>", "java.util.List"}, list); simpleTypeConvertTestSingleMulti("String->List", "[one, two, three", new String[] {"List", "List<java.lang.String>", "java.util.List"}, list("[one, two, three")); simpleTypeConvertTestSingleMulti("String->List", "one, two, three]", new String[] {"List", "List<java.lang.String>", "java.util.List"}, list("one, two, three]")); simpleTypeConvertTestSingleMulti("String->Set", "[one, two, three]", new String[] {"Set", "Set<java.lang.String>", "java.util.Set"}, set); simpleTypeConvertTestSingleMulti("String->Set", "[one, two, three", new String[] {"Set", "Set<java.lang.String>", "java.util.Set"}, set("[one, two, three")); simpleTypeConvertTestSingleMulti("String->Set", "one, two, three]", new String[] {"Set", "Set<java.lang.String>", "java.util.Set"}, set("one, two, three]")); simpleTypeConvertTestSingleMulti("String->Map", "{one=1, two=2, three=3}", new String[] {"Map", "Map<String, String>", "java.util.Map"}, map); simpleTypeConvertTestError("String->Map(error-1)", "{one=1, two=2, three=3", new String[] {"Map", "java.util.Map"}); simpleTypeConvertTestError("String->Map(error-2)", "one=1, two=2, three=3}", new String[] {"Map", "java.util.Map"}); simpleTypeConvertTestSingleMulti("String->TimeDuration(number)", "3,661,001", new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, null, localeData, duration); simpleTypeConvertTestMultiMulti("String->TimeDuration(string)", new String[] {"1:1:1:1"}, new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, duration); simpleTypeConvertTestError("String->error-TimeDuration", "o", new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}); } public void testDouble() throws GeneralException { simpleTypeConvertTestSingleMulti("Double->String", Double.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); simpleTypeConvertTestSingleMulti("Double->BigDecimal", dbl, new String[] {"BigDecimal", "java.math.BigDecimal"}, dcml); simpleTypeConvertTestSingleMulti("Double->Double", dbl, new String[] {"Double", "java.lang.Double"}, new Double("781.25")); simpleTypeConvertTestSingleMulti("Double->Float", dbl, new String[] {"Float", "java.lang.Float"}, flt); simpleTypeConvertTestSingleMulti("Double->Long", dbl, new String[] {"Long", "java.lang.Long"}, lng); simpleTypeConvertTestSingleMulti("Double->Integer", dbl, new String[] {"Integer", "java.lang.Integer"}, intg); simpleTypeConvertTestSingleMulti("Double->List", dbl, new String[] {"List", "List<java.lang.Double>", "java.util.List"}, list(dbl)); simpleTypeConvertTestSingleMulti("Double->Set", dbl, new String[] {"Set", "Set<java.lang.Double>", "java.util.Set"}, set(dbl)); simpleTypeConvertTestSingleMulti("Double->TimeDuration", Double.valueOf("3661001.25"), new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, duration); simpleTypeConvertTestError("Double->error", dbl, new String[] {}); } public void testFloat() throws GeneralException { // does not support to java.lang variants simpleTypeConvertTestSingleMulti("Float->String", Float.valueOf("1234567"), new String[] {"String"}, null, localeData, "1,234,567"); simpleTypeConvertTestSingleMulti("Float->BigDecimal", flt, new String[] {"BigDecimal", "java.math.BigDecimal"}, dcml); simpleTypeConvertTestSingleMulti("Float->Double", flt, new String[] {"Double", "java.lang.Double"}, dbl); simpleTypeConvertTestSingleMulti("Float->Float", flt, new String[] {"Float", "java.lang.Float"}, new Float("781.25")); simpleTypeConvertTestSingleMulti("Float->Long", flt, new String[] {"Long", "java.lang.Long"}, lng); simpleTypeConvertTestSingleMulti("Float->Integer", flt, new String[] {"Integer", "java.lang.Integer"}, intg); simpleTypeConvertTestSingleMulti("Float->List", flt, new String[] {"List", "List<java.lang.Float>", "java.util.List"}, list(flt)); simpleTypeConvertTestSingleMulti("Float->Set", flt, new String[] {"Set", "Set<java.lang.Float>", "java.util.Set"}, set(flt)); simpleTypeConvertTestSingleMulti("Float->TimeDuration", Float.valueOf("3661001.25"), new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, duration); simpleTypeConvertTestError("Float->error", flt, new String[] {}); } public void testLong() throws GeneralException { simpleTypeConvertTestSingleMulti("Long->String", Long.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); simpleTypeConvertTestSingleMulti("Long->BigDecimal", lng, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781")); simpleTypeConvertTestSingleMulti("Long->Double", lng, new String[] {"Double", "java.lang.Double"}, new Double("781")); simpleTypeConvertTestSingleMulti("Long->Float", lng, new String[] {"Float", "java.lang.Float"}, new Float("781")); simpleTypeConvertTestSingleMulti("Long->Long", lng, new String[] {"Long", "java.lang.Long"}, new Long("781")); simpleTypeConvertTestSingleMulti("Long->Integer", lng, new String[] {"Integer", "java.lang.Integer"}, intg); simpleTypeConvertTestSingleMulti("Long->List", lng, new String[] {"List", "List<java.lang.Long>", "java.util.List"}, list(lng)); simpleTypeConvertTestSingleMulti("Long->Set", lng, new String[] {"Set", "Set<java.lang.Long>", "java.util.Set"}, set(lng)); simpleTypeConvertTestSingleMulti("Long->java.util.Date", 781L, new String[] {"java.util.Date"}, utlDt); simpleTypeConvertTestSingleMulti("Long->Timestamp", lng, new String[] {"Timestamp", "java.sql.Timestamp"}, tstmp); simpleTypeConvertTestSingleMulti("Long->TimeDuration", Long.valueOf("3661001"), new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, duration); simpleTypeConvertTestError("Long->error", lng, new String[] {}); } public void testInteger() throws GeneralException { simpleTypeConvertTestSingleMulti("Integer->String", Integer.valueOf("1234567"), new String[] {"String", "java.lang.String"}, null, localeData, "1,234,567"); simpleTypeConvertTestSingleMulti("Integer->BigDecimal", intg, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781")); simpleTypeConvertTestSingleMulti("Integer->Double", intg, new String[] {"Double", "java.lang.Double"}, new Double("781")); simpleTypeConvertTestSingleMulti("Integer->Float", intg, new String[] {"Float", "java.lang.Float"}, new Float("781")); simpleTypeConvertTestSingleMulti("Integer->Long", intg, new String[] {"Long", "java.lang.Long"}, lng); simpleTypeConvertTestSingleMulti("Integer->Integer", intg, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("781")); simpleTypeConvertTestSingleMulti("Integer->List", intg, new String[] {"List", "List<java.lang.Integer>", "java.util.List"}, list(intg)); simpleTypeConvertTestSingleMulti("Integer->Set", intg, new String[] {"Set", "Set<java.lang.Integer>", "java.util.Set"}, set(intg)); simpleTypeConvertTestSingleMulti("Integer->TimeDuration", Integer.valueOf("3661001"), new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, duration); simpleTypeConvertTestError("Integer->error", intg, new String[] {}); } public void testBigDecimal() throws GeneralException { simpleTypeConvertTestSingleMulti("BigDecimal->String", new BigDecimal("12345.67"), new String[] {"String", "java.lang.String"}, null, localeData, "12,345.67"); simpleTypeConvertTestSingleMulti("BigDecimal->BigDecimal", dcml, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("781.25")); simpleTypeConvertTestSingleMulti("BigDecimal->Double", dcml, new String[] {"Double", "java.lang.Double"}, dbl); simpleTypeConvertTestSingleMulti("BigDecimal->Float", dcml, new String[] {"Float", "java.lang.Float"}, flt); simpleTypeConvertTestSingleMulti("BigDecimal->Long", dcml, new String[] {"Long", "java.lang.Long"}, lng); simpleTypeConvertTestSingleMulti("BigDecimal->Integer", dcml, new String[] {"Integer", "java.lang.Integer"}, intg); simpleTypeConvertTestSingleMulti("BigDecimal->List", dcml, new String[] {"List", "List<java.math.BigDecimal>", "java.util.List"}, list(dcml)); simpleTypeConvertTestSingleMulti("BigDecimal->Set", dcml, new String[] {"Set", "Set<java.math.BigDecimal>", "java.util.Set"}, set(dcml)); simpleTypeConvertTestSingleMulti("BigDecimal->TimeDuration", new BigDecimal("3661001"), new String[] {"TimeDuration", "org.apache.ofbiz.base.util.TimeDuration"}, duration); simpleTypeConvertTestError("BigDecimal->error", dcml, new String[] {}); } public void testSqlDate() throws GeneralException { simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, null, localeData, "1969-12-31"); simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, "", localeData, "1969-12-31"); simpleTypeConvertTestSingleMulti("SqlDate->String", sqlDt, new String[] {"String", "java.lang.String"}, "dd-MM-yyyy", localeData, "31-12-1969"); simpleTypeConvertTestSingleMulti("SqlDate->SqlDate", sqlDt, new String[] {"Date", "java.sql.Date"}, new java.sql.Date(-129600000)); simpleTypeConvertTestSingleMulti("SqlDate->Timestamp", sqlDt, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(-129600000)); simpleTypeConvertTestSingleMulti("SqlDate->List", sqlDt, new String[] {"List", "List<java.sql.Date>", "java.util.List"}, list(sqlDt)); simpleTypeConvertTestSingleMulti("SqlDate->Set", sqlDt, new String[] {"Set", "Set<java.sql.Date>", "java.util.Set"}, set(sqlDt)); simpleTypeConvertTestSingleMulti("SqlDate->Long", sqlDt, new String[] {"Long", "java.lang.Long"}, Long.valueOf("-129600000")); simpleTypeConvertTestError("SqlDate->error", sqlDt, new String[] {"Time", "java.sql.Time"}); } public void testSqlTime() throws GeneralException { simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, null, localeData, "12:34:56"); simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, "", localeData, "12:34:56"); simpleTypeConvertTestSingleMulti("SqlTime->String", sqlTm, new String[] {"String", "java.lang.String"}, "ss:mm:HH", localeData, "56:34:12"); simpleTypeConvertTestSingleMulti("SqlTime->SqlTime", sqlTm, new String[] {"Time", "java.sql.Time"}, new java.sql.Time(2096000)); simpleTypeConvertTestSingleMulti("SqlTime->Timestamp", sqlTm, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(2096000)); simpleTypeConvertTestSingleMulti("SqlTime->List", sqlTm, new String[] {"List", "List<java.sql.Time>", "java.util.List"}, list(sqlTm)); simpleTypeConvertTestSingleMulti("SqlTime->Set", sqlTm, new String[] {"Set", "Set<java.sql.Time>", "java.util.Set"}, set(sqlTm)); simpleTypeConvertTestError("SqlTime->error", sqlTm, new String[] {"Date", "java.sql.Date"}); } public void testTimestamp() throws GeneralException { simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, null, localeData, "1970-01-01 12:00:00.781"); simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, "", localeData, "1970-01-01 12:00:00.781"); simpleTypeConvertTestSingleMulti("Timestamp->String", tstmp, new String[] {"String", "java.lang.String"}, "dd-MM-yyyy HH:mm:ss/SSS", localeData, "01-01-1970 12:00:00/781"); simpleTypeConvertTestSingleMulti("Timestamp->Date", tstmp, new String[] {"Date", "java.sql.Date"}, new java.sql.Date(781)); simpleTypeConvertTestSingleMulti("Timestamp->Time", tstmp, new String[] {"Time", "java.sql.Time"}, new java.sql.Time(781)); simpleTypeConvertTestSingleMulti("Timestamp->Timestamp", tstmp, new String[] {"Timestamp", "java.sql.Timestamp"}, new Timestamp(781)); simpleTypeConvertTestSingleMulti("Timestamp->List", tstmp, new String[] {"List", "List<java.sql.Timestamp>", "java.util.List"}, list(tstmp)); simpleTypeConvertTestSingleMulti("Timestamp->Set", tstmp, new String[] {"Set", "Set<java.sql.Timestamp>", "java.util.Set"}, set(tstmp)); simpleTypeConvertTestSingleMulti("Timestamp->Long", tstmp, new String[] {"Long", "java.lang.Long"}, Long.valueOf("781")); simpleTypeConvertTestError("Timestamp->error", tstmp, new String[] {}); } public void testBoolean() throws GeneralException { simpleTypeConvertTestSingleMulti("Boolean->Boolean", true, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.TRUE); simpleTypeConvertTestSingleMulti("Boolean->Boolean", false, new String[] {"Boolean", "java.lang.Boolean"}, Boolean.FALSE); simpleTypeConvertTestSingleMulti("Boolean->String", true, new String[] {"String", "java.lang.String"}, "true"); simpleTypeConvertTestSingleMulti("Boolean->String", false, new String[] {"String", "java.lang.String"}, "false"); simpleTypeConvertTestSingleMulti("Boolean->Integer", true, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("1")); simpleTypeConvertTestSingleMulti("Boolean->Integer", false, new String[] {"Integer", "java.lang.Integer"}, Integer.valueOf("0")); simpleTypeConvertTestSingleMulti("Boolean->List", true, new String[] {"List", "List<java.lang.Boolean>", "java.util.List"}, list(true)); simpleTypeConvertTestSingleMulti("Boolean->Set", true, new String[] {"Set", "Set<java.lang.Boolean>", "java.util.Set"}, set(true)); simpleTypeConvertTestError("Boolean->error", true, new String[] {}); } public void testLocale() throws GeneralException { simpleTypeConvertTestSingleMulti("Locale->Locale", localeData.goodLocale, new String[] {"Locale", "java.util.Locale"}, localeData.goodLocale); simpleTypeConvertTestSingleMulti("Locale->String", localeData.goodLocale, new String[] {"String", "java.lang.String"}, localeData.goodLocale.toString()); simpleTypeConvertTestError("Locale->error", localeData.goodLocale, new String[] {}); } public void testTimeZone() throws GeneralException { simpleTypeConvertTestSingleMulti("TimeZone->TimeZone", localeData.goodTimeZone, new String[] {"TimeZone", "java.util.TimeZone"}, localeData.goodTimeZone); simpleTypeConvertTestSingleMulti("TimeZone->String", localeData.goodTimeZone, new String[] {"String", "java.lang.String"}, localeData.goodTimeZone.getID()); simpleTypeConvertTestError("TimeZone->error", localeData.goodTimeZone, new String[] {}); } public void testMap() throws GeneralException { simpleTypeConvertTestSingleMulti("Map->Map", map, new String[] {"Map", "java.util.Map"}, map("one", "1", "two", "2", "three", "3")); simpleTypeConvertTestSingleMulti("Map->String", map, new String[] {"String", "java.lang.String"}, "{one=1, two=2, three=3}"); simpleTypeConvertTestSingleMulti("Map->List", map, new String[] {"List", "List<java.util.Map>", "java.util.List"}, list(map)); simpleTypeConvertTestSingleMulti("Map->Set", map, new String[] {"Set", "Set<java.util.Map>", "java.util.Set"}, set(map)); simpleTypeConvertTestError("Map->error", map, new String[] {}); } public void testList() throws GeneralException { simpleTypeConvertTestSingleMulti("List->String", list, new String[] {"String", "java.lang.String"}, "[one, two, three]"); simpleTypeConvertTestSingleMulti("List->List", list, new String[] {"List", "java.util.List"}, list("one", "two", "three")); simpleTypeConvertTestError("List->error", list, new String[] {}); } // Node tests are done for all String-> conversions // org.w3c.dom.Node public void testTimeDuration() throws GeneralException { simpleTypeConvertTestSingleMulti("TimeDuration->String", duration, new String[] {"String", "java.lang.String"}, "0:0:0:1:1:1:1"); simpleTypeConvertTestSingleMulti("TimeDuration->BigDecimal", duration, new String[] {"BigDecimal", "java.math.BigDecimal"}, new BigDecimal("3661001")); simpleTypeConvertTestSingleMulti("TimeDuration->Double", duration, new String[] {"Double", "java.lang.Double"}, Double.valueOf("3661001")); simpleTypeConvertTestSingleMulti("TimeDuration->Float", duration, new String[] {"Float", "java.lang.Float"}, Float.valueOf("3661001")); simpleTypeConvertTestSingleMulti("TimeDuration->Long", duration, new String[] {"Long", "java.lang.Long"}, Long.valueOf("3661001")); simpleTypeConvertTestSingleMulti("TimeDuration->List", duration, new String[] {"List", "java.util.List"}, list(duration)); simpleTypeConvertTestSingleMulti("TimeDuration->Set", duration, new String[] {"Set", "java.util.Set"}, set(duration)); simpleTypeConvertTestError("TimeDuration->error", duration, new String[] {}); } public void testOther() throws GeneralException { simpleTypeConvertTestSingleMulti("this->String", this, new String[] {"String", "java.lang.String"}, this.toString()); simpleTypeConvertTestError("this->error", this, new String[] {"List", "Map", "Date"}); simpleTypeConvertTestNoError("this->no-error", this, new String[] {"List", "Map", "Date"}); } }
googleapis/google-cloud-java
36,863
java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/FirebaseLink.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1alpha/resources.proto // Protobuf Java Version: 3.25.8 package com.google.analytics.admin.v1alpha; /** * * * <pre> * A link between a Google Analytics property and a Firebase project. * </pre> * * Protobuf type {@code google.analytics.admin.v1alpha.FirebaseLink} */ public final class FirebaseLink extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.FirebaseLink) FirebaseLinkOrBuilder { private static final long serialVersionUID = 0L; // Use FirebaseLink.newBuilder() to construct. private FirebaseLink(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FirebaseLink() { name_ = ""; project_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FirebaseLink(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.ResourcesProto .internal_static_google_analytics_admin_v1alpha_FirebaseLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.ResourcesProto .internal_static_google_analytics_admin_v1alpha_FirebaseLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.FirebaseLink.class, com.google.analytics.admin.v1alpha.FirebaseLink.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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 PROJECT_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object project_ = ""; /** * * * <pre> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</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> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</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 CREATE_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } 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(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, project_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getCreateTime()); } 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(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, project_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCreateTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.analytics.admin.v1alpha.FirebaseLink)) { return super.equals(obj); } com.google.analytics.admin.v1alpha.FirebaseLink other = (com.google.analytics.admin.v1alpha.FirebaseLink) obj; if (!getName().equals(other.getName())) return false; if (!getProject().equals(other.getProject())) return false; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) 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) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.FirebaseLink parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.analytics.admin.v1alpha.FirebaseLink 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 link between a Google Analytics property and a Firebase project. * </pre> * * Protobuf type {@code google.analytics.admin.v1alpha.FirebaseLink} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.FirebaseLink) com.google.analytics.admin.v1alpha.FirebaseLinkOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.ResourcesProto .internal_static_google_analytics_admin_v1alpha_FirebaseLink_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.ResourcesProto .internal_static_google_analytics_admin_v1alpha_FirebaseLink_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.FirebaseLink.class, com.google.analytics.admin.v1alpha.FirebaseLink.Builder.class); } // Construct using com.google.analytics.admin.v1alpha.FirebaseLink.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCreateTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; project_ = ""; createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1alpha.ResourcesProto .internal_static_google_analytics_admin_v1alpha_FirebaseLink_descriptor; } @java.lang.Override public com.google.analytics.admin.v1alpha.FirebaseLink getDefaultInstanceForType() { return com.google.analytics.admin.v1alpha.FirebaseLink.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1alpha.FirebaseLink build() { com.google.analytics.admin.v1alpha.FirebaseLink result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1alpha.FirebaseLink buildPartial() { com.google.analytics.admin.v1alpha.FirebaseLink result = new com.google.analytics.admin.v1alpha.FirebaseLink(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.analytics.admin.v1alpha.FirebaseLink result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.project_ = project_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.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.analytics.admin.v1alpha.FirebaseLink) { return mergeFrom((com.google.analytics.admin.v1alpha.FirebaseLink) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1alpha.FirebaseLink other) { if (other == com.google.analytics.admin.v1alpha.FirebaseLink.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } 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: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getCreateTimeFieldBuilder().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> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Output only. Example format: properties/1234/firebaseLinks/5678 * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</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 project_ = ""; /** * * * <pre> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</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> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</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> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Immutable. Firebase project resource name. When creating a FirebaseLink, * you may provide this resource name using either a project number or project * ID. Once this resource has been created, returned FirebaseLinks will always * have a project_name that contains a project number. * * Format: 'projects/{project number}' * Example: 'projects/1234' * </pre> * * <code>string project = 2 [(.google.api.field_behavior) = IMMUTABLE];</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.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; } else { createTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && createTime_ != null && createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCreateTimeBuilder().mergeFrom(value); } else { createTime_ = value; } } else { createTimeBuilder_.mergeFrom(value); } if (createTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearCreateTime() { bitField0_ = (bitField0_ & ~0x00000004); createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Output only. Time when this FirebaseLink was originally created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.FirebaseLink) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.FirebaseLink) private static final com.google.analytics.admin.v1alpha.FirebaseLink DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.FirebaseLink(); } public static com.google.analytics.admin.v1alpha.FirebaseLink getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FirebaseLink> PARSER = new com.google.protobuf.AbstractParser<FirebaseLink>() { @java.lang.Override public FirebaseLink 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<FirebaseLink> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FirebaseLink> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1alpha.FirebaseLink getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,888
java-securitycenter/proto-google-cloud-securitycenter-v1/src/main/java/com/google/cloud/securitycenter/v1/SetFindingStateRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/securitycenter/v1/securitycenter_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.securitycenter.v1; /** * * * <pre> * Request message for updating a finding's state. * </pre> * * Protobuf type {@code google.cloud.securitycenter.v1.SetFindingStateRequest} */ public final class SetFindingStateRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1.SetFindingStateRequest) SetFindingStateRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SetFindingStateRequest.newBuilder() to construct. private SetFindingStateRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SetFindingStateRequest() { name_ = ""; state_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SetFindingStateRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycenter.v1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1_SetFindingStateRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycenter.v1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1_SetFindingStateRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycenter.v1.SetFindingStateRequest.class, com.google.cloud.securitycenter.v1.SetFindingStateRequest.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATE_FIELD_NUMBER = 2; private int state_ = 0; /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for state. */ @java.lang.Override public int getStateValue() { return state_; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The state. */ @java.lang.Override public com.google.cloud.securitycenter.v1.Finding.State getState() { com.google.cloud.securitycenter.v1.Finding.State result = com.google.cloud.securitycenter.v1.Finding.State.forNumber(state_); return result == null ? com.google.cloud.securitycenter.v1.Finding.State.UNRECOGNIZED : result; } public static final int START_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp startTime_; /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the startTime field is set. */ @java.lang.Override public boolean hasStartTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The startTime. */ @java.lang.Override public com.google.protobuf.Timestamp getStartTime() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } 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 (state_ != com.google.cloud.securitycenter.v1.Finding.State.STATE_UNSPECIFIED.getNumber()) { output.writeEnum(2, state_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getStartTime()); } 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 (state_ != com.google.cloud.securitycenter.v1.Finding.State.STATE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, state_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getStartTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.securitycenter.v1.SetFindingStateRequest)) { return super.equals(obj); } com.google.cloud.securitycenter.v1.SetFindingStateRequest other = (com.google.cloud.securitycenter.v1.SetFindingStateRequest) obj; if (!getName().equals(other.getName())) return false; if (state_ != other.state_) return false; if (hasStartTime() != other.hasStartTime()) return false; if (hasStartTime()) { if (!getStartTime().equals(other.getStartTime())) 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) + STATE_FIELD_NUMBER; hash = (53 * hash) + state_; if (hasStartTime()) { hash = (37 * hash) + START_TIME_FIELD_NUMBER; hash = (53 * hash) + getStartTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.securitycenter.v1.SetFindingStateRequest 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 updating a finding's state. * </pre> * * Protobuf type {@code google.cloud.securitycenter.v1.SetFindingStateRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1.SetFindingStateRequest) com.google.cloud.securitycenter.v1.SetFindingStateRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycenter.v1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1_SetFindingStateRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycenter.v1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1_SetFindingStateRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycenter.v1.SetFindingStateRequest.class, com.google.cloud.securitycenter.v1.SetFindingStateRequest.Builder.class); } // Construct using com.google.cloud.securitycenter.v1.SetFindingStateRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getStartTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; state_ = 0; startTime_ = null; if (startTimeBuilder_ != null) { startTimeBuilder_.dispose(); startTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.securitycenter.v1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1_SetFindingStateRequest_descriptor; } @java.lang.Override public com.google.cloud.securitycenter.v1.SetFindingStateRequest getDefaultInstanceForType() { return com.google.cloud.securitycenter.v1.SetFindingStateRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.securitycenter.v1.SetFindingStateRequest build() { com.google.cloud.securitycenter.v1.SetFindingStateRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.securitycenter.v1.SetFindingStateRequest buildPartial() { com.google.cloud.securitycenter.v1.SetFindingStateRequest result = new com.google.cloud.securitycenter.v1.SetFindingStateRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.securitycenter.v1.SetFindingStateRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.state_ = state_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.startTime_ = startTimeBuilder_ == null ? startTime_ : startTimeBuilder_.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.securitycenter.v1.SetFindingStateRequest) { return mergeFrom((com.google.cloud.securitycenter.v1.SetFindingStateRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.securitycenter.v1.SetFindingStateRequest other) { if (other == com.google.cloud.securitycenter.v1.SetFindingStateRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.state_ != 0) { setStateValue(other.getStateValue()); } if (other.hasStartTime()) { mergeStartTime(other.getStartTime()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { state_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { input.readMessage(getStartTimeFieldBuilder().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> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The [relative resource * name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) * of the finding. Example: * `organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`, * `folders/{folder_id}/sources/{source_id}/findings/{finding_id}`, * `projects/{project_id}/sources/{source_id}/findings/{finding_id}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int state_ = 0; /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for state. */ @java.lang.Override public int getStateValue() { return state_; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The enum numeric value on the wire for state to set. * @return This builder for chaining. */ public Builder setStateValue(int value) { state_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The state. */ @java.lang.Override public com.google.cloud.securitycenter.v1.Finding.State getState() { com.google.cloud.securitycenter.v1.Finding.State result = com.google.cloud.securitycenter.v1.Finding.State.forNumber(state_); return result == null ? com.google.cloud.securitycenter.v1.Finding.State.UNRECOGNIZED : result; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The state to set. * @return This builder for chaining. */ public Builder setState(com.google.cloud.securitycenter.v1.Finding.State value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; state_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearState() { bitField0_ = (bitField0_ & ~0x00000002); state_ = 0; onChanged(); return this; } private com.google.protobuf.Timestamp startTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> startTimeBuilder_; /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the startTime field is set. */ public boolean hasStartTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The startTime. */ public com.google.protobuf.Timestamp getStartTime() { if (startTimeBuilder_ == null) { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } else { return startTimeBuilder_.getMessage(); } } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } startTime_ = value; } else { startTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (startTimeBuilder_ == null) { startTime_ = builderForValue.build(); } else { startTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && startTime_ != null && startTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getStartTimeBuilder().mergeFrom(value); } else { startTime_ = value; } } else { startTimeBuilder_.mergeFrom(value); } if (startTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearStartTime() { bitField0_ = (bitField0_ & ~0x00000004); startTime_ = null; if (startTimeBuilder_ != null) { startTimeBuilder_.dispose(); startTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getStartTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { if (startTimeBuilder_ != null) { return startTimeBuilder_.getMessageOrBuilder(); } else { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getStartTimeFieldBuilder() { if (startTimeBuilder_ == null) { startTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getStartTime(), getParentForChildren(), isClean()); startTime_ = null; } return startTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.securitycenter.v1.SetFindingStateRequest) } // @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.SetFindingStateRequest) private static final com.google.cloud.securitycenter.v1.SetFindingStateRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v1.SetFindingStateRequest(); } public static com.google.cloud.securitycenter.v1.SetFindingStateRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SetFindingStateRequest> PARSER = new com.google.protobuf.AbstractParser<SetFindingStateRequest>() { @java.lang.Override public SetFindingStateRequest 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<SetFindingStateRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SetFindingStateRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.securitycenter.v1.SetFindingStateRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/flex-blazeds
37,293
common/src/main/java/flex/messaging/config/ClientConfigurationParser.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 flex.messaging.config; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A special mxmlc compiler specific implentation of the configuration * parser for JDK 1.4. Only a small subset of the configuration is * processed to generate the information that the client needs at runtime, * such as channel definitions and service destination properties. */ public abstract class ClientConfigurationParser extends AbstractConfigurationParser { protected void parseTopLevelConfig(Document doc) { Node root = selectSingleNode(doc, "/" + SERVICES_CONFIG_ELEMENT); if (root != null) { // Validation allowedChildElements(root, SERVICES_CONFIG_CHILDREN); // Channels (parse before services) channelsSection(root); // Services services(root); // Clustering clusters(root); // FlexClient flexClient(root); } } private void channelsSection(Node root) { Node channelsNode = selectSingleNode(root, CHANNELS_ELEMENT); if (channelsNode != null) { // Validation allowedAttributesOrElements(channelsNode, CHANNELS_CHILDREN); NodeList channels = selectNodeList(channelsNode, CHANNEL_DEFINITION_ELEMENT); for (int i = 0; i < channels.getLength(); i++) { Node channel = channels.item(i); channelDefinition(channel); } NodeList includes = selectNodeList(channelsNode, CHANNEL_INCLUDE_ELEMENT); for (int i = 0; i < includes.getLength(); i++) { Node include = includes.item(i); channelInclude(include); } } } private void channelDefinition(Node channel) { // Validation requiredAttributesOrElements(channel, CHANNEL_DEFINITION_REQ_CHILDREN); allowedAttributesOrElements(channel, CHANNEL_DEFINITION_CHILDREN); String id = getAttributeOrChildElement(channel, ID_ATTR).trim(); if (isValidID(id)) { // Don't allow multiple channels with the same id if (config.getChannelSettings(id) != null) { // Cannot have multiple channels with the same id ''{0}''. ConfigurationException e = new ConfigurationException(); e.setMessage(DUPLICATE_CHANNEL_ERROR, new Object[]{id}); throw e; } ChannelSettings channelSettings = new ChannelSettings(id); // Endpoint Node endpoint = selectSingleNode(channel, ENDPOINT_ELEMENT); if (endpoint != null) { // Endpoint Validation allowedAttributesOrElements(endpoint, ENDPOINT_CHILDREN); // The url attribute may also be specified by the deprecated uri attribute String uri = getAttributeOrChildElement(endpoint, URL_ATTR); if (uri == null || EMPTY_STRING.equals(uri)) uri = getAttributeOrChildElement(endpoint, URI_ATTR); channelSettings.setUri(uri); config.addChannelSettings(id, channelSettings); } channelServerOnlyAttribute(channel, channelSettings); // Add the channel properties that the client needs namely polling-enabled, // polling-interval-millis, piggybacking-enabled, login-after-disconnect, // record-message-sizes, record-message-times, connect-timeout-seconds, // polling-interval-seconds (deprecated), and client-load-balancing. addProperty(channel, channelSettings, POLLING_ENABLED_ELEMENT); addProperty(channel, channelSettings, POLLING_INTERVAL_MILLIS_ELEMENT); addProperty(channel, channelSettings, PIGGYBACKING_ENABLED_ELEMENT); addProperty(channel, channelSettings, LOGIN_AFTER_DISCONNECT_ELEMENT); addProperty(channel, channelSettings, RECORD_MESSAGE_SIZES_ELEMENT); addProperty(channel, channelSettings, RECORD_MESSAGE_TIMES_ELEMENT); addProperty(channel, channelSettings, CONNECT_TIMEOUT_SECONDS_ELEMENT); addProperty(channel, channelSettings, POLLING_INTERVAL_SECONDS_ELEMENT); // deprecated. addProperty(channel, channelSettings, CLIENT_LOAD_BALANCING_ELEMENT); addProperty(channel, channelSettings, REQUEST_TIMEOUT_SECONDS_ELEMENT); // enable-small-messages. NodeList properties = selectNodeList(channel, PROPERTIES_ELEMENT + "/" + SERIALIZATION_ELEMENT); if (properties.getLength() > 0) { ConfigMap map = properties(properties, getSourceFileOf(channel)); ConfigMap serialization = map.getPropertyAsMap(SERIALIZATION_ELEMENT, null); if (serialization != null) { // enable-small-messages. String enableSmallMessages = serialization.getProperty(ENABLE_SMALL_MESSAGES_ELEMENT); if (enableSmallMessages != null) { ConfigMap clientMap = new ConfigMap(); clientMap.addProperty(ENABLE_SMALL_MESSAGES_ELEMENT, enableSmallMessages); channelSettings.addProperty(SERIALIZATION_ELEMENT, clientMap); } } } } else { // Invalid {CHANNEL_DEFINITION_ELEMENT} id '{id}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_ID, new Object[]{CHANNEL_DEFINITION_ELEMENT, id}); String details = "An id must be non-empty and not contain any list delimiter characters, i.e. commas, semi-colons or colons."; ex.setDetails(details); throw ex; } } private void channelServerOnlyAttribute(Node channel, ChannelSettings channelSettings) { String clientType = getAttributeOrChildElement(channel, CLASS_ATTR); clientType = clientType.length() > 0 ? clientType : null; String serverOnlyString = getAttributeOrChildElement(channel, SERVER_ONLY_ATTR); boolean serverOnly = serverOnlyString.length() > 0 && Boolean.valueOf(serverOnlyString).booleanValue(); if (clientType == null && !serverOnly) // None set. { String url = channelSettings.getUri(); boolean serverOnlyProtocol = (url.startsWith("samfsocket") || url.startsWith("amfsocket") || url.startsWith("ws")); if (!serverOnlyProtocol) { // Endpoint ''{0}'' needs to have either class or server-only attribute defined. ConfigurationException ce = new ConfigurationException(); ce.setMessage(CLASS_OR_SERVER_ONLY_ERROR, new Object[]{channelSettings.getId()}); throw ce; } channelSettings.setServerOnly(true); } else if (clientType != null && serverOnly) // Both set. { // Endpoint ''{0}'' cannot have both class and server-only attribute defined. ConfigurationException ce = new ConfigurationException(); ce.setMessage(CLASS_AND_SERVER_ONLY_ERROR, new Object[]{channelSettings.getId()}); throw ce; } else // One of them set. { if (serverOnly) channelSettings.setServerOnly(true); else channelSettings.setClientType(clientType); } } private void addProperty(Node channel, ChannelSettings channelSettings, String property) { NodeList properties = selectNodeList(channel, PROPERTIES_ELEMENT + "/" + property); if (properties.getLength() > 0) { ConfigMap map = properties(properties, getSourceFileOf(channel)); if (CLIENT_LOAD_BALANCING_ELEMENT.equals(property)) { ConfigMap clientLoadBalancingMap = map.getPropertyAsMap(CLIENT_LOAD_BALANCING_ELEMENT, null); if (clientLoadBalancingMap == null) { // Invalid {0} configuration for endpoint ''{1}''; no urls defined. ConfigurationException ce = new ConfigurationException(); ce.setMessage(ERR_MSG_EMPTY_CLIENT_LOAD_BALANCING_ELEMENT, new Object[]{CLIENT_LOAD_BALANCING_ELEMENT, channelSettings.getId()}); throw ce; } List urls = clientLoadBalancingMap.getPropertyAsList(URL_ATTR, null); addClientLoadBalancingUrls(urls, channelSettings.getId()); } channelSettings.addProperties(map); } } // Add client load balancing urls after necessary validation checks. private void addClientLoadBalancingUrls(List urls, String endpointId) { if (urls == null || urls.isEmpty()) { // Invalid {0} configuration for endpoint ''{1}''; no urls defined. ConfigurationException ce = new ConfigurationException(); ce.setMessage(ERR_MSG_EMPTY_CLIENT_LOAD_BALANCING_ELEMENT, new Object[]{CLIENT_LOAD_BALANCING_ELEMENT, endpointId}); throw ce; } Set clientLoadBalancingUrls = new HashSet(); for (Iterator iterator = urls.iterator(); iterator.hasNext(); ) { String url = (String) iterator.next(); if (url == null || url.length() == 0) { // Invalid {0} configuration for endpoint ''{1}''; cannot add empty url. ConfigurationException ce = new ConfigurationException(); ce.setMessage(ERR_MSG_EMTPY_CLIENT_LOAD_BALACNING_URL, new Object[]{CLIENT_LOAD_BALANCING_ELEMENT, endpointId}); throw ce; } if (TokenReplacer.containsTokens(url)) { // Invalid {0} configuration for endpoint ''{1}''; cannot add url with tokens. ConfigurationException ce = new ConfigurationException(); ce.setMessage(ERR_MSG_CLIENT_LOAD_BALANCING_URL_WITH_TOKEN, new Object[]{CLIENT_LOAD_BALANCING_ELEMENT, endpointId}); throw ce; } if (clientLoadBalancingUrls.contains(url)) iterator.remove(); else clientLoadBalancingUrls.add(url); } } private void channelInclude(Node channelInclude) { // Validation allowedAttributesOrElements(channelInclude, CHANNEL_INCLUDE_CHILDREN); String src = getAttributeOrChildElement(channelInclude, SRC_ATTR); String dir = getAttributeOrChildElement(channelInclude, DIRECTORY_ATTR); if (src.length() > 0) { channelIncludeFile(src); } else if (dir.length() > 0) { channelIncludeDirectory(dir); } else { // The include element ''{0}'' must specify either the ''{1}'' or ''{2}'' attribute. ConfigurationException ex = new ConfigurationException(); ex.setMessage(MISSING_INCLUDE_ATTRIBUTES, new Object[]{channelInclude.getNodeName(), SRC_ATTR, DIRECTORY_ATTR}); throw ex; } } private void channelIncludeFile(String src) { Document doc = loadDocument(src, fileResolver.getIncludedFile(src)); if (fileResolver instanceof LocalFileResolver) { LocalFileResolver local = (LocalFileResolver) fileResolver; ((ClientConfiguration) config).addConfigPath(local.getIncludedPath(src), local.getIncludedLastModified(src)); } doc.getDocumentElement().normalize(); // Check for multiple channels in a single file. Node channelsNode = selectSingleNode(doc, CHANNELS_ELEMENT); if (channelsNode != null) { allowedChildElements(channelsNode, CHANNELS_CHILDREN); NodeList channels = selectNodeList(channelsNode, CHANNEL_DEFINITION_ELEMENT); for (int a = 0; a < channels.getLength(); a++) { Node service = channels.item(a); channelDefinition(service); } fileResolver.popIncludedFile(); } else // Check for single channel in the file. { Node channel = selectSingleNode(doc, "/" + CHANNEL_DEFINITION_ELEMENT); if (channel != null) { channelDefinition(channel); fileResolver.popIncludedFile(); } else { // The {0} root element in file {1} must be '{CHANNELS_ELEMENT}' or '{CHANNEL_ELEMENT}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_INCLUDE_ROOT, new Object[]{CHANNEL_INCLUDE_ELEMENT, src, CHANNELS_ELEMENT, CHANNEL_DEFINITION_ELEMENT}); throw ex; } } } private void channelIncludeDirectory(String dir) { List files = fileResolver.getFiles(dir); for (int i = 0; i < files.size(); i++) { String src = (String) files.get(i); channelIncludeFile(src); } } private void services(Node root) { Node servicesNode = selectSingleNode(root, SERVICES_ELEMENT); if (servicesNode != null) { // Validation allowedChildElements(servicesNode, SERVICES_CHILDREN); // Default Channels for the application Node defaultChannels = selectSingleNode(servicesNode, DEFAULT_CHANNELS_ELEMENT); if (defaultChannels != null) { allowedChildElements(defaultChannels, DEFAULT_CHANNELS_CHILDREN); NodeList channels = selectNodeList(defaultChannels, CHANNEL_ELEMENT); for (int c = 0; c < channels.getLength(); c++) { Node chan = channels.item(c); allowedAttributes(chan, new String[]{REF_ATTR}); defaultChannel(chan); } } // Service Includes NodeList services = selectNodeList(servicesNode, SERVICE_INCLUDE_ELEMENT); for (int i = 0; i < services.getLength(); i++) { Node service = services.item(i); serviceInclude(service); } // Service services = selectNodeList(servicesNode, SERVICE_ELEMENT); for (int i = 0; i < services.getLength(); i++) { Node service = services.item(i); service(service); } } } private void clusters(Node root) { Node clusteringNode = selectSingleNode(root, CLUSTERS_ELEMENT); if (clusteringNode != null) { allowedAttributesOrElements(clusteringNode, CLUSTERING_CHILDREN); NodeList clusters = selectNodeList(clusteringNode, CLUSTER_DEFINITION_ELEMENT); for (int i = 0; i < clusters.getLength(); i++) { Node cluster = clusters.item(i); requiredAttributesOrElements(cluster, CLUSTER_DEFINITION_CHILDREN); String clusterName = getAttributeOrChildElement(cluster, ID_ATTR); if (isValidID(clusterName)) { String propsFileName = getAttributeOrChildElement(cluster, CLUSTER_PROPERTIES_ATTR); ClusterSettings clusterSettings = new ClusterSettings(); clusterSettings.setClusterName(clusterName); clusterSettings.setPropsFileName(propsFileName); String defaultValue = getAttributeOrChildElement(cluster, ClusterSettings.DEFAULT_ELEMENT); if (defaultValue != null && defaultValue.length() > 0) { if (defaultValue.equalsIgnoreCase("true")) clusterSettings.setDefault(true); else if (!defaultValue.equalsIgnoreCase("false")) { ConfigurationException e = new ConfigurationException(); e.setMessage(10215, new Object[]{clusterName, defaultValue}); throw e; } } String ulb = getAttributeOrChildElement(cluster, ClusterSettings.URL_LOAD_BALANCING); if (ulb != null && ulb.length() > 0) { if (ulb.equalsIgnoreCase("false")) clusterSettings.setURLLoadBalancing(false); else if (!ulb.equalsIgnoreCase("true")) { ConfigurationException e = new ConfigurationException(); e.setMessage(10216, new Object[]{clusterName, ulb}); throw e; } } ((ClientConfiguration) config).addClusterSettings(clusterSettings); } } } } private void serviceInclude(Node serviceInclude) { // Validation allowedAttributesOrElements(serviceInclude, SERVICE_INCLUDE_CHILDREN); String src = getAttributeOrChildElement(serviceInclude, SRC_ATTR); String dir = getAttributeOrChildElement(serviceInclude, DIRECTORY_ATTR); if (src.length() > 0) { serviceIncludeFile(src); } else if (dir.length() > 0) { serviceIncludeDirectory(dir); } else { // The include element ''{0}'' must specify either the ''{1}'' or ''{2}'' attribute. ConfigurationException ex = new ConfigurationException(); ex.setMessage(MISSING_INCLUDE_ATTRIBUTES, new Object[]{serviceInclude.getNodeName(), SRC_ATTR, DIRECTORY_ATTR}); throw ex; } } private void serviceIncludeFile(String src) { Document doc = loadDocument(src, fileResolver.getIncludedFile(src)); if (fileResolver instanceof LocalFileResolver) { LocalFileResolver local = (LocalFileResolver) fileResolver; ((ClientConfiguration) config).addConfigPath(local.getIncludedPath(src), local.getIncludedLastModified(src)); } doc.getDocumentElement().normalize(); // Check for multiple services defined in file. Node servicesNode = selectSingleNode(doc, SERVICES_ELEMENT); if (servicesNode != null) { allowedChildElements(servicesNode, SERVICES_CHILDREN); NodeList services = selectNodeList(servicesNode, SERVICES_ELEMENT); for (int a = 0; a < services.getLength(); a++) { Node service = services.item(a); service(service); } fileResolver.popIncludedFile(); } else // Check for single service in file. { Node service = selectSingleNode(doc, "/" + SERVICE_ELEMENT); if (service != null) { service(service); fileResolver.popIncludedFile(); } else { // The {0} root element in file {1} must be ''{2}'' or ''{3}''. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_INCLUDE_ROOT, new Object[]{SERVICE_INCLUDE_ELEMENT, src, SERVICES_ELEMENT, SERVICE_ELEMENT}); throw ex; } } } private void serviceIncludeDirectory(String dir) { List files = fileResolver.getFiles(dir); for (int i = 0; i < files.size(); i++) { String src = (String) files.get(i); serviceIncludeFile(src); } } private void service(Node service) { // Validation requiredAttributesOrElements(service, SERVICE_REQ_CHILDREN); allowedAttributesOrElements(service, SERVICE_CHILDREN); String id = getAttributeOrChildElement(service, ID_ATTR); if (isValidID(id)) { ServiceSettings serviceSettings = config.getServiceSettings(id); if (serviceSettings == null) { serviceSettings = new ServiceSettings(id); // Service Properties NodeList properties = selectNodeList(service, PROPERTIES_ELEMENT + "/*"); if (properties.getLength() > 0) { ConfigMap map = properties(properties, getSourceFileOf(service)); serviceSettings.addProperties(map); } config.addServiceSettings(serviceSettings); } else { // Duplicate service definition '{0}'. ConfigurationException e = new ConfigurationException(); e.setMessage(DUPLICATE_SERVICE_ERROR, new Object[]{id}); throw e; } // Service Class Name String className = getAttributeOrChildElement(service, CLASS_ATTR); if (className.length() > 0) { serviceSettings.setClassName(className); } else { // Class not specified for {SERVICE_ELEMENT} '{id}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(CLASS_NOT_SPECIFIED, new Object[]{SERVICE_ELEMENT, id}); throw ex; } //Service Message Types - deprecated // Default Channels Node defaultChannels = selectSingleNode(service, DEFAULT_CHANNELS_ELEMENT); if (defaultChannels != null) { allowedChildElements(defaultChannels, DEFAULT_CHANNELS_CHILDREN); NodeList channels = selectNodeList(defaultChannels, CHANNEL_ELEMENT); for (int c = 0; c < channels.getLength(); c++) { Node chan = channels.item(c); allowedAttributes(chan, new String[]{REF_ATTR}); defaultChannel(chan, serviceSettings); } } // Fall back on application's default channels else if (config.getDefaultChannels().size() > 0) { for (Iterator iter = config.getDefaultChannels().iterator(); iter.hasNext(); ) { String channelId = (String) iter.next(); ChannelSettings channel = config.getChannelSettings(channelId); serviceSettings.addDefaultChannel(channel); } } // Destinations NodeList list = selectNodeList(service, DESTINATION_ELEMENT); for (int i = 0; i < list.getLength(); i++) { Node dest = list.item(i); destination(dest, serviceSettings); } // Destination Includes list = selectNodeList(service, DESTINATION_INCLUDE_ELEMENT); for (int i = 0; i < list.getLength(); i++) { Node dest = list.item(i); destinationInclude(dest, serviceSettings); } } else { //Invalid {SERVICE_ELEMENT} id '{id}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_ID, new Object[]{SERVICE_ELEMENT, id}); throw ex; } } /** * Flex application can declare default channels for its services. If a * service specifies its own list of channels it overrides these defaults. * <p> * &lt;default-channels&gt;<br /> * ;&lt;channel ref="channel-id" /&gt;<br /> * &lt;default-channels&gt; * </p> * * @param chan the channel node */ private void defaultChannel(Node chan) { String ref = getAttributeOrChildElement(chan, REF_ATTR); if (ref.length() > 0) { ChannelSettings channel = config.getChannelSettings(ref); if (channel != null) { config.addDefaultChannel(channel.getId()); } else { // {0} not found for reference '{1}' ConfigurationException e = new ConfigurationException(); e.setMessage(REF_NOT_FOUND, new Object[]{CHANNEL_ELEMENT, ref}); throw e; } } else { //A default channel was specified without a reference for service '{0}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_DEFAULT_CHANNEL, new Object[]{"MessageBroker"}); throw ex; } } /** * A service can declare default channels for its destinations. If a destination * specifies its own list of channels it overrides these defaults. * <p> * &lt;default-channels&gt;<br /> * &lt;channel ref="channel-id" /&gt;<br /> * &lt;default-channels&gt; * </p> * * @param chan the channel node * @param serviceSettings service settings */ private void defaultChannel(Node chan, ServiceSettings serviceSettings) { String ref = getAttributeOrChildElement(chan, REF_ATTR).trim(); if (ref.length() > 0) { ChannelSettings channel = config.getChannelSettings(ref); if (channel != null) { serviceSettings.addDefaultChannel(channel); } else { // {0} not found for reference '{1}' ConfigurationException e = new ConfigurationException(); e.setMessage(REF_NOT_FOUND, new Object[]{CHANNEL_ELEMENT, ref}); throw e; } } else { //A default channel was specified without a reference for service '{0}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_DEFAULT_CHANNEL, new Object[]{serviceSettings.getId()}); throw ex; } } private void destinationInclude(Node destInclude, ServiceSettings serviceSettings) { // Validation allowedAttributesOrElements(destInclude, DESTINATION_INCLUDE_CHILDREN); String src = getAttributeOrChildElement(destInclude, SRC_ATTR); String dir = getAttributeOrChildElement(destInclude, DIRECTORY_ATTR); if (src.length() > 0) { destinationIncludeFile(serviceSettings, src); } else if (dir.length() > 0) { destinationIncludeDirectory(serviceSettings, dir); } else { // The include element ''{0}'' must specify either the ''{1}'' or ''{2}'' attribute. ConfigurationException ex = new ConfigurationException(); ex.setMessage(MISSING_INCLUDE_ATTRIBUTES, new Object[]{destInclude.getNodeName(), SRC_ATTR, DIRECTORY_ATTR}); throw ex; } } private void destinationIncludeDirectory(ServiceSettings serviceSettings, String dir) { List files = fileResolver.getFiles(dir); for (int i = 0; i < files.size(); i++) { String src = (String) files.get(i); destinationIncludeFile(serviceSettings, src); } } private void destinationIncludeFile(ServiceSettings serviceSettings, String src) { Document doc = loadDocument(src, fileResolver.getIncludedFile(src)); if (fileResolver instanceof LocalFileResolver) { LocalFileResolver local = (LocalFileResolver) fileResolver; ((ClientConfiguration) config).addConfigPath(local.getIncludedPath(src), local.getIncludedLastModified(src)); } doc.getDocumentElement().normalize(); // Check for multiple destination defined in file. Node destinationsNode = selectSingleNode(doc, DESTINATIONS_ELEMENT); if (destinationsNode != null) { allowedChildElements(destinationsNode, DESTINATIONS_CHILDREN); NodeList destinations = selectNodeList(destinationsNode, DESTINATION_ELEMENT); for (int a = 0; a < destinations.getLength(); a++) { Node dest = destinations.item(a); destination(dest, serviceSettings); } fileResolver.popIncludedFile(); } else // Check for single destination definition. { Node dest = selectSingleNode(doc, "/" + DESTINATION_ELEMENT); if (dest != null) { destination(dest, serviceSettings); fileResolver.popIncludedFile(); } else { // The {0} root element in file {1} must be ''{2}'' or ''{3}''. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_INCLUDE_ROOT, new Object[]{DESTINATION_INCLUDE_ELEMENT, src, DESTINATIONS_ELEMENT, DESTINATION_ELEMENT}); throw ex; } } } private void destination(Node dest, ServiceSettings serviceSettings) { // Validation requiredAttributesOrElements(dest, DESTINATION_REQ_CHILDREN); allowedAttributes(dest, DESTINATION_ATTR); allowedChildElements(dest, DESTINATION_CHILDREN); String serviceId = serviceSettings.getId(); DestinationSettings destinationSettings; String id = getAttributeOrChildElement(dest, ID_ATTR); if (isValidID(id)) { destinationSettings = (DestinationSettings) serviceSettings.getDestinationSettings().get(id); if (destinationSettings != null) { // Duplicate destination definition '{id}' in service '{serviceId}'. ConfigurationException e = new ConfigurationException(); e.setMessage(DUPLICATE_DESTINATION_ERROR, new Object[]{id, serviceId}); throw e; } destinationSettings = new DestinationSettings(id); serviceSettings.addDestinationSettings(destinationSettings); } else { //Invalid {DESTINATION_ELEMENT} id '{id}' for service '{serviceId}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_ID_IN_SERVICE, new Object[]{DESTINATION_ELEMENT, id, serviceId}); throw ex; } // Destination Properties NodeList properties = selectNodeList(dest, PROPERTIES_ELEMENT + "/*"); if (properties.getLength() > 0) { ConfigMap map = properties(properties, getSourceFileOf(dest)); destinationSettings.addProperties(map); } // Channels destinationChannels(dest, destinationSettings, serviceSettings); } private void destinationChannels(Node dest, DestinationSettings destinationSettings, ServiceSettings serviceSettings) { String destId = destinationSettings.getId(); // Channels attribute String channelsList = evaluateExpression(dest, "@" + CHANNELS_ATTR).toString().trim(); if (channelsList.length() > 0) { StringTokenizer st = new StringTokenizer(channelsList, LIST_DELIMITERS); while (st.hasMoreTokens()) { String ref = st.nextToken().trim(); ChannelSettings channel = config.getChannelSettings(ref); if (channel != null) { destinationSettings.addChannelSettings(channel); } else { // {CHANNEL_ELEMENT} not found for reference '{ref}' in destination '{destId}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(REF_NOT_FOUND_IN_DEST, new Object[]{CHANNEL_ELEMENT, ref, destId}); throw ex; } } } else { // Channels element Node channelsNode = selectSingleNode(dest, CHANNELS_ELEMENT); if (channelsNode != null) { allowedChildElements (channelsNode, DESTINATION_CHANNELS_CHILDREN); NodeList channels = selectNodeList(channelsNode, CHANNEL_ELEMENT); if (channels.getLength() > 0) { for (int c = 0; c < channels.getLength(); c++) { Node chan = channels.item(c); // Validation requiredAttributesOrElements(chan, DESTINATION_CHANNEL_REQ_CHILDREN); String ref = getAttributeOrChildElement(chan, REF_ATTR).trim(); if (ref.length() > 0) { ChannelSettings channel = config.getChannelSettings(ref); if (channel != null) { destinationSettings.addChannelSettings(channel); } else { // {CHANNEL_ELEMENT} not found for reference '{ref}' in destination '{destId}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(REF_NOT_FOUND_IN_DEST, new Object[]{CHANNEL_ELEMENT, ref, destId}); throw ex; } } else { //Invalid {0} ref '{1}' in destination '{2}'. ConfigurationException ex = new ConfigurationException(); ex.setMessage(INVALID_REF_IN_DEST, new Object[]{CHANNEL_ELEMENT, ref, destId}); throw ex; } } } } else { // Finally, we fall back to the service's default channels List defaultChannels = serviceSettings.getDefaultChannels(); Iterator it = defaultChannels.iterator(); while (it.hasNext()) { ChannelSettings channel = (ChannelSettings) it.next(); destinationSettings.addChannelSettings(channel); } } } if (destinationSettings.getChannelSettings().size() <= 0) { // Destination '{id}' must specify at least one channel. ConfigurationException ex = new ConfigurationException(); ex.setMessage(DEST_NEEDS_CHANNEL, new Object[]{destId}); throw ex; } } private void flexClient(Node root) { Node flexClient = selectSingleNode(root, FLEX_CLIENT_ELEMENT); if (flexClient != null) { FlexClientSettings flexClientSettings = new FlexClientSettings(); // Reliable reconnect duration millis String reliableReconnectDurationMillis = getAttributeOrChildElement(flexClient, FLEX_CLIENT_RELIABLE_RECONNECT_DURATION_MILLIS); if (reliableReconnectDurationMillis.length() > 0) { try { int millis = Integer.parseInt(reliableReconnectDurationMillis); if (millis < 0) { ConfigurationException e = new ConfigurationException(); e.setMessage(INVALID_FLEX_CLIENT_RELIABLE_RECONNECT_DURATION_MILLIS, new Object[]{reliableReconnectDurationMillis}); throw e; } flexClientSettings.setReliableReconnectDurationMillis(millis); } catch (NumberFormatException nfe) { ConfigurationException e = new ConfigurationException(); e.setMessage(INVALID_FLEX_CLIENT_RELIABLE_RECONNECT_DURATION_MILLIS, new Object[]{reliableReconnectDurationMillis}); throw e; } } else { flexClientSettings.setReliableReconnectDurationMillis(0); // Default is 0. } // heartbeat interval millis String heartbeatIntervalMillis = getAttributeOrChildElement(flexClient, FLEX_CLIENT_HEARTBEAT_INTERVAL_MILLIS); if (heartbeatIntervalMillis.length() > 0) { try { int millis = Integer.parseInt(heartbeatIntervalMillis); if (millis < 0) { ConfigurationException e = new ConfigurationException(); e.setMessage(INVALID_FLEX_CLIENT_HEARTBEAT_INTERVAL_MILLIS, new Object[]{heartbeatIntervalMillis}); throw e; } flexClientSettings.setHeartbeatIntervalMillis(millis); } catch (NumberFormatException nfe) { ConfigurationException e = new ConfigurationException(); e.setMessage(INVALID_FLEX_CLIENT_HEARTBEAT_INTERVAL_MILLIS, new Object[]{heartbeatIntervalMillis}); throw e; } } ((ClientConfiguration) config).setFlexClientSettings(flexClientSettings); } } }
googleapis/google-cloud-java
36,878
java-apihub/proto-google-cloud-apihub-v1/src/main/java/com/google/cloud/apihub/v1/CreateApiRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/apihub/v1/apihub_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.apihub.v1; /** * * * <pre> * The [CreateApi][google.cloud.apihub.v1.ApiHub.CreateApi] method's request. * </pre> * * Protobuf type {@code google.cloud.apihub.v1.CreateApiRequest} */ public final class CreateApiRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.apihub.v1.CreateApiRequest) CreateApiRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateApiRequest.newBuilder() to construct. private CreateApiRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateApiRequest() { parent_ = ""; apiId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateApiRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_CreateApiRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_CreateApiRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apihub.v1.CreateApiRequest.class, com.google.cloud.apihub.v1.CreateApiRequest.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 for the API 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 parent resource for the API 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 API_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object apiId_ = ""; /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The apiId. */ @java.lang.Override public java.lang.String getApiId() { java.lang.Object ref = apiId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); apiId_ = s; return s; } } /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for apiId. */ @java.lang.Override public com.google.protobuf.ByteString getApiIdBytes() { java.lang.Object ref = apiId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); apiId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int API_FIELD_NUMBER = 3; private com.google.cloud.apihub.v1.Api api_; /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return Whether the api field is set. */ @java.lang.Override public boolean hasApi() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The api. */ @java.lang.Override public com.google.cloud.apihub.v1.Api getApi() { return api_ == null ? com.google.cloud.apihub.v1.Api.getDefaultInstance() : api_; } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public com.google.cloud.apihub.v1.ApiOrBuilder getApiOrBuilder() { return api_ == null ? com.google.cloud.apihub.v1.Api.getDefaultInstance() : api_; } 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(apiId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, apiId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getApi()); } 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(apiId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, apiId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getApi()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.apihub.v1.CreateApiRequest)) { return super.equals(obj); } com.google.cloud.apihub.v1.CreateApiRequest other = (com.google.cloud.apihub.v1.CreateApiRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getApiId().equals(other.getApiId())) return false; if (hasApi() != other.hasApi()) return false; if (hasApi()) { if (!getApi().equals(other.getApi())) 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) + API_ID_FIELD_NUMBER; hash = (53 * hash) + getApiId().hashCode(); if (hasApi()) { hash = (37 * hash) + API_FIELD_NUMBER; hash = (53 * hash) + getApi().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.apihub.v1.CreateApiRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.CreateApiRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.CreateApiRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.apihub.v1.CreateApiRequest 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 [CreateApi][google.cloud.apihub.v1.ApiHub.CreateApi] method's request. * </pre> * * Protobuf type {@code google.cloud.apihub.v1.CreateApiRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.apihub.v1.CreateApiRequest) com.google.cloud.apihub.v1.CreateApiRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_CreateApiRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_CreateApiRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apihub.v1.CreateApiRequest.class, com.google.cloud.apihub.v1.CreateApiRequest.Builder.class); } // Construct using com.google.cloud.apihub.v1.CreateApiRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getApiFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; apiId_ = ""; api_ = null; if (apiBuilder_ != null) { apiBuilder_.dispose(); apiBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_CreateApiRequest_descriptor; } @java.lang.Override public com.google.cloud.apihub.v1.CreateApiRequest getDefaultInstanceForType() { return com.google.cloud.apihub.v1.CreateApiRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.apihub.v1.CreateApiRequest build() { com.google.cloud.apihub.v1.CreateApiRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.apihub.v1.CreateApiRequest buildPartial() { com.google.cloud.apihub.v1.CreateApiRequest result = new com.google.cloud.apihub.v1.CreateApiRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.apihub.v1.CreateApiRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.apiId_ = apiId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.api_ = apiBuilder_ == null ? api_ : apiBuilder_.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.apihub.v1.CreateApiRequest) { return mergeFrom((com.google.cloud.apihub.v1.CreateApiRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.apihub.v1.CreateApiRequest other) { if (other == com.google.cloud.apihub.v1.CreateApiRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getApiId().isEmpty()) { apiId_ = other.apiId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasApi()) { mergeApi(other.getApi()); } 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: { apiId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getApiFieldBuilder().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 for the API 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 parent resource for the API 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 parent resource for the API 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 parent resource for the API 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 parent resource for the API 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 java.lang.Object apiId_ = ""; /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The apiId. */ public java.lang.String getApiId() { java.lang.Object ref = apiId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); apiId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for apiId. */ public com.google.protobuf.ByteString getApiIdBytes() { java.lang.Object ref = apiId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); apiId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The apiId to set. * @return This builder for chaining. */ public Builder setApiId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } apiId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearApiId() { apiId_ = getDefaultInstance().getApiId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. The ID to use for the API resource, which will become the final * component of the API's resource name. This field is optional. * * * If provided, the same will be used. The service will throw an error if * the specified id is already used by another API resource in the API hub. * * If not provided, a system generated id will be used. * * This value should be 4-500 characters, and valid characters * are /[a-z][A-Z][0-9]-_/. * </pre> * * <code>string api_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for apiId to set. * @return This builder for chaining. */ public Builder setApiIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); apiId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.apihub.v1.Api api_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.apihub.v1.Api, com.google.cloud.apihub.v1.Api.Builder, com.google.cloud.apihub.v1.ApiOrBuilder> apiBuilder_; /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return Whether the api field is set. */ public boolean hasApi() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The api. */ public com.google.cloud.apihub.v1.Api getApi() { if (apiBuilder_ == null) { return api_ == null ? com.google.cloud.apihub.v1.Api.getDefaultInstance() : api_; } else { return apiBuilder_.getMessage(); } } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setApi(com.google.cloud.apihub.v1.Api value) { if (apiBuilder_ == null) { if (value == null) { throw new NullPointerException(); } api_ = value; } else { apiBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setApi(com.google.cloud.apihub.v1.Api.Builder builderForValue) { if (apiBuilder_ == null) { api_ = builderForValue.build(); } else { apiBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder mergeApi(com.google.cloud.apihub.v1.Api value) { if (apiBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && api_ != null && api_ != com.google.cloud.apihub.v1.Api.getDefaultInstance()) { getApiBuilder().mergeFrom(value); } else { api_ = value; } } else { apiBuilder_.mergeFrom(value); } if (api_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder clearApi() { bitField0_ = (bitField0_ & ~0x00000004); api_ = null; if (apiBuilder_ != null) { apiBuilder_.dispose(); apiBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.cloud.apihub.v1.Api.Builder getApiBuilder() { bitField0_ |= 0x00000004; onChanged(); return getApiFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.cloud.apihub.v1.ApiOrBuilder getApiOrBuilder() { if (apiBuilder_ != null) { return apiBuilder_.getMessageOrBuilder(); } else { return api_ == null ? com.google.cloud.apihub.v1.Api.getDefaultInstance() : api_; } } /** * * * <pre> * Required. The API resource to create. * </pre> * * <code>.google.cloud.apihub.v1.Api api = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.apihub.v1.Api, com.google.cloud.apihub.v1.Api.Builder, com.google.cloud.apihub.v1.ApiOrBuilder> getApiFieldBuilder() { if (apiBuilder_ == null) { apiBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.apihub.v1.Api, com.google.cloud.apihub.v1.Api.Builder, com.google.cloud.apihub.v1.ApiOrBuilder>( getApi(), getParentForChildren(), isClean()); api_ = null; } return apiBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.apihub.v1.CreateApiRequest) } // @@protoc_insertion_point(class_scope:google.cloud.apihub.v1.CreateApiRequest) private static final com.google.cloud.apihub.v1.CreateApiRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.apihub.v1.CreateApiRequest(); } public static com.google.cloud.apihub.v1.CreateApiRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateApiRequest> PARSER = new com.google.protobuf.AbstractParser<CreateApiRequest>() { @java.lang.Override public CreateApiRequest 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<CreateApiRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateApiRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.apihub.v1.CreateApiRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,803
java-channel/proto-google-cloud-channel-v1/src/main/java/com/google/cloud/channel/v1/Column.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/channel/v1/reports_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.channel.v1; /** * * * <pre> * The definition of a report column. Specifies the data properties * in the corresponding position of the report rows. * </pre> * * Protobuf type {@code google.cloud.channel.v1.Column} */ @java.lang.Deprecated public final class Column extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.channel.v1.Column) ColumnOrBuilder { private static final long serialVersionUID = 0L; // Use Column.newBuilder() to construct. private Column(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Column() { columnId_ = ""; displayName_ = ""; dataType_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Column(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.channel.v1.ReportsServiceProto .internal_static_google_cloud_channel_v1_Column_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.channel.v1.ReportsServiceProto .internal_static_google_cloud_channel_v1_Column_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.channel.v1.Column.class, com.google.cloud.channel.v1.Column.Builder.class); } /** * * * <pre> * Available data types for columns. Corresponds to the fields in the * ReportValue `oneof` field. * </pre> * * Protobuf enum {@code google.cloud.channel.v1.Column.DataType} */ public enum DataType implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Not used. * </pre> * * <code>DATA_TYPE_UNSPECIFIED = 0;</code> */ DATA_TYPE_UNSPECIFIED(0), /** * * * <pre> * ReportValues for this column will use string_value. * </pre> * * <code>STRING = 1;</code> */ STRING(1), /** * * * <pre> * ReportValues for this column will use int_value. * </pre> * * <code>INT = 2;</code> */ INT(2), /** * * * <pre> * ReportValues for this column will use decimal_value. * </pre> * * <code>DECIMAL = 3;</code> */ DECIMAL(3), /** * * * <pre> * ReportValues for this column will use money_value. * </pre> * * <code>MONEY = 4;</code> */ MONEY(4), /** * * * <pre> * ReportValues for this column will use date_value. * </pre> * * <code>DATE = 5;</code> */ DATE(5), /** * * * <pre> * ReportValues for this column will use date_time_value. * </pre> * * <code>DATE_TIME = 6;</code> */ DATE_TIME(6), UNRECOGNIZED(-1), ; /** * * * <pre> * Not used. * </pre> * * <code>DATA_TYPE_UNSPECIFIED = 0;</code> */ public static final int DATA_TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * ReportValues for this column will use string_value. * </pre> * * <code>STRING = 1;</code> */ public static final int STRING_VALUE = 1; /** * * * <pre> * ReportValues for this column will use int_value. * </pre> * * <code>INT = 2;</code> */ public static final int INT_VALUE = 2; /** * * * <pre> * ReportValues for this column will use decimal_value. * </pre> * * <code>DECIMAL = 3;</code> */ public static final int DECIMAL_VALUE = 3; /** * * * <pre> * ReportValues for this column will use money_value. * </pre> * * <code>MONEY = 4;</code> */ public static final int MONEY_VALUE = 4; /** * * * <pre> * ReportValues for this column will use date_value. * </pre> * * <code>DATE = 5;</code> */ public static final int DATE_VALUE = 5; /** * * * <pre> * ReportValues for this column will use date_time_value. * </pre> * * <code>DATE_TIME = 6;</code> */ public static final int DATE_TIME_VALUE = 6; 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 DataType 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 DataType forNumber(int value) { switch (value) { case 0: return DATA_TYPE_UNSPECIFIED; case 1: return STRING; case 2: return INT; case 3: return DECIMAL; case 4: return MONEY; case 5: return DATE; case 6: return DATE_TIME; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<DataType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<DataType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<DataType>() { public DataType findValueByNumber(int number) { return DataType.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.channel.v1.Column.getDescriptor().getEnumTypes().get(0); } private static final DataType[] VALUES = values(); public static DataType 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 DataType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.channel.v1.Column.DataType) } public static final int COLUMN_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object columnId_ = ""; /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @return The columnId. */ @java.lang.Override public java.lang.String getColumnId() { java.lang.Object ref = columnId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); columnId_ = s; return s; } } /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @return The bytes for columnId. */ @java.lang.Override public com.google.protobuf.ByteString getColumnIdBytes() { java.lang.Object ref = columnId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); columnId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DISPLAY_NAME_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object displayName_ = ""; /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @return The displayName. */ @java.lang.Override public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } } /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @return The bytes for displayName. */ @java.lang.Override public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DATA_TYPE_FIELD_NUMBER = 3; private int dataType_ = 0; /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @return The enum numeric value on the wire for dataType. */ @java.lang.Override public int getDataTypeValue() { return dataType_; } /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @return The dataType. */ @java.lang.Override public com.google.cloud.channel.v1.Column.DataType getDataType() { com.google.cloud.channel.v1.Column.DataType result = com.google.cloud.channel.v1.Column.DataType.forNumber(dataType_); return result == null ? com.google.cloud.channel.v1.Column.DataType.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(columnId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, columnId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_); } if (dataType_ != com.google.cloud.channel.v1.Column.DataType.DATA_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(3, dataType_); } 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(columnId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, columnId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_); } if (dataType_ != com.google.cloud.channel.v1.Column.DataType.DATA_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, dataType_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.channel.v1.Column)) { return super.equals(obj); } com.google.cloud.channel.v1.Column other = (com.google.cloud.channel.v1.Column) obj; if (!getColumnId().equals(other.getColumnId())) return false; if (!getDisplayName().equals(other.getDisplayName())) return false; if (dataType_ != other.dataType_) 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) + COLUMN_ID_FIELD_NUMBER; hash = (53 * hash) + getColumnId().hashCode(); hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER; hash = (53 * hash) + getDisplayName().hashCode(); hash = (37 * hash) + DATA_TYPE_FIELD_NUMBER; hash = (53 * hash) + dataType_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.channel.v1.Column parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.Column parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.Column parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.Column parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.Column parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.channel.v1.Column parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.channel.v1.Column parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.Column parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.channel.v1.Column parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.Column parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.channel.v1.Column parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.channel.v1.Column parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.channel.v1.Column 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 definition of a report column. Specifies the data properties * in the corresponding position of the report rows. * </pre> * * Protobuf type {@code google.cloud.channel.v1.Column} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.channel.v1.Column) com.google.cloud.channel.v1.ColumnOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.channel.v1.ReportsServiceProto .internal_static_google_cloud_channel_v1_Column_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.channel.v1.ReportsServiceProto .internal_static_google_cloud_channel_v1_Column_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.channel.v1.Column.class, com.google.cloud.channel.v1.Column.Builder.class); } // Construct using com.google.cloud.channel.v1.Column.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; columnId_ = ""; displayName_ = ""; dataType_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.channel.v1.ReportsServiceProto .internal_static_google_cloud_channel_v1_Column_descriptor; } @java.lang.Override public com.google.cloud.channel.v1.Column getDefaultInstanceForType() { return com.google.cloud.channel.v1.Column.getDefaultInstance(); } @java.lang.Override public com.google.cloud.channel.v1.Column build() { com.google.cloud.channel.v1.Column result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.channel.v1.Column buildPartial() { com.google.cloud.channel.v1.Column result = new com.google.cloud.channel.v1.Column(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.channel.v1.Column result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.columnId_ = columnId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.displayName_ = displayName_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.dataType_ = dataType_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.channel.v1.Column) { return mergeFrom((com.google.cloud.channel.v1.Column) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.channel.v1.Column other) { if (other == com.google.cloud.channel.v1.Column.getDefaultInstance()) return this; if (!other.getColumnId().isEmpty()) { columnId_ = other.columnId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getDisplayName().isEmpty()) { displayName_ = other.displayName_; bitField0_ |= 0x00000002; onChanged(); } if (other.dataType_ != 0) { setDataTypeValue(other.getDataTypeValue()); } 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: { columnId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { displayName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { dataType_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object columnId_ = ""; /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @return The columnId. */ public java.lang.String getColumnId() { java.lang.Object ref = columnId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); columnId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @return The bytes for columnId. */ public com.google.protobuf.ByteString getColumnIdBytes() { java.lang.Object ref = columnId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); columnId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @param value The columnId to set. * @return This builder for chaining. */ public Builder setColumnId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } columnId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @return This builder for chaining. */ public Builder clearColumnId() { columnId_ = getDefaultInstance().getColumnId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The unique name of the column (for example, customer_domain, * channel_partner, customer_cost). You can use column IDs in * [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. * To see all reports and their columns, call * [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. * </pre> * * <code>string column_id = 1;</code> * * @param value The bytes for columnId to set. * @return This builder for chaining. */ public Builder setColumnIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); columnId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object displayName_ = ""; /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @return The displayName. */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @return The bytes for displayName. */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @param value The displayName to set. * @return This builder for chaining. */ public Builder setDisplayName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } displayName_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @return This builder for chaining. */ public Builder clearDisplayName() { displayName_ = getDefaultInstance().getDisplayName(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The column's display name. * </pre> * * <code>string display_name = 2;</code> * * @param value The bytes for displayName to set. * @return This builder for chaining. */ public Builder setDisplayNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); displayName_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int dataType_ = 0; /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @return The enum numeric value on the wire for dataType. */ @java.lang.Override public int getDataTypeValue() { return dataType_; } /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @param value The enum numeric value on the wire for dataType to set. * @return This builder for chaining. */ public Builder setDataTypeValue(int value) { dataType_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @return The dataType. */ @java.lang.Override public com.google.cloud.channel.v1.Column.DataType getDataType() { com.google.cloud.channel.v1.Column.DataType result = com.google.cloud.channel.v1.Column.DataType.forNumber(dataType_); return result == null ? com.google.cloud.channel.v1.Column.DataType.UNRECOGNIZED : result; } /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @param value The dataType to set. * @return This builder for chaining. */ public Builder setDataType(com.google.cloud.channel.v1.Column.DataType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; dataType_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * The type of the values for this column. * </pre> * * <code>.google.cloud.channel.v1.Column.DataType data_type = 3;</code> * * @return This builder for chaining. */ public Builder clearDataType() { bitField0_ = (bitField0_ & ~0x00000004); dataType_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.channel.v1.Column) } // @@protoc_insertion_point(class_scope:google.cloud.channel.v1.Column) private static final com.google.cloud.channel.v1.Column DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.channel.v1.Column(); } public static com.google.cloud.channel.v1.Column getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Column> PARSER = new com.google.protobuf.AbstractParser<Column>() { @java.lang.Override public Column 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<Column> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Column> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.channel.v1.Column getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,858
java-oracledatabase/proto-google-cloud-oracledatabase-v1/src/main/java/com/google/cloud/oracledatabase/v1/GenerateAutonomousDatabaseWalletRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/oracledatabase/v1/oracledatabase.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.oracledatabase.v1; /** * * * <pre> * The request for `AutonomousDatabase.GenerateWallet`. * </pre> * * Protobuf type {@code google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest} */ public final class GenerateAutonomousDatabaseWalletRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest) GenerateAutonomousDatabaseWalletRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GenerateAutonomousDatabaseWalletRequest.newBuilder() to construct. private GenerateAutonomousDatabaseWalletRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GenerateAutonomousDatabaseWalletRequest() { name_ = ""; type_ = 0; password_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GenerateAutonomousDatabaseWalletRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_GenerateAutonomousDatabaseWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_GenerateAutonomousDatabaseWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest.class, com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest.Builder .class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </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 TYPE_FIELD_NUMBER = 2; private int type_ = 0; /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The type. */ @java.lang.Override public com.google.cloud.oracledatabase.v1.GenerateType getType() { com.google.cloud.oracledatabase.v1.GenerateType result = com.google.cloud.oracledatabase.v1.GenerateType.forNumber(type_); return result == null ? com.google.cloud.oracledatabase.v1.GenerateType.UNRECOGNIZED : result; } public static final int IS_REGIONAL_FIELD_NUMBER = 3; private boolean isRegional_ = false; /** * * * <pre> * Optional. True when requesting regional connection strings in PDB connect * info, applicable to cross-region Data Guard only. * </pre> * * <code>bool is_regional = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The isRegional. */ @java.lang.Override public boolean getIsRegional() { return isRegional_; } public static final int PASSWORD_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object password_ = ""; /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The password. */ @java.lang.Override public java.lang.String getPassword() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } } /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for password. */ @java.lang.Override public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); password_ = 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 (type_ != com.google.cloud.oracledatabase.v1.GenerateType.GENERATE_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(2, type_); } if (isRegional_ != false) { output.writeBool(3, isRegional_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(password_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, password_); } 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 (type_ != com.google.cloud.oracledatabase.v1.GenerateType.GENERATE_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, type_); } if (isRegional_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, isRegional_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(password_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, password_); } 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.GenerateAutonomousDatabaseWalletRequest)) { return super.equals(obj); } com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest other = (com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest) obj; if (!getName().equals(other.getName())) return false; if (type_ != other.type_) return false; if (getIsRegional() != other.getIsRegional()) return false; if (!getPassword().equals(other.getPassword())) 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) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + IS_REGIONAL_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getIsRegional()); hash = (37 * hash) + PASSWORD_FIELD_NUMBER; hash = (53 * hash) + getPassword().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest 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.GenerateAutonomousDatabaseWalletRequest 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 `AutonomousDatabase.GenerateWallet`. * </pre> * * Protobuf type {@code google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest) com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_GenerateAutonomousDatabaseWalletRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_GenerateAutonomousDatabaseWalletRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest.class, com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest.Builder .class); } // Construct using // com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; type_ = 0; isRegional_ = false; password_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_GenerateAutonomousDatabaseWalletRequest_descriptor; } @java.lang.Override public com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest getDefaultInstanceForType() { return com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest build() { com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest buildPartial() { com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest result = new com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.isRegional_ = isRegional_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.password_ = password_; } } @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.GenerateAutonomousDatabaseWalletRequest) { return mergeFrom( (com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest other) { if (other == com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest .getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (other.getIsRegional() != false) { setIsRegional(other.getIsRegional()); } if (!other.getPassword().isEmpty()) { password_ = other.password_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { type_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { isRegional_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { password_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the Autonomous Database in the following format: * projects/{project}/locations/{location}/autonomousDatabases/{autonomous_database}. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int type_ = 0; /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The type. */ @java.lang.Override public com.google.cloud.oracledatabase.v1.GenerateType getType() { com.google.cloud.oracledatabase.v1.GenerateType result = com.google.cloud.oracledatabase.v1.GenerateType.forNumber(type_); return result == null ? com.google.cloud.oracledatabase.v1.GenerateType.UNRECOGNIZED : result; } /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The type to set. * @return This builder for chaining. */ public Builder setType(com.google.cloud.oracledatabase.v1.GenerateType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; type_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Optional. The type of wallet generation for the Autonomous Database. The * default value is SINGLE. * </pre> * * <code> * .google.cloud.oracledatabase.v1.GenerateType type = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000002); type_ = 0; onChanged(); return this; } private boolean isRegional_; /** * * * <pre> * Optional. True when requesting regional connection strings in PDB connect * info, applicable to cross-region Data Guard only. * </pre> * * <code>bool is_regional = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The isRegional. */ @java.lang.Override public boolean getIsRegional() { return isRegional_; } /** * * * <pre> * Optional. True when requesting regional connection strings in PDB connect * info, applicable to cross-region Data Guard only. * </pre> * * <code>bool is_regional = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The isRegional to set. * @return This builder for chaining. */ public Builder setIsRegional(boolean value) { isRegional_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. True when requesting regional connection strings in PDB connect * info, applicable to cross-region Data Guard only. * </pre> * * <code>bool is_regional = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearIsRegional() { bitField0_ = (bitField0_ & ~0x00000004); isRegional_ = false; onChanged(); return this; } private java.lang.Object password_ = ""; /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The password. */ public java.lang.String getPassword() { java.lang.Object ref = password_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); password_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for password. */ public com.google.protobuf.ByteString getPasswordBytes() { java.lang.Object ref = password_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); password_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The password to set. * @return This builder for chaining. */ public Builder setPassword(java.lang.String value) { if (value == null) { throw new NullPointerException(); } password_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearPassword() { password_ = getDefaultInstance().getPassword(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Required. The password used to encrypt the keys inside the wallet. The * password must be a minimum of 8 characters. * </pre> * * <code>string password = 4 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for password to set. * @return This builder for chaining. */ public Builder setPasswordBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); password_ = 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.GenerateAutonomousDatabaseWalletRequest) } // @@protoc_insertion_point(class_scope:google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest) private static final com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest(); } public static com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GenerateAutonomousDatabaseWalletRequest> PARSER = new com.google.protobuf.AbstractParser<GenerateAutonomousDatabaseWalletRequest>() { @java.lang.Override public GenerateAutonomousDatabaseWalletRequest 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<GenerateAutonomousDatabaseWalletRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GenerateAutonomousDatabaseWalletRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.oracledatabase.v1.GenerateAutonomousDatabaseWalletRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/commons-lang
36,973
src/main/java/org/apache/commons/lang3/text/StrTokenizer.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.lang3.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 java.util.StringTokenizer; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; /** * 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 {@link ListIterator} interface. By default, it is set up * like {@link StringTokenizer}. * </p> * <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> * <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> * <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> * <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> * <p> * Empty tokens may be removed or returned as null. * </p> * <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>StrTokenizer 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 2.2 * @deprecated As of <a href="https://commons.apache.org/proper/commons-lang/changes-report.html#a3.6">3.6</a>, use Apache Commons Text * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringTokenizer.html"> * StringTokenizer</a>. */ @Deprecated public class StrTokenizer implements ListIterator<String>, Cloneable { // @formatter:off private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE = new StrTokenizer() .setDelimiterMatcher(StrMatcher.commaMatcher()) .setQuoteMatcher(StrMatcher.doubleQuoteMatcher()) .setIgnoredMatcher(StrMatcher.noneMatcher()) .setTrimmerMatcher(StrMatcher.trimMatcher()) .setEmptyTokenAsNull(false) .setIgnoreEmptyTokens(false); // @formatter:on // @formatter:off private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE = new StrTokenizer() .setDelimiterMatcher(StrMatcher.tabMatcher()) .setQuoteMatcher(StrMatcher.doubleQuoteMatcher()) .setIgnoredMatcher(StrMatcher.noneMatcher()) .setTrimmerMatcher(StrMatcher.trimMatcher()) .setEmptyTokenAsNull(false) .setIgnoreEmptyTokens(false); // @formatter:on /** * Gets a clone of {@code CSV_TOKENIZER_PROTOTYPE}. * * @return a clone of {@code CSV_TOKENIZER_PROTOTYPE}. */ private static StrTokenizer getCSVClone() { return (StrTokenizer) 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 StrTokenizer 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 StrTokenizer getCSVInstance(final char[] input) { final StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; } /** * 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 StrTokenizer getCSVInstance(final String input) { final StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; } /** * Gets a clone of {@code TSV_TOKENIZER_PROTOTYPE}. * * @return a clone of {@code TSV_TOKENIZER_PROTOTYPE}. */ private static StrTokenizer getTSVClone() { return (StrTokenizer) 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 StrTokenizer 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 StrTokenizer getTSVInstance(final char[] input) { final StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; } /** * 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 StrTokenizer getTSVInstance(final String input) { final StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; } /** 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 StrMatcher delimMatcher = StrMatcher.splitMatcher(); /** The quote matcher */ private StrMatcher quoteMatcher = StrMatcher.noneMatcher(); /** The ignored matcher */ private StrMatcher ignoredMatcher = StrMatcher.noneMatcher(); /** The trimmer matcher */ private StrMatcher trimmerMatcher = StrMatcher.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 formfeed * as per StringTokenizer, but with no text to tokenize. * <p> * This constructor is normally used with {@link #reset(String)}. * </p> */ public StrTokenizer() { this.chars = null; } /** * Constructs a tokenizer splitting on space, tab, newline and formfeed * as per StringTokenizer. * * @param input the string which is to be parsed, not cloned. */ public StrTokenizer(final char[] input) { this.chars = ArrayUtils.clone(input); } /** * 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 StrTokenizer(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 StrTokenizer(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 StrTokenizer(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 StrTokenizer(final char[] input, final StrMatcher 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 StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) { this(input, delim); setQuoteMatcher(quote); } /** * Constructs a tokenizer splitting on space, tab, newline and formfeed * as per StringTokenizer. * * @param input the string which is to be parsed. */ public StrTokenizer(final String input) { if (input != null) { chars = input.toCharArray(); } else { chars = 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 StrTokenizer(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 StrTokenizer(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 StrTokenizer(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 StrTokenizer(final String input, final StrMatcher 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 StrTokenizer(final String input, final StrMatcher delim, final StrMatcher 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 (StringUtils.isEmpty(tok)) { 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) { if (chars == null) { // still call tokenize as subclass may do some work final List<String> split = tokenize(null, 0, 0); tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY); } else { final List<String> 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 StrTokenizer cloned = (StrTokenizer) 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 StrMatcher getDelimiterMatcher() { return this.delimMatcher; } // Ignored /** * 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 StrMatcher 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 StrMatcher 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 array. */ public List<String> getTokenList() { checkTokenized(); final List<String> list = new ArrayList<>(tokens.length); list.addAll(Arrays.asList(tokens)); return list; } /** * 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 StrMatcher getTrimmerMatcher() { return trimmerMatcher; } /** * Checks whether there are any more tokens. * * @return true if there are more tokens. */ @Override public boolean hasNext() { checkTokenized(); return tokenPos < tokens.length; } /** * Checks 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; } /** * Gets 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; } /** * Gets 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; } /** * Checks 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 StrBuilder 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 StrBuilder 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 it's 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; } /** * 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 {@code this} instance. */ public StrTokenizer reset() { tokenPos = 0; tokens = null; return this; } /** * Reset 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 {@code this} instance. */ public StrTokenizer reset(final char[] input) { reset(); this.chars = ArrayUtils.clone(input); return this; } /** * Reset 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 {@code this} instance. */ public StrTokenizer reset(final String input) { reset(); if (input != null) { this.chars = input.toCharArray(); } else { this.chars = null; } return 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 StrTokenizer setDelimiterChar(final char delim) { return setDelimiterMatcher(StrMatcher.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 StrTokenizer setDelimiterMatcher(final StrMatcher delim) { if (delim == null) { this.delimMatcher = StrMatcher.noneMatcher(); } else { this.delimMatcher = delim; } return this; } /** * Sets the field delimiter string. * * @param delim the delimiter string to use. * @return this, to enable chaining. */ public StrTokenizer setDelimiterString(final String delim) { return setDelimiterMatcher(StrMatcher.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 StrTokenizer 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. * * @param ignored the ignored character to use. * @return this, to enable chaining. */ public StrTokenizer setIgnoredChar(final char ignored) { return setIgnoredMatcher(StrMatcher.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 {@code this} instance. */ public StrTokenizer setIgnoredMatcher(final StrMatcher 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 {@code this} instance. */ public StrTokenizer 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 {@code this} instance. */ public StrTokenizer setQuoteChar(final char quote) { return setQuoteMatcher(StrMatcher.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 {@code this} instance. */ public StrTokenizer setQuoteMatcher(final StrMatcher 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. * </p> * * @param trimmer the trimmer matcher to use, null ignored. * @return {@code this} instance. */ public StrTokenizer setTrimmerMatcher(final StrMatcher trimmer) { if (trimmer != null) { this.trimmerMatcher = trimmer; } return this; } // API /** * 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> * {@link 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 (ArrayUtils.isEmpty(srcChars)) { return Collections.emptyList(); } final StrBuilder buf = new StrBuilder(); 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 "StrTokenizer[not tokenized yet]"; } return "StrTokenizer" + getTokenList(); } }
apache/incubator-brooklyn
37,051
brooklyn-server/utils/common/src/main/java/org/apache/brooklyn/util/text/Strings.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.brooklyn.util.text; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import javax.annotation.Nullable; import org.apache.brooklyn.util.collections.MutableList; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.guava.Maybe; import org.apache.brooklyn.util.time.Time; import com.google.common.base.CharMatcher; import com.google.common.base.Functions; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Ordering; public class Strings { /** The empty {@link String}. */ public static final String EMPTY = ""; /** * Checks if the given string is null or is an empty string. * Useful for pre-String.isEmpty. And useful for StringBuilder etc. * * @param s the String to check * @return true if empty or null, false otherwise. * * @see #isNonEmpty(CharSequence) * @see #isBlank(CharSequence) * @see #isNonBlank(CharSequence) */ public static boolean isEmpty(CharSequence s) { // Note guava has com.google.common.base.Strings.isNullOrEmpty(String), // but that is just for String rather than CharSequence return s == null || s.length()==0; } /** * Checks if the given string is empty or only consists of whitespace. * * @param s the String to check * @return true if blank, empty or null, false otherwise. * * @see #isEmpty(CharSequence) * @see #isNonEmpty(CharSequence) * @see #isNonBlank(CharSequence) */ public static boolean isBlank(CharSequence s) { return isEmpty(s) || CharMatcher.WHITESPACE.matchesAllOf(s); } /** * The inverse of {@link #isEmpty(CharSequence)}. * * @param s the String to check * @return true if non empty, false otherwise. * * @see #isEmpty(CharSequence) * @see #isBlank(CharSequence) * @see #isNonBlank(CharSequence) */ public static boolean isNonEmpty(CharSequence s) { return !isEmpty(s); } /** * The inverse of {@link #isBlank(CharSequence)}. * * @param s the String to check * @return true if non blank, false otherwise. * * @see #isEmpty(CharSequence) * @see #isNonEmpty(CharSequence) * @see #isBlank(CharSequence) */ public static boolean isNonBlank(CharSequence s) { return !isBlank(s); } /** @return a {@link Maybe} object which is absent if the argument {@link #isBlank(CharSequence)} */ public static <T extends CharSequence> Maybe<T> maybeNonBlank(T s) { if (isNonBlank(s)) return Maybe.of(s); return Maybe.absent(); } /** throws IllegalArgument if string not empty; cf. guava Preconditions.checkXxxx */ public static void checkNonEmpty(CharSequence s) { if (s==null) throw new IllegalArgumentException("String must not be null"); if (s.length()==0) throw new IllegalArgumentException("String must not be empty"); } /** throws IllegalArgument if string not empty; cf. guava Preconditions.checkXxxx */ public static void checkNonEmpty(CharSequence s, String message) { if (isEmpty(s)) throw new IllegalArgumentException(message); } /** * Removes suffix from the end of the string. Returns string if it does not end with suffix. */ public static String removeFromEnd(String string, String suffix) { if (isEmpty(string)) { return string; } else if (!isEmpty(suffix) && string.endsWith(suffix)) { return string.substring(0, string.length() - suffix.length()); } else { return string; } } /** * As removeFromEnd, but repeats until all such suffixes are gone */ public static String removeAllFromEnd(String string, String... suffixes) { if (isEmpty(string)) return string; int index = string.length(); boolean anotherLoopNeeded = true; while (anotherLoopNeeded) { if (isEmpty(string)) return string; anotherLoopNeeded = false; for (String suffix : suffixes) if (!isEmpty(suffix) && string.startsWith(suffix, index - suffix.length())) { index -= suffix.length(); anotherLoopNeeded = true; break; } } return string.substring(0, index); } /** * Removes prefix from the beginning of string. Returns string if it does not begin with prefix. */ public static String removeFromStart(String string, String prefix) { if (isEmpty(string)) { return string; } else if (!isEmpty(prefix) && string.startsWith(prefix)) { return string.substring(prefix.length()); } else { return string; } } /** * As {@link #removeFromStart(String, String)}, repeating until all such prefixes are gone. */ public static String removeAllFromStart(String string, String... prefixes) { int index = 0; boolean anotherLoopNeeded = true; while (anotherLoopNeeded) { if (isEmpty(string)) return string; anotherLoopNeeded = false; for (String prefix : prefixes) { if (!isEmpty(prefix) && string.startsWith(prefix, index)) { index += prefix.length(); anotherLoopNeeded = true; break; } } } return string.substring(index); } /** convenience for {@link com.google.common.base.Joiner} */ public static String join(Iterable<? extends Object> list, String separator) { if (list==null) return null; boolean app = false; StringBuilder out = new StringBuilder(); for (Object s: list) { if (app) out.append(separator); out.append(s); app = true; } return out.toString(); } /** convenience for {@link com.google.common.base.Joiner} */ public static String join(Object[] list, String separator) { boolean app = false; StringBuilder out = new StringBuilder(); for (Object s: list) { if (app) out.append(separator); out.append(s); app = true; } return out.toString(); } /** convenience for joining lines together */ public static String lines(String ...lines) { return Joiner.on("\n").join(Arrays.asList(lines)); } /** NON-REGEX - replaces all key->value entries from the replacement map in source (non-regex) */ @SuppressWarnings("rawtypes") public static String replaceAll(String source, Map replacements) { for (Object rr: replacements.entrySet()) { Map.Entry r = (Map.Entry)rr; source = replaceAllNonRegex(source, ""+r.getKey(), ""+r.getValue()); } return source; } /** NON-REGEX replaceAll - see the better, explicitly named {@link #replaceAllNonRegex(String, String, String)}. */ public static String replaceAll(String source, String pattern, String replacement) { return replaceAllNonRegex(source, pattern, replacement); } /** * Replaces all instances in source, of the given pattern, with the given replacement * (not interpreting any arguments as regular expressions). * <p> * This is actually the same as the very ambiguous {@link String#replace(CharSequence, CharSequence)}, * which does replace all, but not using regex like the similarly ambiguous {@link String#replaceAll(String, String)} as. * Alternatively see {@link #replaceAllRegex(String, String, String)}. */ public static String replaceAllNonRegex(String source, String pattern, String replacement) { if (source==null) return source; StringBuilder result = new StringBuilder(source.length()); for (int i=0; i<source.length(); ) { if (source.substring(i).startsWith(pattern)) { result.append(replacement); i += pattern.length(); } else { result.append(source.charAt(i)); i++; } } return result.toString(); } /** REGEX replacement -- explicit method name for readability, doing same as {@link String#replaceAll(String, String)}. */ public static String replaceAllRegex(String source, String pattern, String replacement) { return source.replaceAll(pattern, replacement); } /** Valid non alphanumeric characters for filenames. */ public static final String VALID_NON_ALPHANUM_FILE_CHARS = "-_."; /** * Returns a valid filename based on the input. * * A valid filename starts with the first alphanumeric character, then include * all alphanumeric characters plus those in {@link #VALID_NON_ALPHANUM_FILE_CHARS}, * with any runs of invalid characters being replaced by {@literal _}. * * @throws NullPointerException if the input string is null. * @throws IllegalArgumentException if the input string is blank. */ public static String makeValidFilename(String s) { Preconditions.checkNotNull(s, "Cannot make valid filename from null string"); Preconditions.checkArgument(isNonBlank(s), "Cannot make valid filename from blank string"); return CharMatcher.anyOf(VALID_NON_ALPHANUM_FILE_CHARS).or(CharMatcher.JAVA_LETTER_OR_DIGIT) .negate() .trimAndCollapseFrom(s, '_'); } /** * A {@link CharMatcher} that matches valid Java identifier characters. * * @see Character#isJavaIdentifierPart(char) */ public static final CharMatcher IS_JAVA_IDENTIFIER_PART = CharMatcher.forPredicate(new Predicate<Character>() { @Override public boolean apply(@Nullable Character input) { return input != null && Character.isJavaIdentifierPart(input); } }); /** * Returns a valid Java identifier name based on the input. * * Removes certain characterss (like apostrophe), replaces one or more invalid * characterss with {@literal _}, and prepends {@literal _} if the first character * is only valid as an identifier part (not start). * <p> * The result is usually unique to s, though this isn't guaranteed, for example if * all characters are invalid. For a unique identifier use {@link #makeValidUniqueJavaName(String)}. * * @see #makeValidUniqueJavaName(String) */ public static String makeValidJavaName(String s) { if (s==null) return "__null"; if (s.length()==0) return "__empty"; String name = IS_JAVA_IDENTIFIER_PART.negate().collapseFrom(CharMatcher.is('\'').removeFrom(s), '_'); if (!Character.isJavaIdentifierStart(s.charAt(0))) return "_" + name; return name; } /** * Returns a unique valid java identifier name based on the input. * * Translated as per {@link #makeValidJavaName(String)} but with {@link String#hashCode()} * appended where necessary to guarantee uniqueness. * * @see #makeValidJavaName(String) */ public static String makeValidUniqueJavaName(String s) { String name = makeValidJavaName(s); if (isEmpty(s) || IS_JAVA_IDENTIFIER_PART.matchesAllOf(s) || CharMatcher.is('\'').matchesNoneOf(s)) { return name; } else { return name + "_" + s.hashCode(); } } /** @see {@link Identifiers#makeRandomId(int)} */ public static String makeRandomId(int l) { return Identifiers.makeRandomId(l); } /** pads the string with 0's at the left up to len; no padding if i longer than len */ public static String makeZeroPaddedString(int i, int len) { return makePaddedString(""+i, len, "0", ""); } /** pads the string with "pad" at the left up to len; no padding if base longer than len */ public static String makePaddedString(String base, int len, String left_pad, String right_pad) { String s = ""+(base==null ? "" : base); while (s.length()<len) s=left_pad+s+right_pad; return s; } public static void trimAll(String[] s) { for (int i=0; i<s.length; i++) s[i] = (s[i]==null ? "" : s[i].trim()); } /** creates a string from a real number, with specified accuracy (more iff it comes for free, ie integer-part); * switches to E notation if needed to fit within maxlen; can be padded left up too (not useful) * @param x number to use * @param maxlen maximum length for the numeric string, if possible (-1 to suppress) * @param prec number of digits accuracy desired (more kept for integers) * @param leftPadLen will add spaces at left if necessary to make string this long (-1 to suppress) [probably not usef] * @return such a string */ public static String makeRealString(double x, int maxlen, int prec, int leftPadLen) { return makeRealString(x, maxlen, prec, leftPadLen, 0.00000000001, true); } /** creates a string from a real number, with specified accuracy (more iff it comes for free, ie integer-part); * switches to E notation if needed to fit within maxlen; can be padded left up too (not useful) * @param x number to use * @param maxlen maximum length for the numeric string, if possible (-1 to suppress) * @param prec number of digits accuracy desired (more kept for integers) * @param leftPadLen will add spaces at left if necessary to make string this long (-1 to suppress) [probably not usef] * @param skipDecimalThreshhold if positive it will not add a decimal part if the fractional part is less than this threshhold * (but for a value 3.00001 it would show zeroes, e.g. with 3 precision and positive threshhold <= 0.00001 it would show 3.00); * if zero or negative then decimal digits are always shown * @param useEForSmallNumbers whether to use E notation for numbers near zero (e.g. 0.001) * @return such a string */ public static String makeRealString(double x, int maxlen, int prec, int leftPadLen, double skipDecimalThreshhold, boolean useEForSmallNumbers) { if (x<0) return "-"+makeRealString(-x, maxlen, prec, leftPadLen); NumberFormat df = DecimalFormat.getInstance(); //df.setMaximumFractionDigits(maxlen); df.setMinimumFractionDigits(0); //df.setMaximumIntegerDigits(prec); df.setMinimumIntegerDigits(1); df.setGroupingUsed(false); String s; if (x==0) { if (skipDecimalThreshhold>0 || prec<=1) s="0"; else { s="0.0"; while (s.length()<prec+1) s+="0"; } } else { // long bits= Double.doubleToLongBits(x); // int s = ((bits >> 63) == 0) ? 1 : -1; // int e = (int)((bits >> 52) & 0x7ffL); // long m = (e == 0) ? // (bits & 0xfffffffffffffL) << 1 : // (bits & 0xfffffffffffffL) | 0x10000000000000L; // //s*m*2^(e-1075); int log = (int)Math.floor(Math.log10(x)); int numFractionDigits = (log>=prec ? 0 : prec-log-1); if (numFractionDigits>0) { //need decimal digits if (skipDecimalThreshhold>0) { int checkFractionDigits = 0; double multiplier = 1; while (checkFractionDigits < numFractionDigits) { if (Math.abs(x - Math.rint(x*multiplier)/multiplier)<skipDecimalThreshhold) break; checkFractionDigits++; multiplier*=10; } numFractionDigits = checkFractionDigits; } df.setMinimumFractionDigits(numFractionDigits); df.setMaximumFractionDigits(numFractionDigits); } else { //x = Math.rint(x); df.setMaximumFractionDigits(0); } s = df.format(x); if (maxlen>0 && s.length()>maxlen) { //too long: double signif = x/Math.pow(10,log); if (s.indexOf(getDefaultDecimalSeparator())>=0) { //have a decimal point; either we are very small 0.000001 //or prec is larger than maxlen if (Math.abs(x)<1 && useEForSmallNumbers) { //very small-- use alternate notation s = makeRealString(signif, -1, prec, -1) + "E"+log; } else { //leave it alone, user error or E not wanted } } else { //no decimal point, integer part is too large, use alt notation s = makeRealString(signif, -1, prec, -1) + "E"+log; } } } if (leftPadLen>s.length()) return makePaddedString(s, leftPadLen, " ", ""); else return s; } /** creates a string from a real number, with specified accuracy (more iff it comes for free, ie integer-part); * switches to E notation if needed to fit within maxlen; can be padded left up too (not useful) * @param x number to use * @param maxlen maximum length for the numeric string, if possible (-1 to suppress) * @param prec number of digits accuracy desired (more kept for integers) * @param leftPadLen will add spaces at left if necessary to make string this long (-1 to suppress) [probably not usef] * @return such a string */ public static String makeRealStringNearZero(double x, int maxlen, int prec, int leftPadLen) { if (Math.abs(x)<0.0000000001) x=0; NumberFormat df = DecimalFormat.getInstance(); //df.setMaximumFractionDigits(maxlen); df.setMinimumFractionDigits(0); //df.setMaximumIntegerDigits(prec); df.setMinimumIntegerDigits(1); df.setGroupingUsed(false); String s; if (x==0) { if (prec<=1) s="0"; else { s="0.0"; while (s.length()<prec+1) s+="0"; } } else { // long bits= Double.doubleToLongBits(x); // int s = ((bits >> 63) == 0) ? 1 : -1; // int e = (int)((bits >> 52) & 0x7ffL); // long m = (e == 0) ? // (bits & 0xfffffffffffffL) << 1 : // (bits & 0xfffffffffffffL) | 0x10000000000000L; // //s*m*2^(e-1075); int log = (int)Math.floor(Math.log10(x)); int scale = (log>=prec ? 0 : prec-log-1); if (scale>0) { //need decimal digits double scale10 = Math.pow(10, scale); x = Math.rint(x*scale10)/scale10; df.setMinimumFractionDigits(scale); df.setMaximumFractionDigits(scale); } else { //x = Math.rint(x); df.setMaximumFractionDigits(0); } s = df.format(x); if (maxlen>0 && s.length()>maxlen) { //too long: double signif = x/Math.pow(10,log); if (s.indexOf('.')>=0) { //have a decimal point; either we are very small 0.000001 //or prec is larger than maxlen if (Math.abs(x)<1) { //very small-- use alternate notation s = makeRealString(signif, -1, prec, -1) + "E"+log; } else { //leave it alone, user error } } else { //no decimal point, integer part is too large, use alt notation s = makeRealString(signif, -1, prec, -1) + "E"+log; } } } if (leftPadLen>s.length()) return makePaddedString(s, leftPadLen, " ", ""); else return s; } /** returns the first word (whitespace delimited text), or null if there is none (input null or all whitespace) */ public static String getFirstWord(String s) { if (s==null) return null; int start = 0; while (start<s.length()) { if (!Character.isWhitespace(s.charAt(start))) break; start++; } int end = start; if (end >= s.length()) return null; while (end<s.length()) { if (Character.isWhitespace(s.charAt(end))) break; end++; } return s.substring(start, end); } /** returns the last word (whitespace delimited text), or null if there is none (input null or all whitespace) */ public static String getLastWord(String s) { if (s==null) return null; int end = s.length()-1; while (end >= 0) { if (!Character.isWhitespace(s.charAt(end))) break; end--; } int start = end; if (start < 0) return null; while (start >= 0) { if (Character.isWhitespace(s.charAt(start))) break; start--; } return s.substring(start+1, end+1); } /** returns the first word after the given phrase, or null if no such phrase; * if the character immediately after the phrase is not whitespace, the non-whitespace * sequence starting with that character will be returned */ public static String getFirstWordAfter(String context, String phrase) { if (context==null || phrase==null) return null; int index = context.indexOf(phrase); if (index<0) return null; return getFirstWord(context.substring(index + phrase.length())); } /** * searches in context for the given phrase, and returns the <b>untrimmed</b> remainder of the first line * on which the phrase is found */ public static String getRemainderOfLineAfter(String context, String phrase) { if (context == null || phrase == null) return null; int index = context.indexOf(phrase); if (index < 0) return null; int lineEndIndex = context.indexOf("\n", index); if (lineEndIndex <= 0) { return context.substring(index + phrase.length()); } else { return context.substring(index + phrase.length(), lineEndIndex); } } /** @deprecated use {@link Time#makeTimeStringRounded(long)} */ @Deprecated public static String makeTimeString(long utcMillis) { return Time.makeTimeStringRounded(utcMillis); } /** returns e.g. { "prefix01", ..., "prefix96" }; * see more functional NumericRangeGlobExpander for "prefix{01-96}" */ public static String[] makeArray(String prefix, int count) { String[] result = new String[count]; int len = (""+count).length(); for (int i=1; i<=count; i++) result[i-1] = prefix + makePaddedString("", len, "0", ""+i); return result; } public static String[] combineArrays(String[] ...arrays) { int totalLen = 0; for (String[] array : arrays) { if (array!=null) totalLen += array.length; } String[] result = new String[totalLen]; int i=0; for (String[] array : arrays) { if (array!=null) for (String s : array) { result[i++] = s; } } return result; } public static String toInitialCapOnly(String value) { if (value==null || value.length()==0) return value; return value.substring(0, 1).toUpperCase(Locale.ENGLISH) + value.substring(1).toLowerCase(Locale.ENGLISH); } public static String reverse(String name) { return new StringBuffer(name).reverse().toString(); } public static boolean isLowerCase(String s) { return s.toLowerCase().equals(s); } public static String makeRepeated(char c, int length) { StringBuilder result = new StringBuilder(length); for (int i = 0; i < length; i++) { result.append(c); } return result.toString(); } public static String trim(String s) { if (s==null) return null; return s.trim(); } public static String trimEnd(String s) { if (s==null) return null; return ("a"+s).trim().substring(1); } /** returns up to maxlen characters from the start of s */ public static String maxlen(String s, int maxlen) { return maxlenWithEllipsis(s, maxlen, ""); } /** as {@link #maxlenWithEllipsis(String, int, String) with "..." as the ellipsis */ public static String maxlenWithEllipsis(String s, int maxlen) { return maxlenWithEllipsis(s, maxlen, "..."); } /** as {@link #maxlenWithEllipsis(String, int) but replacing the last few chars with the given ellipsis */ public static String maxlenWithEllipsis(String s, int maxlen, String ellipsis) { if (s==null) return null; if (ellipsis==null) ellipsis=""; if (s.length()<=maxlen) return s; return s.substring(0, Math.max(maxlen-ellipsis.length(), 0))+ellipsis; } /** returns toString of the object if it is not null, otherwise null */ public static String toString(Object o) { return toStringWithValueForNull(o, null); } /** returns toString of the object if it is not null, otherwise the given value */ public static String toStringWithValueForNull(Object o, String valueIfNull) { if (o==null) return valueIfNull; return o.toString(); } public static boolean containsLiteralIgnoreCase(CharSequence input, CharSequence fragment) { if (input==null) return false; if (isEmpty(fragment)) return true; int lastValidStartPos = input.length()-fragment.length(); char f0u = Character.toUpperCase(fragment.charAt(0)); char f0l = Character.toLowerCase(fragment.charAt(0)); i: for (int i=0; i<=lastValidStartPos; i++) { char ii = input.charAt(i); if (ii==f0l || ii==f0u) { for (int j=1; j<fragment.length(); j++) { if (Character.toLowerCase(input.charAt(i+j))!=Character.toLowerCase(fragment.charAt(j))) continue i; } return true; } } return false; } public static boolean containsLiteral(CharSequence input, CharSequence fragment) { if (input==null) return false; if (isEmpty(fragment)) return true; int lastValidStartPos = input.length()-fragment.length(); char f0 = fragment.charAt(0); i: for (int i=0; i<=lastValidStartPos; i++) { char ii = input.charAt(i); if (ii==f0) { for (int j=1; j<fragment.length(); j++) { if (input.charAt(i+j)!=fragment.charAt(j)) continue i; } return true; } } return false; } /** Returns a size string using metric suffixes from {@link ByteSizeStrings#metric()}, e.g. 23.5MB */ public static String makeSizeString(long sizeInBytes) { return ByteSizeStrings.metric().makeSizeString(sizeInBytes); } /** Returns a size string using ISO suffixes from {@link ByteSizeStrings#iso()}, e.g. 23.5MiB */ public static String makeISOSizeString(long sizeInBytes) { return ByteSizeStrings.iso().makeSizeString(sizeInBytes); } /** Returns a size string using Java suffixes from {@link ByteSizeStrings#java()}, e.g. 23m */ public static String makeJavaSizeString(long sizeInBytes) { return ByteSizeStrings.java().makeSizeString(sizeInBytes); } /** returns a configurable shortener */ public static StringShortener shortener() { return new StringShortener(); } public static Supplier<String> toStringSupplier(Object src) { return Suppliers.compose(Functions.toStringFunction(), Suppliers.ofInstance(src)); } /** wraps a call to {@link String#format(String, Object...)} in a toString, i.e. using %s syntax, * useful for places where we want deferred evaluation * (e.g. as message to {@link Preconditions} to skip concatenation when not needed) */ public static FormattedString format(String pattern, Object... args) { return new FormattedString(pattern, args); } /** returns "s" if the argument is not 1, empty string otherwise; useful when constructing plurals */ public static String s(int count) { return count==1 ? "" : "s"; } /** as {@link #s(int)} based on size of argument */ public static String s(@Nullable Map<?,?> x) { return s(x==null ? 0 : x.size()); } /** as {@link #s(int)} based on size of argument */ public static String s(Iterable<?> x) { if (x==null) return s(0); return s(x.iterator()); } /** as {@link #s(int)} based on size of argument */ public static String s(Iterator<?> x) { int count = 0; if (x==null || !x.hasNext()) {} else { x.next(); count++; if (x.hasNext()) count++; } return s(count); } /** returns "ies" if the argument is not 1, "y" otherwise; useful when constructing plurals */ public static String ies(int count) { return count==1 ? "y" : "ies"; } /** as {@link #ies(int)} based on size of argument */ public static String ies(@Nullable Map<?,?> x) { return ies(x==null ? 0 : x.size()); } /** as {@link #ies(int)} based on size of argument */ public static String ies(Iterable<?> x) { if (x==null) return ies(0); return ies(x.iterator()); } /** as {@link #ies(int)} based on size of argument */ public static String ies(Iterator<?> x) { int count = 0; if (x==null || !x.hasNext()) {} else { x.next(); count++; if (x.hasNext()) count++; } return ies(count); } /** converts a map of any objects to a map of strings, using the tostring, and returning "null" for nulls * @deprecated since 0.7.0 use {@link #toStringMap(Map, String)} to remove ambiguity about how to handle null */ // NB previously the javadoc here was wrong, said it returned null not "null" @Deprecated public static Map<String, String> toStringMap(Map<?,?> map) { return toStringMap(map, "null"); } /** converts a map of any objects to a map of strings, using {@link Object#toString()}, * with the second argument used where a value (or key) is null */ public static Map<String, String> toStringMap(Map<?,?> map, String valueIfNull) { if (map==null) return null; Map<String,String> result = MutableMap.<String, String>of(); for (Map.Entry<?,?> e: map.entrySet()) { result.put(toStringWithValueForNull(e.getKey(), valueIfNull), toStringWithValueForNull(e.getValue(), valueIfNull)); } return result; } /** converts a list of any objects to a list of strings, using {@link Object#toString()}, * with the second argument used where an entry is null */ public static List<String> toStringList(List<?> list, String valueIfNull) { if (list==null) return null; List<String> result = MutableList.of(); for (Object v: list) result.add(toStringWithValueForNull(v, valueIfNull)); return result; } /** returns base repeated count times */ public static String repeat(String base, int count) { if (base==null) return null; StringBuilder result = new StringBuilder(); for (int i=0; i<count; i++) result.append(base); return result.toString(); } /** returns comparator which compares based on length, with shorter ones first (and null before that); * in event of a tie, it uses the toString order */ public static Ordering<String> lengthComparator() { return Ordering.<Integer>natural().onResultOf(StringFunctions.length()).compound(Ordering.<String>natural()).nullsFirst(); } public static boolean isMultiLine(String s) { if (s==null) return false; if (s.indexOf('\n')>=0 || s.indexOf('\r')>=0) return true; return false; } public static String getFirstLine(String s) { int idx = s.indexOf('\n'); if (idx==-1) return s; return s.substring(0, idx); } /** looks for first section of text in following the prefix and, if present, before the suffix; * null if the prefix is not present in the string, and everything after the prefix if suffix is not present in the string; * if either prefix or suffix is null, it is treated as the start/end of the string */ public static String getFragmentBetween(String input, String prefix, String suffix) { if (input==null) return null; int index; if (prefix!=null) { index = input.indexOf(prefix); if (index==-1) return null; input = input.substring(index + prefix.length()); } if (suffix!=null) { index = input.indexOf(suffix); if (index>=0) input = input.substring(0, index); } return input; } public static int getWordCount(String phrase, boolean respectQuotes) { if (phrase==null) return 0; phrase = phrase.trim(); if (respectQuotes) return new QuotedStringTokenizer(phrase).remainderAsList().size(); else return Collections.list(new StringTokenizer(phrase)).size(); } public static char getDecimalSeparator(Locale locale) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale); return dfs.getDecimalSeparator(); } public static char getDefaultDecimalSeparator() { return getDecimalSeparator(Locale.getDefault()); } /** replaces each sequence of whitespace in the first string with the replacement in the second string */ public static String collapseWhitespace(String x, String whitespaceReplacement) { if (x==null) return null; return replaceAllRegex(x, "\\s+", whitespaceReplacement); } public static String toLowerCase(String value) { if (value==null || value.length()==0) return value; return value.toLowerCase(Locale.ENGLISH); } /** * @return null if var is null or empty string, otherwise return var */ public static String emptyToNull(String var) { if (isNonEmpty(var)) { return var; } else { return null; } } /** Returns canonicalized string from the given object, made "unique" by: * <li> putting sets into the toString order * <li> appending a hash code if it's longer than the max (and the max is bigger than 0) */ public static String toUniqueString(Object x, int optionalMax) { if (x instanceof Iterable && !(x instanceof List)) { // unsorted collections should have a canonical order imposed MutableList<String> result = MutableList.of(); for (Object xi: (Iterable<?>)x) { result.add(toUniqueString(xi, optionalMax)); } Collections.sort(result); x = result.toString(); } if (x==null) return "{null}"; String xs = x.toString(); if (xs.length()<=optionalMax || optionalMax<=0) return xs; return maxlenWithEllipsis(xs, optionalMax-8)+"/"+Integer.toHexString(xs.hashCode()); } }
oracle/coherence
36,759
prj/coherence-core-components/src/main/java/com/tangosol/coherence/component/net/Security.java
/* * Copyright (c) 2000, 2025, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ // ---- class: com.tangosol.coherence.component.net.Security package com.tangosol.coherence.component.net; import com.tangosol.coherence.component.application.console.Coherence; import com.tangosol.coherence.component.net.security.Standard; import com.tangosol.internal.net.security.DefaultSecurityDependencies; import com.tangosol.internal.net.security.DefaultStandardDependencies; import com.tangosol.internal.net.security.LegacyXmlStandardHelper; import com.tangosol.net.CacheFactory; import com.tangosol.net.ClusterDependencies; import com.tangosol.net.ClusterPermission; import com.tangosol.net.security.Authorizer; import com.tangosol.net.security.DefaultIdentityAsserter; import com.tangosol.net.security.DefaultIdentityTransformer; import com.tangosol.net.security.DoAsAction; import com.tangosol.net.security.IdentityAsserter; import com.tangosol.net.security.IdentityTransformer; import com.tangosol.net.security.SecurityHelper; import com.tangosol.run.xml.XmlElement; import com.tangosol.util.Base; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import javax.security.auth.Subject; /** * The base component for the Coherence Security framework implementation. * * The basic pattern of usage is: * * Security security = Security.getInstance(); * if (security != null) * { * security.checkPermission(cluster, * new ClusterPermission(sTarget, sAction)); * } * * alternatively there is a helper method: * * Security.checkPermission(cluster, sService, sCache, sAction); * * that incapsulates the above logic where basically: * sTarget = sService +'/' + sCache; * * The oddities in the design of this Component tree are historical; prior to * Coherence 3.6, we had the following requirment: * * "The Security component itself MUST NOT be J2SE 1.4 dependent." */ @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public abstract class Security extends com.tangosol.coherence.component.Net implements java.security.PrivilegedAction { // ---- Fields declarations ---- /** * Property Authorizer * * Authorizer represents an environment-specific facility for authorizing * callers to perform actions described by the corresponding permission * objects. */ private static transient com.tangosol.net.security.Authorizer __s_Authorizer; /** * Property Configured * * Is security already configured? * * @volatile - else if getInstance were called concurrently when not yet * configured, one thread could see configured as true but not see the * corresponding Security instance. This can then result in the * PermissionInfo not getting inserted into the ServiceContext. Bug 27376204 */ private static volatile transient boolean __s_Configured; /** * Property IdentityAsserter * * IdentityAsserter validates a token in order to establish a user's * identity. */ private static transient com.tangosol.net.security.IdentityAsserter __s_IdentityAsserter; /** * Property IdentityTransformer * * IdentityTransformer transforms a Subject to a token that asserts * identity. */ private static transient com.tangosol.net.security.IdentityTransformer __s_IdentityTransformer; /** * Property Instance * * The Security instance. */ private static transient Security __s_Instance; /** * Property SubjectScoped * * Indicates if the security configuration specifies subject scoping. */ private static transient boolean __s_SubjectScoped; private static com.tangosol.util.ListMap __mapChildren; // Static initializer static { __initStatic(); } // Default static initializer private static void __initStatic() { // register child classes __mapChildren = new com.tangosol.util.ListMap(); __mapChildren.put("CheckPermissionAction", Security.CheckPermissionAction.get_CLASS()); __mapChildren.put("ConfigAction", Security.ConfigAction.get_CLASS()); __mapChildren.put("RefAction", Security.RefAction.get_CLASS()); } // Initializing constructor public Security(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object for a * given component. */ public static Class get_CLASS() { Class clz; try { clz = Class.forName("com.tangosol.coherence/component/net/Security".replace('/', '.')); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.getMessage()); } return clz; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design time] * parent component. * * Note: the class generator will ignore any custom implementation for this * behavior. */ private com.tangosol.coherence.Component get_Module() { return this; } //++ getter for autogen property _ChildClasses /** * This is an auto-generated method that returns the map of design time * [static] children. * * Note: the class generator will ignore any custom implementation for this * behavior. */ protected java.util.Map get_ChildClasses() { return __mapChildren; } /** * Security API exposed to the all Service components. Called on a client * thread. */ public void checkPermission(com.tangosol.net.Cluster cluster, com.tangosol.net.ClusterPermission permission, javax.security.auth.Subject subject) { } /** * Helper method around "Security API". */ public static void checkPermission(com.tangosol.net.Cluster cluster, String sServiceName, String sCacheName, String sAction) { // import com.tangosol.net.ClusterPermission; // import com.tangosol.net.security.Authorizer; // import com.tangosol.net.security.DoAsAction; // import javax.security.auth.Subject; Authorizer authorizer = getAuthorizer(); Security security = Security.getInstance(); if (authorizer == null && security == null) { return; } _assert(sServiceName != null, "Service must be specified"); String sTarget = "service=" + sServiceName + (sCacheName == null ? "" : ",cache=" + sCacheName); ClusterPermission permission = new ClusterPermission(cluster == null || !cluster.isRunning() ? null : cluster.getClusterName(), sTarget, sAction); Subject subject = null; if (authorizer != null) { subject = authorizer.authorize(subject, permission); } if (security != null) { Security.CheckPermissionAction action = new Security.CheckPermissionAction(); action.setCluster(cluster); action.setPermission(permission); action.setSubject(subject); action.setSecurity(security); SecurityHelper.doPrivileged(new DoAsAction(action)); } } /** * Create a new Default dependencies object by cloning the input * dependencies. Each class or component that uses dependencies implements * a Default dependencies class which provides the clone functionality. * The dependency injection design pattern requires every component in the * component hierarchy to implement clone. * * @return DefaultSecurityDependencies the cloned dependencies */ public static com.tangosol.internal.net.security.DefaultSecurityDependencies cloneDeps(com.tangosol.internal.net.security.SecurityDependencies deps) { // import com.tangosol.internal.net.security.DefaultSecurityDependencies; return new DefaultSecurityDependencies(deps); } /** * Declared as public only to be accessed by the action. */ public static synchronized void configureSecurity() { // import Component.Application.Console.Coherence; // import Component.Net.Security.Standard; // import com.tangosol.internal.net.security.DefaultStandardDependencies; // import com.tangosol.internal.net.security.LegacyXmlStandardHelper; // import com.tangosol.run.xml.XmlElement; if (isConfigured()) { return; } DefaultStandardDependencies deps = null; Security security = null; try { // create security dependencies including default values deps = new DefaultStandardDependencies(); // internal call equivalent to "CacheFactory.getSecurityConfig();" XmlElement xmlConfig = Coherence.getServiceConfig("$Security"); ClusterDependencies depsCluster = CacheFactory.getCluster().getDependencies(); if (xmlConfig != null) { // load the security dependencies given the xml config deps = LegacyXmlStandardHelper.fromXml(xmlConfig, deps, depsCluster); if (deps.isEnabled()) { // "model" element is not documented for now security = (Standard) _newInstance("Component.Net.Security." + deps.getModel()); } } } finally { // if Security is not instantiated, we still neeed to process // the dependencies to pickup the IdentityAsserter and IdentityTransformer // objects for the Security component (see onDeps()). if (security == null) { processDependencies(deps.validate()); } else { // load the standard dependencies (currently only support Standard) if (deps.getModel().equals("Standard")) { ((Standard) security).setDependencies(deps); } setInstance(security); } setConfigured(true); } } /** * Helper method. */ public static java.security.PrivilegedAction createPrivilegedAction(java.lang.reflect.Method method) { Security.RefAction action = new Security.RefAction(); action.setMethod(method); return action; } /** * Helper method. */ public static java.security.PrivilegedAction createPrivilegedAction(java.lang.reflect.Method method, Object oTarget, Object[] aoArg) { Security.RefAction action = new Security.RefAction(); action.setMethod(method); action.setTarget(oTarget); action.setArguments(aoArg); return action; } // Accessor for the property "Authorizer" /** * Getter for property Authorizer.<p> * Authorizer represents an environment-specific facility for authorizing * callers to perform actions described by the corresponding permission * objects. */ public static com.tangosol.net.security.Authorizer getAuthorizer() { return __s_Authorizer; } // Accessor for the property "IdentityAsserter" /** * Getter for property IdentityAsserter.<p> * IdentityAsserter validates a token in order to establish a user's * identity. */ public static com.tangosol.net.security.IdentityAsserter getIdentityAsserter() { return __s_IdentityAsserter; } // Accessor for the property "IdentityTransformer" /** * Getter for property IdentityTransformer.<p> * IdentityTransformer transforms a Subject to a token that asserts identity. */ public static com.tangosol.net.security.IdentityTransformer getIdentityTransformer() { return __s_IdentityTransformer; } // Accessor for the property "Instance" /** * Getter for property Instance.<p> * The Security instance. */ public static Security getInstance() { if (!isConfigured()) { SecurityHelper.doPrivileged(new Security.ConfigAction()); } return __s_Instance; } /** * Security debugging helper. Not used for anything else! */ public javax.security.auth.Subject impersonate(javax.security.auth.Subject subject, String sNameOld, String sNameNew) { return null; } // Accessor for the property "Configured" /** * Getter for property Configured.<p> * Is security already configured? * * @volatile - else if getInstance were called concurrently when not yet * configured, one thread could see configured as true but not see the * corresponding Security instance. This can then result in the * PermissionInfo not getting inserted into the ServiceContext. Bug 27376204 */ protected static boolean isConfigured() { return __s_Configured; } // Accessor for the property "SecurityEnabled" /** * Getter for property SecurityEnabled.<p> * Indicates if security is enabled by the configuration. */ public static boolean isSecurityEnabled() { return Security.getInstance() != null || getAuthorizer() != null; } // Accessor for the property "SubjectScoped" /** * Getter for property SubjectScoped.<p> * Indicates if the security configuration specifies subject scoping. */ public static boolean isSubjectScoped() { return __s_SubjectScoped; } /** * @param oHandler a CallbackHandler object * * @see com.tangosol.net.security.Security */ public static javax.security.auth.Subject login(javax.security.auth.callback.CallbackHandler handler) { Security security = getInstance(); return security == null ? null : security.loginSecure(handler, null); } /** * Subclassing support. */ protected javax.security.auth.Subject loginSecure(javax.security.auth.callback.CallbackHandler handler, javax.security.auth.Subject subject) { return null; } /** * Process the Dependencies for the component. */ protected static void processDependencies(com.tangosol.internal.net.security.SecurityDependencies deps) { // import com.tangosol.net.security.DefaultIdentityAsserter; // import com.tangosol.net.security.DefaultIdentityTransformer; // import com.tangosol.net.security.IdentityAsserter; // import com.tangosol.net.security.IdentityTransformer; // if asserter and transformer are not configured then use defaults IdentityAsserter asserter = deps.getIdentityAsserter(); setIdentityAsserter(asserter == null ? DefaultIdentityAsserter.INSTANCE : asserter); IdentityTransformer transformer = deps.getIdentityTransformer(); setIdentityTransformer(transformer == null ? DefaultIdentityTransformer.INSTANCE : transformer); setAuthorizer(deps.getAuthorizer()); setSubjectScoped(deps.isSubjectScoped()); } /** * Callback API used to validate and respond to a security related request. * Called on a corresponding service thread of the service senior node. * * @param memberThis the member validating the secure request * @param memberFrom the member requesting validation * @param oRequestInfo the information to validate */ public Object processSecureRequest(Member memberThis, Member memberFrom, com.tangosol.net.security.PermissionInfo piRequest) { return null; } /** * Security API used by the Service components. Called on a service thread * upon the service termination. * * @param sServiceName the relevant Service name */ public void releaseSecureContext(String sServiceName) { } // From interface: java.security.PrivilegedAction public Object run() { return null; } /** * Helper method. */ protected static Object runAnonymously(Object oAction) throws java.security.PrivilegedActionException { // import java.security.PrivilegedAction; // import java.security.PrivilegedActionException; // import java.security.PrivilegedExceptionAction; if (oAction instanceof PrivilegedAction) { return ((PrivilegedAction) oAction).run(); } else { try { return ((PrivilegedExceptionAction) oAction).run(); } catch (Exception e) { throw new PrivilegedActionException(e); } } } /** * @param oSubject a Subject object (optional) * @param oAction a PrivilegedAction or PrivilegedExceptionAction object * * @see com.tangosol.net.security.Security */ public static Object runAs(javax.security.auth.Subject subject, Object oAction) throws java.security.PrivilegedActionException { Security security = getInstance(); return security == null ? runAnonymously(oAction) : security.runSecure(subject, oAction); } /** * Subclassing support. */ protected Object runSecure(javax.security.auth.Subject subject, Object oAction) throws java.security.PrivilegedActionException { return null; } // Accessor for the property "Authorizer" /** * Setter for property Authorizer.<p> * Authorizer represents an environment-specific facility for authorizing * callers to perform actions described by the corresponding permission * objects. */ protected static void setAuthorizer(com.tangosol.net.security.Authorizer authorizer) { __s_Authorizer = authorizer; } // Accessor for the property "Configured" /** * Setter for property Configured.<p> * Is security already configured? * * @volatile - else if getInstance were called concurrently when not yet * configured, one thread could see configured as true but not see the * corresponding Security instance. This can then result in the * PermissionInfo not getting inserted into the ServiceContext. Bug 27376204 */ protected static void setConfigured(boolean fConfig) { __s_Configured = fConfig; } // Accessor for the property "IdentityAsserter" /** * Setter for property IdentityAsserter.<p> * IdentityAsserter validates a token in order to establish a user's * identity. */ protected static void setIdentityAsserter(com.tangosol.net.security.IdentityAsserter asserter) { __s_IdentityAsserter = asserter; } // Accessor for the property "IdentityTransformer" /** * Setter for property IdentityTransformer.<p> * IdentityTransformer transforms a Subject to a token that asserts identity. */ protected static void setIdentityTransformer(com.tangosol.net.security.IdentityTransformer transformer) { __s_IdentityTransformer = transformer; } // Accessor for the property "Instance" /** * Setter for property Instance.<p> * The Security instance. */ protected static void setInstance(Security security) { __s_Instance = security; } // Accessor for the property "SubjectScoped" /** * Setter for property SubjectScoped.<p> * Indicates if the security configuration specifies subject scoping. */ protected static void setSubjectScoped(boolean fSubjectScoped) { __s_SubjectScoped = fSubjectScoped; } /** * Callback API used to verify that the joining service member has passed * the authentication step. Called on a corresponding service thread on the * joining node. * * @param service the Service * @param info the security request info */ public void verifySecureResponse(com.tangosol.net.Service service, com.tangosol.net.security.PermissionInfo info) { } // ---- class: com.tangosol.coherence.component.net.Security$CheckPermissionAction /** * Privileged action to check permission. */ @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class CheckPermissionAction extends com.tangosol.coherence.component.Util implements java.security.PrivilegedAction { // ---- Fields declarations ---- /** * Property Cluster * */ private com.tangosol.net.Cluster __m_Cluster; /** * Property Permission * */ private com.tangosol.net.ClusterPermission __m_Permission; /** * Property Security * */ private Security __m_Security; /** * Property Subject * */ private javax.security.auth.Subject __m_Subject; // Default constructor public CheckPermissionAction() { this(null, null, true); } // Initializing constructor public CheckPermissionAction(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.net.Security.CheckPermissionAction(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object * for a given component. */ public static Class get_CLASS() { Class clz; try { clz = Class.forName("com.tangosol.coherence/component/net/Security$CheckPermissionAction".replace('/', '.')); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.getMessage()); } return clz; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation for * this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent(); } // Accessor for the property "Cluster" /** * Getter for property Cluster.<p> */ public com.tangosol.net.Cluster getCluster() { return __m_Cluster; } // Accessor for the property "Permission" /** * Getter for property Permission.<p> */ public com.tangosol.net.ClusterPermission getPermission() { return __m_Permission; } // Accessor for the property "Security" /** * Getter for property Security.<p> */ public Security getSecurity() { return __m_Security; } // Accessor for the property "Subject" /** * Getter for property Subject.<p> */ public javax.security.auth.Subject getSubject() { return __m_Subject; } // From interface: java.security.PrivilegedAction public Object run() { getSecurity().checkPermission(getCluster(), getPermission(), getSubject()); return null; } // Accessor for the property "Cluster" /** * Setter for property Cluster.<p> */ public void setCluster(com.tangosol.net.Cluster cluster) { __m_Cluster = cluster; } // Accessor for the property "Permission" /** * Setter for property Permission.<p> */ public void setPermission(com.tangosol.net.ClusterPermission permission) { __m_Permission = permission; } // Accessor for the property "Security" /** * Setter for property Security.<p> */ public void setSecurity(Security security) { __m_Security = security; } // Accessor for the property "Subject" /** * Setter for property Subject.<p> */ public void setSubject(javax.security.auth.Subject subject) { __m_Subject = subject; } } // ---- class: com.tangosol.coherence.component.net.Security$ConfigAction /** * Privileged action to configure security. */ @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class ConfigAction extends com.tangosol.coherence.component.Util implements java.security.PrivilegedAction { // ---- Fields declarations ---- // Default constructor public ConfigAction() { this(null, null, true); } // Initializing constructor public ConfigAction(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.net.Security.ConfigAction(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object * for a given component. */ public static Class get_CLASS() { Class clz; try { clz = Class.forName("com.tangosol.coherence/component/net/Security$ConfigAction".replace('/', '.')); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.getMessage()); } return clz; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation for * this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent(); } // From interface: java.security.PrivilegedAction public Object run() { try { ((Security) get_Module()).configureSecurity(); } catch (RuntimeException e) { _trace("Failed to configure the Security module", 1); _trace(e); } return null; } } // ---- class: com.tangosol.coherence.component.net.Security$RefAction /** * Reflection based PrivilegedAction */ @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class RefAction extends com.tangosol.coherence.component.Util implements java.security.PrivilegedAction { // ---- Fields declarations ---- /** * Property Arguments * */ private transient Object[] __m_Arguments; /** * Property Method * */ private transient java.lang.reflect.Method __m_Method; /** * Property Target * */ private transient Object __m_Target; // Default constructor public RefAction() { this(null, null, true); } // Initializing constructor public RefAction(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.net.Security.RefAction(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object * for a given component. */ public static Class get_CLASS() { Class clz; try { clz = Class.forName("com.tangosol.coherence/component/net/Security$RefAction".replace('/', '.')); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.getMessage()); } return clz; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation for * this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent(); } // Accessor for the property "Arguments" /** * Getter for property Arguments.<p> */ public Object[] getArguments() { return __m_Arguments; } // Accessor for the property "Method" /** * Getter for property Method.<p> */ public java.lang.reflect.Method getMethod() { return __m_Method; } // Accessor for the property "Target" /** * Getter for property Target.<p> */ public Object getTarget() { return __m_Target; } // From interface: java.security.PrivilegedAction public Object run() { // import com.tangosol.util.Base; try { return getMethod().invoke(getTarget(), getArguments()); } catch (Exception e) { throw Base.ensureRuntimeException(e, toString()); } } // Accessor for the property "Arguments" /** * Setter for property Arguments.<p> */ public void setArguments(Object[] method) { __m_Arguments = method; } // Accessor for the property "Method" /** * Setter for property Method.<p> */ public void setMethod(java.lang.reflect.Method method) { __m_Method = method; } // Accessor for the property "Target" /** * Setter for property Target.<p> */ public void setTarget(Object method) { __m_Target = method; } // Declared at the super level public String toString() { // import Component.Application.Console.Coherence; return "RefAction{Method=" + getMethod().getName() + ", Target=" + getTarget() + ", Args=" + Coherence.toString(getArguments()) + '}'; } } }
apache/streampark
37,161
streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationManageServiceImpl.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.streampark.console.core.service.application.impl; import org.apache.streampark.common.conf.Workspace; import org.apache.streampark.common.enums.ClusterState; import org.apache.streampark.common.enums.FlinkDeployMode; import org.apache.streampark.common.enums.FlinkJobType; import org.apache.streampark.common.enums.StorageType; import org.apache.streampark.common.fs.HdfsOperator; import org.apache.streampark.common.util.DeflaterUtils; import org.apache.streampark.console.base.domain.RestRequest; import org.apache.streampark.console.base.exception.ApiAlertException; import org.apache.streampark.console.base.mybatis.pager.MybatisPager; import org.apache.streampark.console.base.util.ObjectUtils; import org.apache.streampark.console.base.util.WebUtils; import org.apache.streampark.console.core.bean.AppControl; import org.apache.streampark.console.core.entity.FlinkApplication; import org.apache.streampark.console.core.entity.FlinkApplicationConfig; import org.apache.streampark.console.core.entity.FlinkCluster; import org.apache.streampark.console.core.entity.FlinkSql; import org.apache.streampark.console.core.entity.Resource; import org.apache.streampark.console.core.enums.CandidateTypeEnum; import org.apache.streampark.console.core.enums.ChangeTypeEnum; import org.apache.streampark.console.core.enums.FlinkAppStateEnum; import org.apache.streampark.console.core.enums.OptionStateEnum; import org.apache.streampark.console.core.enums.ReleaseStateEnum; import org.apache.streampark.console.core.mapper.FlinkApplicationMapper; import org.apache.streampark.console.core.service.FlinkClusterService; import org.apache.streampark.console.core.service.FlinkEffectiveService; import org.apache.streampark.console.core.service.FlinkSqlService; import org.apache.streampark.console.core.service.ProjectService; import org.apache.streampark.console.core.service.ResourceService; import org.apache.streampark.console.core.service.SavepointService; import org.apache.streampark.console.core.service.SettingService; import org.apache.streampark.console.core.service.YarnQueueService; import org.apache.streampark.console.core.service.application.ApplicationLogService; import org.apache.streampark.console.core.service.application.FlinkApplicationBackupService; import org.apache.streampark.console.core.service.application.FlinkApplicationBuildPipelineService; import org.apache.streampark.console.core.service.application.FlinkApplicationConfigService; import org.apache.streampark.console.core.service.application.FlinkApplicationManageService; import org.apache.streampark.console.core.util.ServiceHelper; import org.apache.streampark.console.core.watcher.FlinkAppHttpWatcher; import org.apache.streampark.console.core.watcher.FlinkClusterWatcher; import org.apache.streampark.console.core.watcher.FlinkK8sWatcherWrapper; import org.apache.streampark.flink.kubernetes.FlinkK8sWatcher; import org.apache.streampark.flink.packer.pipeline.PipelineStatusEnum; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.annotations.VisibleForTesting; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import static org.apache.streampark.console.base.exception.ApiAlertException.validateCondition; @Slf4j @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class FlinkApplicationManageServiceImpl extends ServiceImpl<FlinkApplicationMapper, FlinkApplication> implements FlinkApplicationManageService { private static final String ERROR_APP_QUEUE_HINT = "Queue label '%s' isn't available for teamId '%d', please add it into the team first."; @Autowired private ProjectService projectService; @Autowired private FlinkApplicationBackupService backUpService; @Autowired private FlinkApplicationConfigService configService; @Autowired private ApplicationLogService applicationLogService; @Autowired private FlinkSqlService flinkSqlService; @Autowired private SavepointService savepointService; @Autowired private FlinkEffectiveService effectiveService; @Autowired private SettingService settingService; @Autowired private FlinkK8sWatcher k8SFlinkTrackMonitor; @Autowired private FlinkApplicationBuildPipelineService appBuildPipeService; @Autowired private YarnQueueService yarnQueueService; @Autowired private ResourceService resourceService; @Autowired private FlinkClusterWatcher flinkClusterWatcher; @Autowired private FlinkClusterService flinkClusterService; @Autowired private FlinkK8sWatcherWrapper k8sWatcherWrapper; @PostConstruct public void resetOptionState() { this.lambdaUpdate().set(FlinkApplication::getOptionState, OptionStateEnum.NONE.getValue()).update(); } @Override public void toEffective(FlinkApplication appParam) { // set latest to Effective FlinkApplicationConfig config = configService.getLatest(appParam.getId()); if (config != null) { this.configService.toEffective(appParam.getId(), config.getId()); } if (appParam.isFlinkSql()) { FlinkSql flinkSql = flinkSqlService.getCandidate(appParam.getId(), null); if (flinkSql != null) { flinkSqlService.toEffective(appParam.getId(), flinkSql.getId()); // clean candidate flinkSqlService.cleanCandidate(flinkSql.getId()); } } } @Override public void persistMetrics(FlinkApplication appParam) { this.baseMapper.persistMetrics(appParam); } @Override public boolean mapping(FlinkApplication appParam) { boolean result = this.lambdaUpdate() .eq(FlinkApplication::getId, appParam.getId()) .set(appParam.getClusterId() != null, FlinkApplication::getClusterId, appParam.getClusterId()) .set(appParam.getJobId() != null, FlinkApplication::getJobId, appParam.getJobId()) .set(FlinkApplication::getEndTime, null) .set(FlinkApplication::getState, FlinkAppStateEnum.MAPPING.getValue()) .set(FlinkApplication::getTracking, 1) .update(); FlinkApplication application = getById(appParam.getId()); if (application.isKubernetesModeJob()) { // todo mark k8SFlinkTrackMonitor.doWatching(k8sWatcherWrapper.toTrackId(application)); } else { FlinkAppHttpWatcher.doWatching(application); } return result; } @Override public Boolean remove(Long appId) { FlinkApplication application = getById(appId); // 1) remove flink sql flinkSqlService.removeByAppId(application.getId()); // 2) remove log applicationLogService.removeByAppId(application.getId()); // 3) remove config configService.removeByAppId(application.getId()); // 4) remove effective effectiveService.removeByAppId(application.getId()); // remove related hdfs // 5) remove backup backUpService.remove(application); // 6) remove savepoint savepointService.remove(application); // 7) remove BuildPipeline appBuildPipeService.removeByAppId(application.getId()); // 8) remove app removeApp(application); if (application.isKubernetesModeJob()) { k8SFlinkTrackMonitor.unWatching(k8sWatcherWrapper.toTrackId(application)); } else { FlinkAppHttpWatcher.unWatching(appId); } return true; } private void removeApp(FlinkApplication application) { Long appId = application.getId(); removeById(appId); try { application .getFsOperator() .delete(application.getWorkspace().APP_WORKSPACE().concat("/").concat(appId.toString())); // try to delete yarn-application, and leave no trouble. String path = Workspace.of(StorageType.HDFS).APP_WORKSPACE().concat("/").concat(appId.toString()); if (HdfsOperator.exists(path)) { HdfsOperator.delete(path); } } catch (Exception e) { // skip } } @Override public IPage<FlinkApplication> page(FlinkApplication appParam, RestRequest request) { if (appParam.getTeamId() == null) { return null; } Page<FlinkApplication> page = MybatisPager.getPage(request); if (ArrayUtils.isNotEmpty(appParam.getStateArray()) && Arrays.stream(appParam.getStateArray()) .anyMatch(x -> x == FlinkAppStateEnum.FINISHED.getValue())) { Integer[] newArray = ArrayUtils.insert( appParam.getStateArray().length, appParam.getStateArray(), FlinkAppStateEnum.POS_TERMINATED.getValue()); appParam.setStateArray(newArray); } this.baseMapper.selectPage(page, appParam); List<FlinkApplication> records = page.getRecords(); long now = System.currentTimeMillis(); List<Long> appIds = records.stream().map(FlinkApplication::getId).collect(Collectors.toList()); Map<Long, PipelineStatusEnum> pipeStates = appBuildPipeService.listAppIdPipelineStatusMap(appIds); List<FlinkApplication> newRecords = records.stream() .peek( record -> { // status of flink job on kubernetes mode had been automatically persisted // to db // in time. if (record.isKubernetesModeJob()) { // set duration String restUrl = k8SFlinkTrackMonitor .getRemoteRestUrl(k8sWatcherWrapper.toTrackId(record)); record.setFlinkRestUrl(restUrl); setAppDurationIfNeeded(record, now); } if (pipeStates.containsKey(record.getId())) { record.setBuildStatus(pipeStates.get(record.getId()).getCode()); } AppControl appControl = getAppControl(record); record.setAppControl(appControl); }) .collect(Collectors.toList()); page.setRecords(newRecords); return page; } private void setAppDurationIfNeeded(FlinkApplication record, long now) { if (record.getTracking() == 1 && record.getStartTime() != null && record.getStartTime().getTime() > 0) { record.setDuration(now - record.getStartTime().getTime()); } } private AppControl getAppControl(FlinkApplication record) { return new AppControl() .setAllowBuild( record.getBuildStatus() == null || !PipelineStatusEnum.running.getCode() .equals(record.getBuildStatus())) .setAllowStart( !record.shouldTracking() && PipelineStatusEnum.success.getCode() .equals(record.getBuildStatus())) .setAllowStop(record.isRunning()) .setAllowView(record.shouldTracking()); } @Override public void changeOwnership(Long userId, Long targetUserId) { this.lambdaUpdate().eq(FlinkApplication::getUserId, userId) .set(FlinkApplication::getUserId, targetUserId).update(); } @SneakyThrows @Override public boolean create(FlinkApplication appParam) { ApiAlertException.throwIfNull( appParam.getTeamId(), "The teamId can't be null. Create application failed."); appParam.setUserId(ServiceHelper.getUserId()); appParam.setState(FlinkAppStateEnum.ADDED.getValue()); appParam.setRelease(ReleaseStateEnum.NEED_RELEASE.get()); appParam.setOptionState(OptionStateEnum.NONE.getValue()); Date date = new Date(); appParam.setCreateTime(date); appParam.setModifyTime(date); appParam.setDefaultModeIngress(settingService.getIngressModeDefault()); String jobName = appParam.getJobName(); // validate job application validateCondition(!jobName.contains(" "), "The added job name `%s` is an invalid character and cannot contain Spaces", jobName); validateCondition(validateQueueIfNeeded(appParam), ERROR_APP_QUEUE_HINT, appParam.getYarnQueue(), appParam.getTeamId()); appParam.doSetHotParams(); if (appParam.isUploadResource()) { String jarPath = String.format( "%s/%d/%s", Workspace.local().APP_UPLOADS(), appParam.getTeamId(), appParam.getJar()); if (!new File(jarPath).exists()) { Resource resource = resourceService.findByResourceName(appParam.getTeamId(), appParam.getJar()); if (resource != null && StringUtils.isNotBlank(resource.getFilePath())) { jarPath = resource.getFilePath(); } } appParam.setJarCheckSum(org.apache.commons.io.FileUtils.checksumCRC32(new File(jarPath))); } boolean saveSuccess = save(appParam); if (saveSuccess) { FlinkJobType jobType = appParam.getJobTypeEnum(); if (jobType == FlinkJobType.FLINK_SQL || jobType == FlinkJobType.PYFLINK) { FlinkSql flinkSql = new FlinkSql(appParam); flinkSqlService.create(flinkSql); } if (appParam.getConfig() != null) { configService.create(appParam, true); } return true; } else { throw new ApiAlertException("create application failed"); } } private boolean existsByJobName(String jobName) { return this.lambdaQuery().eq(FlinkApplication::getJobName, jobName).exists(); } @SuppressWarnings("checkstyle:WhitespaceAround") @Override @SneakyThrows public Long copy(FlinkApplication appParam) { boolean existsByJobName = this.existsByJobName(appParam.getJobName()); ApiAlertException.throwIfFalse( !existsByJobName, "[StreamPark] Application names can't be repeated, copy application failed."); FlinkApplication persist = getById(appParam.getId()); FlinkApplication newApp = new FlinkApplication(); String jobName = appParam.getJobName(); newApp.setJobName(jobName); newApp.setClusterId( FlinkDeployMode.isSessionMode(persist.getDeployModeEnum()) ? persist.getClusterId() : null); newApp.setArgs(appParam.getArgs() != null ? appParam.getArgs() : persist.getArgs()); newApp.setVersionId(persist.getVersionId()); newApp.setFlinkClusterId(persist.getFlinkClusterId()); newApp.setRestartSize(persist.getRestartSize()); newApp.setJobType(persist.getJobType()); newApp.setOptions(persist.getOptions()); newApp.setDynamicProperties(persist.getDynamicProperties()); newApp.setResolveOrder(persist.getResolveOrder()); newApp.setDeployMode(persist.getDeployMode()); newApp.setFlinkImage(persist.getFlinkImage()); newApp.setK8sNamespace(persist.getK8sNamespace()); newApp.setK8sRestExposedType(persist.getK8sRestExposedType()); newApp.setK8sPodTemplate(persist.getK8sPodTemplate()); newApp.setK8sJmPodTemplate(persist.getK8sJmPodTemplate()); newApp.setK8sTmPodTemplate(persist.getK8sTmPodTemplate()); newApp.setK8sHadoopIntegration(persist.getK8sHadoopIntegration()); newApp.setDescription(persist.getDescription()); newApp.setAlertId(persist.getAlertId()); newApp.setCpFailureAction(persist.getCpFailureAction()); newApp.setCpFailureRateInterval(persist.getCpFailureRateInterval()); newApp.setCpMaxFailureInterval(persist.getCpMaxFailureInterval()); newApp.setMainClass(persist.getMainClass()); newApp.setAppType(persist.getAppType()); newApp.setResourceFrom(persist.getResourceFrom()); newApp.setProjectId(persist.getProjectId()); newApp.setModule(persist.getModule()); newApp.setUserId(ServiceHelper.getUserId()); newApp.setState(FlinkAppStateEnum.ADDED.getValue()); newApp.setRelease(ReleaseStateEnum.NEED_RELEASE.get()); newApp.setOptionState(OptionStateEnum.NONE.getValue()); newApp.setHotParams(persist.getHotParams()); // createTime & modifyTime Date date = new Date(); newApp.setCreateTime(date); newApp.setModifyTime(date); newApp.setJar(persist.getJar()); newApp.setJarCheckSum(persist.getJarCheckSum()); newApp.setTags(persist.getTags()); newApp.setTeamId(persist.getTeamId()); newApp.setDependency(persist.getDependency()); boolean saved = save(newApp); if (saved) { if (newApp.isFlinkSql()) { FlinkSql copyFlinkSql = flinkSqlService.getLatestFlinkSql(appParam.getId(), true); newApp.setFlinkSql(copyFlinkSql.getSql()); newApp.setDependency(copyFlinkSql.getDependency()); FlinkSql flinkSql = new FlinkSql(newApp); flinkSqlService.create(flinkSql); } FlinkApplicationConfig copyConfig = configService.getEffective(appParam.getId()); if (copyConfig != null) { FlinkApplicationConfig config = new FlinkApplicationConfig(); config.setAppId(newApp.getId()); config.setFormat(copyConfig.getFormat()); config.setContent(copyConfig.getContent()); config.setCreateTime(new Date()); config.setVersion(1); configService.save(config); configService.setLatestOrEffective(true, config.getId(), newApp.getId()); } return newApp.getId(); } else { throw new ApiAlertException( "create application from copy failed, copy source app: " + persist.getJobName()); } } @Override public boolean update(FlinkApplication appParam) { FlinkApplication application = getById(appParam.getId()); /* If the original mode is remote, k8s-session, yarn-session, check cluster status */ FlinkDeployMode flinkDeployMode = application.getDeployModeEnum(); switch (flinkDeployMode) { case REMOTE: case YARN_SESSION: case KUBERNETES_NATIVE_SESSION: FlinkCluster flinkCluster = flinkClusterService.getById(application.getFlinkClusterId()); ApiAlertException.throwIfFalse( flinkClusterWatcher.getClusterState(flinkCluster) == ClusterState.RUNNING, "[StreamPark] update failed, because bind flink cluster not running"); break; default: } boolean success = validateQueueIfNeeded(application, appParam); ApiAlertException.throwIfFalse( success, String.format(ERROR_APP_QUEUE_HINT, appParam.getYarnQueue(), appParam.getTeamId())); application.setRelease(ReleaseStateEnum.NEED_RELEASE.get()); // 1) jar job jar file changed if (application.isUploadResource()) { if (!Objects.equals(application.getJar(), appParam.getJar())) { application.setBuild(true); } else { File jarFile = new File(WebUtils.getAppTempDir(), appParam.getJar()); if (jarFile.exists()) { try { long checkSum = org.apache.commons.io.FileUtils.checksumCRC32(jarFile); if (!Objects.equals(checkSum, application.getJarCheckSum())) { application.setBuild(true); application.setJarCheckSum(checkSum); } } catch (IOException e) { log.error("Error in checksumCRC32 for {}.", jarFile); throw new RuntimeException(e); } } } } // 2) k8s podTemplate changed. if (application.getBuild() && isK8sPodTemplateChanged(application, appParam)) { application.setBuild(true); } // 3) flink version changed if (!application.getBuild() && !Objects.equals(application.getVersionId(), appParam.getVersionId())) { application.setBuild(true); } // 4) yarn application mode change if (!application.getBuild() && isYarnApplicationModeChange(application, appParam)) { application.setBuild(true); } appParam.setJobType(application.getJobType()); // changes to the following parameters need to be re-release to take effect application.setJobName(appParam.getJobName()); application.setVersionId(appParam.getVersionId()); application.setArgs(appParam.getArgs()); application.setOptions(appParam.getOptions()); application.setDynamicProperties(appParam.getDynamicProperties()); application.setResolveOrder(appParam.getResolveOrder()); application.setDeployMode(appParam.getDeployMode()); application.setFlinkImage(appParam.getFlinkImage()); application.setK8sNamespace(appParam.getK8sNamespace()); application.updateHotParams(appParam); application.setK8sRestExposedType(appParam.getK8sRestExposedType()); application.setK8sPodTemplate(appParam.getK8sPodTemplate()); application.setK8sJmPodTemplate(appParam.getK8sJmPodTemplate()); application.setK8sTmPodTemplate(appParam.getK8sTmPodTemplate()); application.setK8sHadoopIntegration(appParam.getK8sHadoopIntegration()); // changes to the following parameters do not affect running tasks application.setModifyTime(new Date()); application.setDescription(appParam.getDescription()); application.setAlertId(appParam.getAlertId()); application.setRestartSize(appParam.getRestartSize()); application.setCpFailureAction(appParam.getCpFailureAction()); application.setCpFailureRateInterval(appParam.getCpFailureRateInterval()); application.setCpMaxFailureInterval(appParam.getCpMaxFailureInterval()); application.setTags(appParam.getTags()); switch (appParam.getDeployModeEnum()) { case YARN_APPLICATION: application.setHadoopUser(appParam.getHadoopUser()); break; case YARN_PER_JOB: application.setHadoopUser(appParam.getHadoopUser()); break; case KUBERNETES_NATIVE_APPLICATION: application.setFlinkClusterId(null); break; case REMOTE: case YARN_SESSION: case KUBERNETES_NATIVE_SESSION: application.setFlinkClusterId(appParam.getFlinkClusterId()); break; default: break; } // Flink Sql job... if (application.isFlinkSql()) { updateFlinkSqlJob(application, appParam); return true; } if (application.isStreamParkType()) { configService.update(appParam, application.isRunning()); } else { application.setJar(appParam.getJar()); application.setMainClass(appParam.getMainClass()); } this.updateById(application); return true; } /** * update FlinkSql type jobs, there are 3 aspects to consider<br> * 1. flink sql has changed <br> * 2. dependency has changed<br> * 3. parameter has changed<br> * * @param application * @param appParam */ private void updateFlinkSqlJob(FlinkApplication application, FlinkApplication appParam) { FlinkSql effectiveFlinkSql = flinkSqlService.getEffective(application.getId(), true); if (effectiveFlinkSql == null) { effectiveFlinkSql = flinkSqlService.getCandidate(application.getId(), CandidateTypeEnum.NEW); flinkSqlService.removeById(effectiveFlinkSql.getId()); FlinkSql sql = new FlinkSql(appParam); flinkSqlService.create(sql); application.setBuild(true); } else { // get previous flink sql and decode FlinkSql copySourceFlinkSql = flinkSqlService.getById(appParam.getSqlId()); ApiAlertException.throwIfNull( copySourceFlinkSql, "Flink sql is null, update flink sql job failed."); copySourceFlinkSql.decode(); // get submit flink sql FlinkSql targetFlinkSql = new FlinkSql(appParam); // judge sql and dependency has changed ChangeTypeEnum changeTypeEnum = copySourceFlinkSql.checkChange(targetFlinkSql); log.info("updateFlinkSqlJob changeTypeEnum: {}", changeTypeEnum); // if has been changed if (changeTypeEnum.hasChanged()) { // check if there is a candidate version for the newly added record FlinkSql newFlinkSql = flinkSqlService.getCandidate(application.getId(), CandidateTypeEnum.NEW); // If the candidate version of the new record exists, it will be deleted directly, // and only one candidate version will be retained. If the new candidate version is not // effective, // if it is edited again and the next record comes in, the previous candidate version will // be deleted. if (newFlinkSql != null) { // delete all records about candidates flinkSqlService.removeById(newFlinkSql.getId()); } FlinkSql historyFlinkSql = flinkSqlService.getCandidate(application.getId(), CandidateTypeEnum.HISTORY); // remove candidate flags that already exist but are set as candidates if (historyFlinkSql != null) { flinkSqlService.cleanCandidate(historyFlinkSql.getId()); } FlinkSql sql = new FlinkSql(appParam); flinkSqlService.create(sql); if (changeTypeEnum.isDependencyChanged()) { application.setBuild(true); } } else { // judge version has changed boolean versionChanged = !effectiveFlinkSql.getId().equals(appParam.getSqlId()); if (versionChanged) { // sql and dependency not changed, but version changed, means that rollback to the version CandidateTypeEnum type = CandidateTypeEnum.HISTORY; flinkSqlService.setCandidate(type, appParam.getId(), appParam.getSqlId()); application.setRelease(ReleaseStateEnum.NEED_ROLLBACK.get()); application.setBuild(true); } } } this.updateById(application); this.configService.update(appParam, application.isRunning()); } @Override public void updateRelease(FlinkApplication appParam) { this.lambdaUpdate() .eq(FlinkApplication::getId, appParam.getId()) .set(FlinkApplication::getRelease, appParam.getRelease()) .set(FlinkApplication::getBuild, appParam.getBuild()) .set(appParam.getOptionState() != null, FlinkApplication::getOptionState, appParam.getOptionState()) .update(); } @Override public List<FlinkApplication> listByProjectId(Long id) { return this.lambdaQuery().eq(FlinkApplication::getProjectId, id).list(); } @Override public List<FlinkApplication> listByTeamId(Long teamId) { return baseMapper.selectAppsByTeamId(teamId); } @Override public List<FlinkApplication> listByTeamIdAndDeployModes( Long teamId, @Nonnull Collection<FlinkDeployMode> deployModeEnums) { return this.lambdaQuery() .eq((SFunction<FlinkApplication, Long>) FlinkApplication::getTeamId, teamId) .in( FlinkApplication::getDeployMode, deployModeEnums.stream() .map(FlinkDeployMode::getMode) .collect(Collectors.toSet())) .list(); } @Override public boolean checkBuildAndUpdate(FlinkApplication appParam) { boolean build = appParam.getBuild(); if (!build) { LambdaUpdateChainWrapper<FlinkApplication> update = this.lambdaUpdate() .eq(FlinkApplication::getId, appParam.getId()); if (appParam.isRunning()) { update.set(FlinkApplication::getRelease, ReleaseStateEnum.NEED_RESTART.get()); } else { update .set(FlinkApplication::getRelease, ReleaseStateEnum.DONE.get()) .set(FlinkApplication::getOptionState, OptionStateEnum.NONE.getValue()); } update.update(); // backup if (appParam.isFlinkSql()) { FlinkSql newFlinkSql = flinkSqlService.getCandidate(appParam.getId(), CandidateTypeEnum.NEW); if (!appParam.isNeedRollback() && newFlinkSql != null) { backUpService.backup(appParam, newFlinkSql); } } // If the current task is not running, or the task has just been added, // directly set the candidate version to the official version FlinkSql flinkSql = flinkSqlService.getEffective(appParam.getId(), false); if (!appParam.isRunning() || flinkSql == null) { this.toEffective(appParam); } } return build; } @Override public void clean(FlinkApplication appParam) { appParam.setRelease(ReleaseStateEnum.DONE.get()); this.updateRelease(appParam); } @Override public FlinkApplication getApp(Long id) { FlinkApplication application = this.baseMapper.selectApp(id); FlinkApplicationConfig config = configService.getEffective(id); config = config == null ? configService.getLatest(id) : config; if (config != null) { config.setToApplication(application); } if (application.isFlinkSql()) { FlinkSql flinkSql = flinkSqlService.getEffective(application.getId(), true); if (flinkSql == null) { flinkSql = flinkSqlService.getCandidate(application.getId(), CandidateTypeEnum.NEW); flinkSql.setSql(DeflaterUtils.unzipString(flinkSql.getSql())); } flinkSql.setToApplication(application); } else { if (application.isBuildResource()) { String path = this.projectService.getAppConfPath(application.getProjectId(), application.getModule()); application.setConfPath(path); } } // add flink web url info for k8s-mode if (application.isKubernetesModeJob()) { String restUrl = k8SFlinkTrackMonitor.getRemoteRestUrl(k8sWatcherWrapper.toTrackId(application)); application.setFlinkRestUrl(restUrl); // set duration long now = System.currentTimeMillis(); setAppDurationIfNeeded(application, now); } application.setYarnQueueByHotParams(); return application; } /** * Check queue label validation when create the application if needed. * * @param appParam the app to create. * @return <code>true</code> if validate it successfully, <code>false</code> else. */ @VisibleForTesting public boolean validateQueueIfNeeded(FlinkApplication appParam) { yarnQueueService.checkQueueLabel(appParam.getDeployModeEnum(), appParam.getYarnQueue()); if (!isYarnNotDefaultQueue(appParam)) { return true; } return yarnQueueService.existByTeamIdQueueLabel(appParam.getTeamId(), appParam.getYarnQueue()); } /** * Check queue label validation when update the application if needed. * * @param oldApp the old app to update. * @param newApp the new app payload. * @return <code>true</code> if validate it successfully, <code>false</code> else. */ @VisibleForTesting public boolean validateQueueIfNeeded(FlinkApplication oldApp, FlinkApplication newApp) { yarnQueueService.checkQueueLabel(newApp.getDeployModeEnum(), newApp.getYarnQueue()); if (!isYarnNotDefaultQueue(newApp)) { return true; } oldApp.setYarnQueueByHotParams(); if (FlinkDeployMode.isYarnPerJobOrAppMode(newApp.getDeployModeEnum()) && StringUtils.equals(oldApp.getYarnQueue(), newApp.getYarnQueue())) { return true; } return yarnQueueService.existByTeamIdQueueLabel(newApp.getTeamId(), newApp.getYarnQueue()); } /** * Judge the execution mode whether is the Yarn PerJob or Application mode with not default or * empty queue label. * * @param application application entity. * @return If the deployMode is (Yarn PerJob or application mode) and the queue label is not * (empty or default), return true, false else. */ private boolean isYarnNotDefaultQueue(FlinkApplication application) { return FlinkDeployMode.isYarnPerJobOrAppMode(application.getDeployModeEnum()) && !yarnQueueService.isDefaultQueue(application.getYarnQueue()); } private boolean isK8sPodTemplateChanged(FlinkApplication application, FlinkApplication appParam) { return FlinkDeployMode.isKubernetesMode(appParam.getDeployMode()) && (ObjectUtils.trimNoEquals( application.getK8sRestExposedType(), appParam.getK8sRestExposedType()) || ObjectUtils.trimNoEquals( application.getK8sJmPodTemplate(), appParam.getK8sJmPodTemplate()) || ObjectUtils.trimNoEquals( application.getK8sTmPodTemplate(), appParam.getK8sTmPodTemplate()) || ObjectUtils.trimNoEquals( application.getK8sPodTemplates(), appParam.getK8sPodTemplates()) || ObjectUtils.trimNoEquals( application.getK8sHadoopIntegration(), appParam.getK8sHadoopIntegration()) || ObjectUtils.trimNoEquals(application.getFlinkImage(), appParam.getFlinkImage())); } private boolean isYarnApplicationModeChange(FlinkApplication application, FlinkApplication appParam) { return !application.getDeployMode().equals(appParam.getDeployMode()) && (FlinkDeployMode.YARN_APPLICATION == appParam.getDeployModeEnum() || FlinkDeployMode.YARN_APPLICATION == application.getDeployModeEnum()); } }
googleapis/google-api-java-client-services
37,058
clients/google-api-services-walletobjects/v1/2.0.0/com/google/api/services/walletobjects/model/LoyaltyObject.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.walletobjects.model; /** * Model definition for LoyaltyObject. * * <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 Google Wallet 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 LoyaltyObject extends com.google.api.client.json.GenericJson { /** * The loyalty account identifier. Recommended maximum length is 20 characters. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountId; /** * The loyalty account holder name, such as "John Smith." Recommended maximum length is 20 * characters to ensure full string is displayed on smaller screens. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String accountName; /** * Optional app or website link that will be displayed as a button on the front of the pass. If * AppLinkData is provided for the corresponding class only object AppLinkData will be displayed. * The value may be {@code null}. */ @com.google.api.client.util.Key private AppLinkData appLinkData; /** * The barcode type and value. * The value may be {@code null}. */ @com.google.api.client.util.Key private Barcode barcode; /** * Required. The class associated with this object. The class must be of the same type as this * object, must already exist, and must be approved. Class IDs should follow the format issuer * ID.identifier where the former is issued by Google and latter is chosen by you. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String classId; /** * A copy of the inherited fields of the parent class. These fields are retrieved during a GET. * The value may be {@code null}. */ @com.google.api.client.util.Key private LoyaltyClass classReference; /** * Indicates if notifications should explicitly be suppressed. If this field is set to true, * regardless of the `messages` field, expiration notifications to the user will be suppressed. By * default, this field is set to false. Currently, this can only be set for offers. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean disableExpirationNotification; /** * Information that controls how passes are grouped together. * The value may be {@code null}. */ @com.google.api.client.util.Key private GroupingInfo groupingInfo; /** * Whether this object is currently linked to a single device. This field is set by the platform * when a user saves the object, linking it to their device. Intended for use by select partners. * Contact support for additional information. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean hasLinkedDevice; /** * Indicates if the object has users. This field is set by the platform. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean hasUsers; /** * Optional banner image displayed on the front of the card. If none is present, hero image of the * class, if present, will be displayed. If hero image of the class is also not present, nothing * will be displayed. * The value may be {@code null}. */ @com.google.api.client.util.Key private Image heroImage; /** * Required. The unique identifier for an object. This ID must be unique across all objects from * an issuer. This value should follow the format issuer ID.identifier where the former is issued * by Google and latter is chosen by you. The unique identifier should only include alphanumeric * characters, '.', '_', or '-'. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * Image module data. The maximum number of these fields displayed is 1 from object level and 1 * for class object level. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ImageModuleData> imageModulesData; static { // hack to force ProGuard to consider ImageModuleData 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(ImageModuleData.class); } /** * Deprecated. Use textModulesData instead. * The value may be {@code null}. */ @com.google.api.client.util.Key private InfoModuleData infoModuleData; /** * Identifies what kind of resource this is. Value: the fixed string * `"walletobjects#loyaltyObject"`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * linked_object_ids are a list of other objects such as event ticket, loyalty, offer, generic, * giftcard, transit and boarding pass that should be automatically attached to this loyalty * object. If a user had saved this loyalty card, then these linked_object_ids would be * automatically pushed to the user's wallet (unless they turned off the setting to receive such * linked passes). Make sure that objects present in linked_object_ids are already inserted - if * not, calls would fail. Once linked, the linked objects cannot be unlinked. You cannot link * objects belonging to another issuer. There is a limit to the number of objects that can be * linked to a single object. After the limit is reached, new linked objects in the call will be * ignored silently. Object IDs should follow the format issuer ID. identifier where the former is * issued by Google and the latter is chosen by you. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> linkedObjectIds; /** * A list of offer objects linked to this loyalty card. The offer objects must already exist. * Offer object IDs should follow the format issuer ID. identifier where the former is issued by * Google and latter is chosen by you. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> linkedOfferIds; /** * Links module data. If links module data is also defined on the class, both will be displayed. * The value may be {@code null}. */ @com.google.api.client.util.Key private LinksModuleData linksModuleData; /** * Note: This field is currently not supported to trigger geo notifications. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<LatLongPoint> locations; static { // hack to force ProGuard to consider LatLongPoint 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(LatLongPoint.class); } /** * The loyalty reward points label, balance, and type. * The value may be {@code null}. */ @com.google.api.client.util.Key private LoyaltyPoints loyaltyPoints; /** * Merchant locations. There is a maximum of ten on the object. Any additional MerchantLocations * added beyond the 10 will be rejected. These locations will trigger a notification when a user * enters within a Google-set radius of the point. This field replaces the deprecated * LatLongPoints. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<MerchantLocation> merchantLocations; /** * An array of messages displayed in the app. All users of this object will receive its associated * messages. The maximum number of these fields is 10. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Message> messages; /** * Whether or not field updates to this object should trigger notifications. When set to NOTIFY, * we will attempt to trigger a field update notification to users. These notifications will only * be sent to users if the field is part of an allowlist. If set to DO_NOT_NOTIFY or * NOTIFICATION_SETTINGS_UNSPECIFIED, no notification will be triggered. This setting is ephemeral * and needs to be set with each PATCH or UPDATE request, otherwise a notification will not be * triggered. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String notifyPreference; /** * Pass constraints for the object. Includes limiting NFC and screenshot behaviors. * The value may be {@code null}. */ @com.google.api.client.util.Key private PassConstraints passConstraints; /** * The rotating barcode type and value. * The value may be {@code null}. */ @com.google.api.client.util.Key private RotatingBarcode rotatingBarcode; /** * Restrictions on the object that needs to be verified before the user tries to save the pass. * Note that this restrictions will only be applied during save time. If the restrictions changed * after a user saves the pass, the new restrictions will not be applied to an already saved pass. * The value may be {@code null}. */ @com.google.api.client.util.Key private SaveRestrictions saveRestrictions; /** * The secondary loyalty reward points label, balance, and type. Shown in addition to the primary * loyalty points. * The value may be {@code null}. */ @com.google.api.client.util.Key private LoyaltyPoints secondaryLoyaltyPoints; /** * The value that will be transmitted to a Smart Tap certified terminal over NFC for this object. * The class level fields `enableSmartTap` and `redemptionIssuers` must also be set up correctly * in order for the pass to support Smart Tap. Only ASCII characters are supported. If this value * is not set but the class level fields `enableSmartTap` and `redemptionIssuers` are set up * correctly, the `barcode.value` or the `accountId` fields are used as fallback if present. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String smartTapRedemptionValue; /** * Required. The state of the object. This field is used to determine how an object is displayed * in the app. For example, an `inactive` object is moved to the "Expired passes" section. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String state; /** * Text module data. If text module data is also defined on the class, both will be displayed. The * maximum number of these fields displayed is 10 from the object and 10 from the class. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<TextModuleData> textModulesData; /** * The time period this object will be `active` and object can be used. An object's state will be * changed to `expired` when this time period has passed. * The value may be {@code null}. */ @com.google.api.client.util.Key private TimeInterval validTimeInterval; /** * Optional value added module data. Maximum of ten on the object. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ValueAddedModuleData> valueAddedModuleData; /** * Deprecated * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long version; /** * The loyalty account identifier. Recommended maximum length is 20 characters. * @return value or {@code null} for none */ public java.lang.String getAccountId() { return accountId; } /** * The loyalty account identifier. Recommended maximum length is 20 characters. * @param accountId accountId or {@code null} for none */ public LoyaltyObject setAccountId(java.lang.String accountId) { this.accountId = accountId; return this; } /** * The loyalty account holder name, such as "John Smith." Recommended maximum length is 20 * characters to ensure full string is displayed on smaller screens. * @return value or {@code null} for none */ public java.lang.String getAccountName() { return accountName; } /** * The loyalty account holder name, such as "John Smith." Recommended maximum length is 20 * characters to ensure full string is displayed on smaller screens. * @param accountName accountName or {@code null} for none */ public LoyaltyObject setAccountName(java.lang.String accountName) { this.accountName = accountName; return this; } /** * Optional app or website link that will be displayed as a button on the front of the pass. If * AppLinkData is provided for the corresponding class only object AppLinkData will be displayed. * @return value or {@code null} for none */ public AppLinkData getAppLinkData() { return appLinkData; } /** * Optional app or website link that will be displayed as a button on the front of the pass. If * AppLinkData is provided for the corresponding class only object AppLinkData will be displayed. * @param appLinkData appLinkData or {@code null} for none */ public LoyaltyObject setAppLinkData(AppLinkData appLinkData) { this.appLinkData = appLinkData; return this; } /** * The barcode type and value. * @return value or {@code null} for none */ public Barcode getBarcode() { return barcode; } /** * The barcode type and value. * @param barcode barcode or {@code null} for none */ public LoyaltyObject setBarcode(Barcode barcode) { this.barcode = barcode; return this; } /** * Required. The class associated with this object. The class must be of the same type as this * object, must already exist, and must be approved. Class IDs should follow the format issuer * ID.identifier where the former is issued by Google and latter is chosen by you. * @return value or {@code null} for none */ public java.lang.String getClassId() { return classId; } /** * Required. The class associated with this object. The class must be of the same type as this * object, must already exist, and must be approved. Class IDs should follow the format issuer * ID.identifier where the former is issued by Google and latter is chosen by you. * @param classId classId or {@code null} for none */ public LoyaltyObject setClassId(java.lang.String classId) { this.classId = classId; return this; } /** * A copy of the inherited fields of the parent class. These fields are retrieved during a GET. * @return value or {@code null} for none */ public LoyaltyClass getClassReference() { return classReference; } /** * A copy of the inherited fields of the parent class. These fields are retrieved during a GET. * @param classReference classReference or {@code null} for none */ public LoyaltyObject setClassReference(LoyaltyClass classReference) { this.classReference = classReference; return this; } /** * Indicates if notifications should explicitly be suppressed. If this field is set to true, * regardless of the `messages` field, expiration notifications to the user will be suppressed. By * default, this field is set to false. Currently, this can only be set for offers. * @return value or {@code null} for none */ public java.lang.Boolean getDisableExpirationNotification() { return disableExpirationNotification; } /** * Indicates if notifications should explicitly be suppressed. If this field is set to true, * regardless of the `messages` field, expiration notifications to the user will be suppressed. By * default, this field is set to false. Currently, this can only be set for offers. * @param disableExpirationNotification disableExpirationNotification or {@code null} for none */ public LoyaltyObject setDisableExpirationNotification(java.lang.Boolean disableExpirationNotification) { this.disableExpirationNotification = disableExpirationNotification; return this; } /** * Information that controls how passes are grouped together. * @return value or {@code null} for none */ public GroupingInfo getGroupingInfo() { return groupingInfo; } /** * Information that controls how passes are grouped together. * @param groupingInfo groupingInfo or {@code null} for none */ public LoyaltyObject setGroupingInfo(GroupingInfo groupingInfo) { this.groupingInfo = groupingInfo; return this; } /** * Whether this object is currently linked to a single device. This field is set by the platform * when a user saves the object, linking it to their device. Intended for use by select partners. * Contact support for additional information. * @return value or {@code null} for none */ public java.lang.Boolean getHasLinkedDevice() { return hasLinkedDevice; } /** * Whether this object is currently linked to a single device. This field is set by the platform * when a user saves the object, linking it to their device. Intended for use by select partners. * Contact support for additional information. * @param hasLinkedDevice hasLinkedDevice or {@code null} for none */ public LoyaltyObject setHasLinkedDevice(java.lang.Boolean hasLinkedDevice) { this.hasLinkedDevice = hasLinkedDevice; return this; } /** * Indicates if the object has users. This field is set by the platform. * @return value or {@code null} for none */ public java.lang.Boolean getHasUsers() { return hasUsers; } /** * Indicates if the object has users. This field is set by the platform. * @param hasUsers hasUsers or {@code null} for none */ public LoyaltyObject setHasUsers(java.lang.Boolean hasUsers) { this.hasUsers = hasUsers; return this; } /** * Optional banner image displayed on the front of the card. If none is present, hero image of the * class, if present, will be displayed. If hero image of the class is also not present, nothing * will be displayed. * @return value or {@code null} for none */ public Image getHeroImage() { return heroImage; } /** * Optional banner image displayed on the front of the card. If none is present, hero image of the * class, if present, will be displayed. If hero image of the class is also not present, nothing * will be displayed. * @param heroImage heroImage or {@code null} for none */ public LoyaltyObject setHeroImage(Image heroImage) { this.heroImage = heroImage; return this; } /** * Required. The unique identifier for an object. This ID must be unique across all objects from * an issuer. This value should follow the format issuer ID.identifier where the former is issued * by Google and latter is chosen by you. The unique identifier should only include alphanumeric * characters, '.', '_', or '-'. * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * Required. The unique identifier for an object. This ID must be unique across all objects from * an issuer. This value should follow the format issuer ID.identifier where the former is issued * by Google and latter is chosen by you. The unique identifier should only include alphanumeric * characters, '.', '_', or '-'. * @param id id or {@code null} for none */ public LoyaltyObject setId(java.lang.String id) { this.id = id; return this; } /** * Image module data. The maximum number of these fields displayed is 1 from object level and 1 * for class object level. * @return value or {@code null} for none */ public java.util.List<ImageModuleData> getImageModulesData() { return imageModulesData; } /** * Image module data. The maximum number of these fields displayed is 1 from object level and 1 * for class object level. * @param imageModulesData imageModulesData or {@code null} for none */ public LoyaltyObject setImageModulesData(java.util.List<ImageModuleData> imageModulesData) { this.imageModulesData = imageModulesData; return this; } /** * Deprecated. Use textModulesData instead. * @return value or {@code null} for none */ public InfoModuleData getInfoModuleData() { return infoModuleData; } /** * Deprecated. Use textModulesData instead. * @param infoModuleData infoModuleData or {@code null} for none */ public LoyaltyObject setInfoModuleData(InfoModuleData infoModuleData) { this.infoModuleData = infoModuleData; return this; } /** * Identifies what kind of resource this is. Value: the fixed string * `"walletobjects#loyaltyObject"`. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string * `"walletobjects#loyaltyObject"`. * @param kind kind or {@code null} for none */ public LoyaltyObject setKind(java.lang.String kind) { this.kind = kind; return this; } /** * linked_object_ids are a list of other objects such as event ticket, loyalty, offer, generic, * giftcard, transit and boarding pass that should be automatically attached to this loyalty * object. If a user had saved this loyalty card, then these linked_object_ids would be * automatically pushed to the user's wallet (unless they turned off the setting to receive such * linked passes). Make sure that objects present in linked_object_ids are already inserted - if * not, calls would fail. Once linked, the linked objects cannot be unlinked. You cannot link * objects belonging to another issuer. There is a limit to the number of objects that can be * linked to a single object. After the limit is reached, new linked objects in the call will be * ignored silently. Object IDs should follow the format issuer ID. identifier where the former is * issued by Google and the latter is chosen by you. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getLinkedObjectIds() { return linkedObjectIds; } /** * linked_object_ids are a list of other objects such as event ticket, loyalty, offer, generic, * giftcard, transit and boarding pass that should be automatically attached to this loyalty * object. If a user had saved this loyalty card, then these linked_object_ids would be * automatically pushed to the user's wallet (unless they turned off the setting to receive such * linked passes). Make sure that objects present in linked_object_ids are already inserted - if * not, calls would fail. Once linked, the linked objects cannot be unlinked. You cannot link * objects belonging to another issuer. There is a limit to the number of objects that can be * linked to a single object. After the limit is reached, new linked objects in the call will be * ignored silently. Object IDs should follow the format issuer ID. identifier where the former is * issued by Google and the latter is chosen by you. * @param linkedObjectIds linkedObjectIds or {@code null} for none */ public LoyaltyObject setLinkedObjectIds(java.util.List<java.lang.String> linkedObjectIds) { this.linkedObjectIds = linkedObjectIds; return this; } /** * A list of offer objects linked to this loyalty card. The offer objects must already exist. * Offer object IDs should follow the format issuer ID. identifier where the former is issued by * Google and latter is chosen by you. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getLinkedOfferIds() { return linkedOfferIds; } /** * A list of offer objects linked to this loyalty card. The offer objects must already exist. * Offer object IDs should follow the format issuer ID. identifier where the former is issued by * Google and latter is chosen by you. * @param linkedOfferIds linkedOfferIds or {@code null} for none */ public LoyaltyObject setLinkedOfferIds(java.util.List<java.lang.String> linkedOfferIds) { this.linkedOfferIds = linkedOfferIds; return this; } /** * Links module data. If links module data is also defined on the class, both will be displayed. * @return value or {@code null} for none */ public LinksModuleData getLinksModuleData() { return linksModuleData; } /** * Links module data. If links module data is also defined on the class, both will be displayed. * @param linksModuleData linksModuleData or {@code null} for none */ public LoyaltyObject setLinksModuleData(LinksModuleData linksModuleData) { this.linksModuleData = linksModuleData; return this; } /** * Note: This field is currently not supported to trigger geo notifications. * @return value or {@code null} for none */ public java.util.List<LatLongPoint> getLocations() { return locations; } /** * Note: This field is currently not supported to trigger geo notifications. * @param locations locations or {@code null} for none */ public LoyaltyObject setLocations(java.util.List<LatLongPoint> locations) { this.locations = locations; return this; } /** * The loyalty reward points label, balance, and type. * @return value or {@code null} for none */ public LoyaltyPoints getLoyaltyPoints() { return loyaltyPoints; } /** * The loyalty reward points label, balance, and type. * @param loyaltyPoints loyaltyPoints or {@code null} for none */ public LoyaltyObject setLoyaltyPoints(LoyaltyPoints loyaltyPoints) { this.loyaltyPoints = loyaltyPoints; return this; } /** * Merchant locations. There is a maximum of ten on the object. Any additional MerchantLocations * added beyond the 10 will be rejected. These locations will trigger a notification when a user * enters within a Google-set radius of the point. This field replaces the deprecated * LatLongPoints. * @return value or {@code null} for none */ public java.util.List<MerchantLocation> getMerchantLocations() { return merchantLocations; } /** * Merchant locations. There is a maximum of ten on the object. Any additional MerchantLocations * added beyond the 10 will be rejected. These locations will trigger a notification when a user * enters within a Google-set radius of the point. This field replaces the deprecated * LatLongPoints. * @param merchantLocations merchantLocations or {@code null} for none */ public LoyaltyObject setMerchantLocations(java.util.List<MerchantLocation> merchantLocations) { this.merchantLocations = merchantLocations; return this; } /** * An array of messages displayed in the app. All users of this object will receive its associated * messages. The maximum number of these fields is 10. * @return value or {@code null} for none */ public java.util.List<Message> getMessages() { return messages; } /** * An array of messages displayed in the app. All users of this object will receive its associated * messages. The maximum number of these fields is 10. * @param messages messages or {@code null} for none */ public LoyaltyObject setMessages(java.util.List<Message> messages) { this.messages = messages; return this; } /** * Whether or not field updates to this object should trigger notifications. When set to NOTIFY, * we will attempt to trigger a field update notification to users. These notifications will only * be sent to users if the field is part of an allowlist. If set to DO_NOT_NOTIFY or * NOTIFICATION_SETTINGS_UNSPECIFIED, no notification will be triggered. This setting is ephemeral * and needs to be set with each PATCH or UPDATE request, otherwise a notification will not be * triggered. * @return value or {@code null} for none */ public java.lang.String getNotifyPreference() { return notifyPreference; } /** * Whether or not field updates to this object should trigger notifications. When set to NOTIFY, * we will attempt to trigger a field update notification to users. These notifications will only * be sent to users if the field is part of an allowlist. If set to DO_NOT_NOTIFY or * NOTIFICATION_SETTINGS_UNSPECIFIED, no notification will be triggered. This setting is ephemeral * and needs to be set with each PATCH or UPDATE request, otherwise a notification will not be * triggered. * @param notifyPreference notifyPreference or {@code null} for none */ public LoyaltyObject setNotifyPreference(java.lang.String notifyPreference) { this.notifyPreference = notifyPreference; return this; } /** * Pass constraints for the object. Includes limiting NFC and screenshot behaviors. * @return value or {@code null} for none */ public PassConstraints getPassConstraints() { return passConstraints; } /** * Pass constraints for the object. Includes limiting NFC and screenshot behaviors. * @param passConstraints passConstraints or {@code null} for none */ public LoyaltyObject setPassConstraints(PassConstraints passConstraints) { this.passConstraints = passConstraints; return this; } /** * The rotating barcode type and value. * @return value or {@code null} for none */ public RotatingBarcode getRotatingBarcode() { return rotatingBarcode; } /** * The rotating barcode type and value. * @param rotatingBarcode rotatingBarcode or {@code null} for none */ public LoyaltyObject setRotatingBarcode(RotatingBarcode rotatingBarcode) { this.rotatingBarcode = rotatingBarcode; return this; } /** * Restrictions on the object that needs to be verified before the user tries to save the pass. * Note that this restrictions will only be applied during save time. If the restrictions changed * after a user saves the pass, the new restrictions will not be applied to an already saved pass. * @return value or {@code null} for none */ public SaveRestrictions getSaveRestrictions() { return saveRestrictions; } /** * Restrictions on the object that needs to be verified before the user tries to save the pass. * Note that this restrictions will only be applied during save time. If the restrictions changed * after a user saves the pass, the new restrictions will not be applied to an already saved pass. * @param saveRestrictions saveRestrictions or {@code null} for none */ public LoyaltyObject setSaveRestrictions(SaveRestrictions saveRestrictions) { this.saveRestrictions = saveRestrictions; return this; } /** * The secondary loyalty reward points label, balance, and type. Shown in addition to the primary * loyalty points. * @return value or {@code null} for none */ public LoyaltyPoints getSecondaryLoyaltyPoints() { return secondaryLoyaltyPoints; } /** * The secondary loyalty reward points label, balance, and type. Shown in addition to the primary * loyalty points. * @param secondaryLoyaltyPoints secondaryLoyaltyPoints or {@code null} for none */ public LoyaltyObject setSecondaryLoyaltyPoints(LoyaltyPoints secondaryLoyaltyPoints) { this.secondaryLoyaltyPoints = secondaryLoyaltyPoints; return this; } /** * The value that will be transmitted to a Smart Tap certified terminal over NFC for this object. * The class level fields `enableSmartTap` and `redemptionIssuers` must also be set up correctly * in order for the pass to support Smart Tap. Only ASCII characters are supported. If this value * is not set but the class level fields `enableSmartTap` and `redemptionIssuers` are set up * correctly, the `barcode.value` or the `accountId` fields are used as fallback if present. * @return value or {@code null} for none */ public java.lang.String getSmartTapRedemptionValue() { return smartTapRedemptionValue; } /** * The value that will be transmitted to a Smart Tap certified terminal over NFC for this object. * The class level fields `enableSmartTap` and `redemptionIssuers` must also be set up correctly * in order for the pass to support Smart Tap. Only ASCII characters are supported. If this value * is not set but the class level fields `enableSmartTap` and `redemptionIssuers` are set up * correctly, the `barcode.value` or the `accountId` fields are used as fallback if present. * @param smartTapRedemptionValue smartTapRedemptionValue or {@code null} for none */ public LoyaltyObject setSmartTapRedemptionValue(java.lang.String smartTapRedemptionValue) { this.smartTapRedemptionValue = smartTapRedemptionValue; return this; } /** * Required. The state of the object. This field is used to determine how an object is displayed * in the app. For example, an `inactive` object is moved to the "Expired passes" section. * @return value or {@code null} for none */ public java.lang.String getState() { return state; } /** * Required. The state of the object. This field is used to determine how an object is displayed * in the app. For example, an `inactive` object is moved to the "Expired passes" section. * @param state state or {@code null} for none */ public LoyaltyObject setState(java.lang.String state) { this.state = state; return this; } /** * Text module data. If text module data is also defined on the class, both will be displayed. The * maximum number of these fields displayed is 10 from the object and 10 from the class. * @return value or {@code null} for none */ public java.util.List<TextModuleData> getTextModulesData() { return textModulesData; } /** * Text module data. If text module data is also defined on the class, both will be displayed. The * maximum number of these fields displayed is 10 from the object and 10 from the class. * @param textModulesData textModulesData or {@code null} for none */ public LoyaltyObject setTextModulesData(java.util.List<TextModuleData> textModulesData) { this.textModulesData = textModulesData; return this; } /** * The time period this object will be `active` and object can be used. An object's state will be * changed to `expired` when this time period has passed. * @return value or {@code null} for none */ public TimeInterval getValidTimeInterval() { return validTimeInterval; } /** * The time period this object will be `active` and object can be used. An object's state will be * changed to `expired` when this time period has passed. * @param validTimeInterval validTimeInterval or {@code null} for none */ public LoyaltyObject setValidTimeInterval(TimeInterval validTimeInterval) { this.validTimeInterval = validTimeInterval; return this; } /** * Optional value added module data. Maximum of ten on the object. * @return value or {@code null} for none */ public java.util.List<ValueAddedModuleData> getValueAddedModuleData() { return valueAddedModuleData; } /** * Optional value added module data. Maximum of ten on the object. * @param valueAddedModuleData valueAddedModuleData or {@code null} for none */ public LoyaltyObject setValueAddedModuleData(java.util.List<ValueAddedModuleData> valueAddedModuleData) { this.valueAddedModuleData = valueAddedModuleData; return this; } /** * Deprecated * @return value or {@code null} for none */ public java.lang.Long getVersion() { return version; } /** * Deprecated * @param version version or {@code null} for none */ public LoyaltyObject setVersion(java.lang.Long version) { this.version = version; return this; } @Override public LoyaltyObject set(String fieldName, Object value) { return (LoyaltyObject) super.set(fieldName, value); } @Override public LoyaltyObject clone() { return (LoyaltyObject) super.clone(); } }
googleapis/google-cloud-java
36,851
java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/ListInstructionsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datalabeling/v1beta1/data_labeling_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datalabeling.v1beta1; /** * * * <pre> * Request message for ListInstructions. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListInstructionsRequest} */ public final class ListInstructionsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.ListInstructionsRequest) ListInstructionsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListInstructionsRequest.newBuilder() to construct. private ListInstructionsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListInstructionsRequest() { parent_ = ""; filter_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListInstructionsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.class, com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 3; private int pageSize_ = 0; /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_); } if (pageSize_ != 0) { output.writeInt32(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest other = (com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getFilter().equals(other.getFilter())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest 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 ListInstructions. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListInstructionsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.ListInstructionsRequest) com.google.cloud.datalabeling.v1beta1.ListInstructionsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.class, com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.Builder.class); } // Construct using com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; filter_ = ""; pageSize_ = 0; pageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListInstructionsRequest_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest build() { com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest buildPartial() { com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest result = new com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.filter_ = filter_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.pageToken_ = pageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest) { return mergeFrom((com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest other) { if (other == com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000002; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Instruction resource parent, format: * projects/{project_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000004); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListInstructionsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListInstructionsResponse.next_page_token] of the previous * [DataLabelingService.ListInstructions] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datalabeling.v1beta1.ListInstructionsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.ListInstructionsRequest) private static final com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest(); } public static com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListInstructionsRequest> PARSER = new com.google.protobuf.AbstractParser<ListInstructionsRequest>() { @java.lang.Override public ListInstructionsRequest 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<ListInstructionsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListInstructionsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListInstructionsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/jackrabbit-oak
37,163
oak-core/src/test/java/org/apache/jackrabbit/oak/security/authorization/accesscontrol/ACLTest.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.security.authorization.accesscontrol; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.ValueFormatException; import javax.jcr.security.AccessControlEntry; import javax.jcr.security.AccessControlException; import javax.jcr.security.Privilege; import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.api.security.JackrabbitAccessControlEntry; import org.apache.jackrabbit.api.security.JackrabbitAccessControlList; import org.apache.jackrabbit.api.security.authorization.PrivilegeManager; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.commons.collections.SetUtils; import org.apache.jackrabbit.oak.namepath.impl.GlobalNameMapper; import org.apache.jackrabbit.oak.namepath.impl.LocalNameMapper; import org.apache.jackrabbit.oak.namepath.NameMapper; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.namepath.impl.NamePathMapperImpl; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.ACE; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AbstractAccessControlList; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.AbstractRestrictionProvider; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.Restriction; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinitionImpl; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionPattern; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider; import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal; import org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Test; import static java.util.Collections.singletonMap; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test {@code ACL} implementation. */ public class ACLTest extends AbstractAccessControlTest implements PrivilegeConstants, AccessControlConstants { private ACL acl; @Override public void before() throws Exception { super.before(); acl = createACL(TEST_PATH, Collections.emptyList(), getNamePathMapper()); } private static void assertACE(@NotNull JackrabbitAccessControlEntry ace, boolean isAllow, @NotNull Privilege... privileges) { assertEquals(isAllow, ace.isAllow()); assertEquals(SetUtils.toSet(privileges), SetUtils.toSet(ace.getPrivileges())); } @NotNull private ACL createACL(@Nullable String jcrPath, @NotNull List<ACE> entries, @NotNull NamePathMapper namePathMapper) { return createACL(jcrPath, entries, namePathMapper, getRestrictionProvider()); } @NotNull private List<ACE> createTestEntries() throws RepositoryException { List<ACE> entries = new ArrayList<>(3); for (int i = 0; i < 3; i++) { entries.add(createEntry(new PrincipalImpl("testPrincipal" + i), true, null, PrivilegeConstants.JCR_READ)); } return entries; } @Test public void testGetNamePathMapper() { assertSame(getNamePathMapper(), acl.getNamePathMapper()); assertSame(NamePathMapper.DEFAULT, createACL(TEST_PATH, List.of(), NamePathMapper.DEFAULT).getNamePathMapper()); } @Test public void testGetPath() { NameMapper nameMapper = new GlobalNameMapper( Collections.singletonMap("jr", "http://jackrabbit.apache.org")); NamePathMapper npMapper = new NamePathMapperImpl(nameMapper); // map of jcr-path to standard jcr-path Map<String, String> paths = new HashMap<>(); paths.put(null, null); paths.put(TEST_PATH, TEST_PATH); paths.put("/", "/"); paths.put("/jr:testPath", "/jr:testPath"); paths.put("/{http://jackrabbit.apache.org}testPath", "/jr:testPath"); paths.forEach((key, value) -> { AbstractAccessControlList acl = createACL(key, Collections.emptyList(), npMapper); assertEquals(value, acl.getPath()); }); } @Test public void testGetOakPath() { NamePathMapper npMapper = new NamePathMapperImpl(new LocalNameMapper( singletonMap("oak", "http://jackrabbit.apache.org"), singletonMap("jcr", "http://jackrabbit.apache.org"))); // map of jcr-path to oak path Map<String, String> paths = new HashMap<>(); paths.put(null, null); paths.put(TEST_PATH, TEST_PATH); paths.put("/", "/"); String oakPath = "/oak:testPath"; String jcrPath = "/jcr:testPath"; paths.put(jcrPath, oakPath); jcrPath = "/{http://jackrabbit.apache.org}testPath"; paths.put(jcrPath, oakPath); // test if oak-path is properly set. paths.forEach((key, value) -> { AbstractAccessControlList acl = createACL(key, Collections.emptyList(), npMapper); assertEquals(value, acl.getOakPath()); }); } @Test public void testEmptyAcl() { assertNotNull(acl.getAccessControlEntries()); assertNotNull(acl.getEntries()); assertEquals(0, acl.getAccessControlEntries().length); assertEquals(acl.getAccessControlEntries().length, acl.getEntries().size()); assertEquals(0, acl.size()); assertTrue(acl.isEmpty()); } @Test public void testSize() throws RepositoryException { AbstractAccessControlList acl = createACL(TEST_PATH, createTestEntries(), getNamePathMapper()); assertEquals(3, acl.size()); } @Test public void testIsEmpty() throws RepositoryException { AbstractAccessControlList acl = createACL(TEST_PATH, createTestEntries(), getNamePathMapper()); assertFalse(acl.isEmpty()); } @Test public void testGetEntries() throws RepositoryException { List<ACE> aces = createTestEntries(); AbstractAccessControlList acl = createACL(TEST_PATH, aces, getNamePathMapper()); assertNotNull(acl.getEntries()); assertNotNull(acl.getAccessControlEntries()); assertEquals(aces.size(), acl.getEntries().size()); assertEquals(aces.size(), acl.getAccessControlEntries().length); assertTrue(acl.getEntries().containsAll(aces)); assertTrue(Arrays.asList(acl.getAccessControlEntries()).containsAll(aces)); } @Test public void testGetRestrictionNames() { String[] restrNames = acl.getRestrictionNames(); assertNotNull(restrNames); List<String> names = new ArrayList<>(Arrays.asList(restrNames)); for (RestrictionDefinition def : getRestrictionProvider().getSupportedRestrictions(TEST_PATH)) { assertTrue(names.remove(getNamePathMapper().getJcrName(def.getName()))); } assertTrue(names.isEmpty()); } @Test public void testGetRestrictionType() { for (RestrictionDefinition def : getRestrictionProvider().getSupportedRestrictions(TEST_PATH)) { int reqType = acl.getRestrictionType(getNamePathMapper().getJcrName(def.getName())); assertTrue(reqType > PropertyType.UNDEFINED); assertEquals(def.getRequiredType().tag(), reqType); } } @Test public void testGetRestrictionTypeForUnknownName() { // for backwards compatibility getRestrictionType(String) must return // UNDEFINED for a unknown restriction name: assertEquals(PropertyType.UNDEFINED, acl.getRestrictionType("unknownRestrictionName")); } @Test public void testAddEntriesWithCustomPrincipal() throws Exception { Principal oakPrincipal = new PrincipalImpl("anonymous"); Principal principal = () -> "anonymous"; assertTrue(acl.addAccessControlEntry(oakPrincipal, privilegesFromNames(JCR_READ))); assertTrue(acl.addAccessControlEntry(principal, privilegesFromNames(JCR_READ_ACCESS_CONTROL))); assertEquals(1, acl.getAccessControlEntries().length); assertTrue(acl.addEntry(principal, privilegesFromNames(JCR_READ), false)); assertEquals(2, acl.getAccessControlEntries().length); assertArrayEquals(privilegesFromNames(JCR_READ_ACCESS_CONTROL), acl.getAccessControlEntries()[0].getPrivileges()); } @Test(expected = AccessControlException.class) public void testAddEntryWithoutPrivilege() throws Exception { acl.addAccessControlEntry(testPrincipal, new Privilege[0]); } @Test(expected = AccessControlException.class) public void testAddEntryWithNullPrivilege() throws Exception { acl.addAccessControlEntry(testPrincipal, null); } @Test(expected = AccessControlException.class) public void testAddEntryWithInvalidPrivilege() throws Exception { Privilege invalid = when(mock(Privilege.class).getName()).thenReturn("invalid").getMock(); acl.addAccessControlEntry(testPrincipal, new Privilege[]{invalid}); } @Test(expected = AccessControlException.class) public void testAddEntryWithAbstractPrivilege() throws Exception { Privilege abstractPriv = when(mock(Privilege.class).isAbstract()).thenReturn(true).getMock(); when(abstractPriv.getName()).thenReturn("privName"); PrivilegeManager privMgr = when(mock(PrivilegeManager.class).getPrivilege(anyString())).thenReturn(abstractPriv).getMock(); ACL list = createACL(TEST_PATH, Collections.emptyList(), getNamePathMapper(), getRestrictionProvider(), privMgr); list.addAccessControlEntry(testPrincipal, new Privilege[] {abstractPriv}); } @Test public void testAddAccessControlEntry() throws Exception { assertTrue(acl.addAccessControlEntry(testPrincipal, testPrivileges)); assertFalse(acl.isEmpty()); } @Test public void testAddEntry() throws Exception { assertTrue(acl.addEntry(testPrincipal, testPrivileges, true)); assertFalse(acl.isEmpty()); } @Test public void testAddEntry2() throws Exception { assertTrue(acl.addEntry(testPrincipal, testPrivileges, true, Collections.emptyMap())); assertFalse(acl.isEmpty()); } @Test public void testAddEntryTwice() throws Exception { acl.addEntry(testPrincipal, testPrivileges, true, Collections.emptyMap()); assertFalse(acl.addEntry(testPrincipal, testPrivileges, true, Collections.emptyMap())); } @Test public void testRemoveEntry() throws Exception { assertTrue(acl.addAccessControlEntry(testPrincipal, testPrivileges)); acl.removeAccessControlEntry(acl.getAccessControlEntries()[0]); assertTrue(acl.isEmpty()); } @Test public void testRemoveEntries() throws Exception { JackrabbitAccessControlList acl = createACL(TEST_PATH, createTestEntries(), namePathMapper); for (AccessControlEntry ace : acl.getAccessControlEntries()) { acl.removeAccessControlEntry(ace); } assertTrue(acl.isEmpty()); } @Test(expected = AccessControlException.class) public void testRemoveInvalidEntry() throws Exception { JackrabbitAccessControlEntry ace = mockAccessControlEntry(testPrincipal, testPrivileges); acl.removeAccessControlEntry(ace); verify(ace, never()).getPrincipal(); verify(ace, never()).getPrivileges(); } @Test(expected = AccessControlException.class) public void testRemoveNonExisting() throws Exception { acl.removeAccessControlEntry(createEntry(testPrincipal, testPrivileges, true, Collections.emptySet())); } @Test public void testReorderToTheEnd() throws Exception { Privilege[] read = privilegesFromNames(JCR_READ, JCR_READ_ACCESS_CONTROL); Privilege[] write = privilegesFromNames(JCR_WRITE); acl.addAccessControlEntry(testPrincipal, read); acl.addEntry(testPrincipal, write, false); acl.addAccessControlEntry(EveryonePrincipal.getInstance(), write); List<? extends JackrabbitAccessControlEntry> entries = acl.getEntries(); assertEquals(3, entries.size()); AccessControlEntry first = entries.get(0); acl.orderBefore(first, null); List<? extends JackrabbitAccessControlEntry> entriesAfter = acl.getEntries(); assertEquals(first, entriesAfter.get(2)); } @Test public void testReorder() throws Exception { Privilege[] read = privilegesFromNames(JCR_READ, JCR_READ_ACCESS_CONTROL); Privilege[] write = privilegesFromNames(JCR_WRITE); acl.addAccessControlEntry(testPrincipal, read); acl.addEntry(testPrincipal, write, false); acl.addAccessControlEntry(EveryonePrincipal.getInstance(), write); AccessControlEntry[] entries = acl.getAccessControlEntries(); assertEquals(3, entries.length); AccessControlEntry first = entries[0]; AccessControlEntry second = entries[1]; AccessControlEntry third = entries[2]; // reorder 'second' to the first position acl.orderBefore(second, first); assertEquals(second, acl.getEntries().get(0)); assertEquals(first, acl.getEntries().get(1)); assertEquals(third, acl.getEntries().get(2)); // reorder 'third' before 'first' acl.orderBefore(third, first); assertEquals(second, acl.getEntries().get(0)); assertEquals(third, acl.getEntries().get(1)); assertEquals(first, acl.getEntries().get(2)); } @Test(expected = AccessControlException.class) public void testReorderInvalidSourceEntry() throws Exception { acl.addAccessControlEntry(testPrincipal, privilegesFromNames(JCR_READ, JCR_READ_ACCESS_CONTROL)); acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privilegesFromNames(JCR_WRITE)); AccessControlEntry invalid = createEntry(testPrincipal, false, null, JCR_WRITE); acl.orderBefore(invalid, acl.getEntries().get(0)); } @Test(expected = AccessControlException.class) public void testReorderInvalidSourcDestEntry() throws Exception { acl.addAccessControlEntry(testPrincipal, privilegesFromNames(JCR_READ, JCR_READ_ACCESS_CONTROL)); acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privilegesFromNames(JCR_WRITE)); AccessControlEntry invalid = createEntry(testPrincipal, false, null, JCR_MODIFY_PROPERTIES); acl.orderBefore(acl.getEntries().get(0), invalid); } @Test public void testReorderSourceSameAsDest() throws Exception { acl.addAccessControlEntry(testPrincipal, privilegesFromNames(JCR_READ, JCR_READ_ACCESS_CONTROL)); acl.addEntry(testPrincipal, privilegesFromNames(JCR_WRITE), false); acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privilegesFromNames(JCR_WRITE)); AccessControlEntry[] entries = acl.getAccessControlEntries(); assertEquals(3, entries.length); acl.orderBefore(entries[1], entries[1]); assertArrayEquals(entries, acl.getAccessControlEntries()); } @Test public void testMultipleEntries() throws Exception { Privilege[] privileges = privilegesFromNames(JCR_READ); acl.addEntry(testPrincipal, privileges, true); // new entry extends privileges. privileges = privilegesFromNames(JCR_READ, JCR_ADD_CHILD_NODES); assertTrue(acl.addEntry(testPrincipal, privileges, true)); // expected: only a single allow-entry with both privileges assertEquals(1, acl.size()); assertACE(acl.getEntries().get(0), true, privileges); } @Test public void testMultipleEntries2() throws Exception { Privilege[] privileges = privilegesFromNames(JCR_READ, JCR_ADD_CHILD_NODES); acl.addEntry(testPrincipal, privileges, true); // adding just ADD_CHILD_NODES -> must not remove READ privilege Privilege[] achPrivs = privilegesFromNames(JCR_ADD_CHILD_NODES); assertFalse(acl.addEntry(testPrincipal, achPrivs, true)); // expected: only a single allow-entry with add_child_nodes + read privilege assertEquals(1, acl.size()); assertACE(acl.getEntries().get(0), true, privileges); } @Test public void testComplementaryEntry() throws Exception { Privilege[] privileges = privilegesFromNames(JCR_READ); acl.addEntry(testPrincipal, privileges, true); // same entry but with revers 'isAllow' flag assertTrue(acl.addEntry(testPrincipal, privileges, false)); // expected: only a single deny-read entry assertEquals(1, acl.size()); assertACE(acl.getEntries().get(0), false, privileges); } @Test public void testComplementaryEntry1() throws Exception { Privilege[] privileges = privilegesFromNames(JCR_READ, JCR_ADD_CHILD_NODES); acl.addEntry(testPrincipal, privileges, true); // revoke the 'READ' privilege privileges = privilegesFromNames(JCR_READ); assertTrue(acl.addEntry(testPrincipal, privileges, false)); // expected: 2 entries one allowing ADD_CHILD_NODES, the other denying READ assertEquals(2, acl.size()); assertACE(acl.getEntries().get(0), true, privilegesFromNames(JCR_ADD_CHILD_NODES)); assertACE(acl.getEntries().get(1), false, privilegesFromNames(JCR_READ)); } @Test public void testComplementaryEntry2() throws Exception { Privilege[] repwrite = privilegesFromNames(REP_WRITE); acl.addAccessControlEntry(testPrincipal, repwrite); // add deny entry for mod_props Privilege[] modProperties = privilegesFromNames(JCR_MODIFY_PROPERTIES); assertTrue(acl.addEntry(testPrincipal, modProperties, false)); // expected: 2 entries with the allow entry being adjusted assertEquals(2, acl.size()); Privilege[] expected = privilegesFromNames(JCR_ADD_CHILD_NODES, JCR_REMOVE_CHILD_NODES, JCR_REMOVE_NODE, JCR_NODE_TYPE_MANAGEMENT); assertACE(acl.getEntries().get(0), true, expected); assertACE(acl.getEntries().get(1), false, modProperties); } @Test public void testComplementaryEntry3() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); acl.addAccessControlEntry(testPrincipal, privilegesFromNames(JCR_WRITE)); acl.addEntry(testPrincipal, readPriv, false); acl.addAccessControlEntry(testPrincipal, readPriv); List<? extends JackrabbitAccessControlEntry> entries = acl.getEntries(); assertEquals(1, entries.size()); } @Test public void testMultiplePrincipals() throws Exception { Principal everyone = principalManager.getEveryone(); Privilege[] privs = privilegesFromNames(JCR_READ); acl.addAccessControlEntry(testPrincipal, privs); assertFalse(acl.addAccessControlEntry(testPrincipal, privs)); // add same privileges for another principal -> must modify as well. assertTrue(acl.addAccessControlEntry(everyone, privs)); // .. 2 entries must be present. assertEquals(2, acl.getAccessControlEntries().length); assertEquals(everyone, acl.getAccessControlEntries()[1].getPrincipal()); } @Test public void testSetEntryForGroupPrincipal() throws Exception { Privilege[] privs = privilegesFromNames(JCR_READ); Principal grPrincipal = principalManager.getEveryone(); // adding allow-entry must succeed assertTrue(acl.addAccessControlEntry(grPrincipal, privs)); // adding deny-entry must succeed assertTrue(acl.addEntry(grPrincipal, privs, false)); assertEquals(1, acl.size()); assertFalse(acl.getEntries().get(0).isAllow()); } @Test public void testUpdateGroupEntry() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); Principal everyone = principalManager.getEveryone(); acl.addEntry(testPrincipal, readPriv, true); acl.addEntry(everyone, readPriv, true); acl.addEntry(testPrincipal, writePriv, false); // adding an entry that should update the existing allow-entry for everyone. acl.addEntry(everyone, writePriv, true); AccessControlEntry[] entries = acl.getAccessControlEntries(); assertEquals(3, entries.length); JackrabbitAccessControlEntry princ2AllowEntry = (JackrabbitAccessControlEntry) entries[1]; assertEquals(everyone, princ2AllowEntry.getPrincipal()); assertACE(princ2AllowEntry, true, privilegesFromNames(JCR_READ, JCR_WRITE)); } @Test public void testComplementaryGroupEntry() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); Principal everyone = principalManager.getEveryone(); acl.addEntry(testPrincipal, readPriv, true); acl.addEntry(everyone, readPriv, true); acl.addEntry(testPrincipal, writePriv, false); acl.addEntry(everyone, writePriv, true); // entry complementary to the first entry // -> must remove the allow-READ entry and update the deny-WRITE entry. acl.addEntry(testPrincipal, readPriv, false); AccessControlEntry[] entries = acl.getAccessControlEntries(); assertEquals(2, entries.length); JackrabbitAccessControlEntry first = (JackrabbitAccessControlEntry) entries[0]; assertEquals(everyone, first.getPrincipal()); JackrabbitAccessControlEntry second = (JackrabbitAccessControlEntry) entries[1]; assertEquals(testPrincipal, second.getPrincipal()); assertACE(second, false, privilegesFromNames(JCR_READ, JCR_WRITE)); } @Test public void testAllowWriteDenyRemoveGroupEntries() throws Exception { Principal everyone = principalManager.getEveryone(); Privilege[] grPriv = privilegesFromNames(REP_WRITE); Privilege[] dePriv = privilegesFromNames(JCR_REMOVE_CHILD_NODES); acl.addEntry(everyone, grPriv, true, Collections.emptyMap()); acl.addEntry(everyone, dePriv, false, Collections.emptyMap()); Set<Privilege> allows = new HashSet<>(); Set<Privilege> denies = new HashSet<>(); AccessControlEntry[] entries = acl.getAccessControlEntries(); for (AccessControlEntry en : entries) { if (everyone.equals(en.getPrincipal()) && en instanceof JackrabbitAccessControlEntry) { JackrabbitAccessControlEntry ace = (JackrabbitAccessControlEntry) en; Privilege[] privs = ace.getPrivileges(); if (ace.isAllow()) { allows.addAll(Arrays.asList(privs)); } else { denies.addAll(Arrays.asList(privs)); } } } Privilege[] expected = privilegesFromNames(JCR_ADD_CHILD_NODES, JCR_REMOVE_NODE, JCR_MODIFY_PROPERTIES, JCR_NODE_TYPE_MANAGEMENT); assertEquals(expected.length, allows.size()); assertEquals(Set.of(expected), allows); assertEquals(1, denies.size()); assertArrayEquals(privilegesFromNames(JCR_REMOVE_CHILD_NODES), denies.toArray(new Privilege[0])); } @Test public void testUpdateAndComplementary() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); Privilege[] acReadPriv = privilegesFromNames(JCR_READ_ACCESS_CONTROL); assertTrue(acl.addEntry(testPrincipal, readPriv, true)); assertTrue(acl.addEntry(testPrincipal, writePriv, true)); assertTrue(acl.addEntry(testPrincipal, acReadPriv, true)); assertEquals(1, acl.size()); assertTrue(acl.addEntry(testPrincipal, readPriv, false)); assertEquals(2, acl.size()); assertACE(acl.getEntries().get(0), true, privilegesFromNames(JCR_WRITE, JCR_READ_ACCESS_CONTROL)); assertACE(acl.getEntries().get(1), false, readPriv); } @Test public void testDifferentPrivilegeImplementation() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); acl.addEntry(testPrincipal, readPriv, false); assertFalse(acl.addEntry(new PrincipalImpl(testPrincipal.getName()), readPriv, false)); assertFalse(acl.addEntry(() -> testPrincipal.getName(), readPriv, false)); } @Test public void testNewEntriesAppendedAtEnd() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); acl.addEntry(testPrincipal, readPriv, true); acl.addEntry(principalManager.getEveryone(), readPriv, true); acl.addEntry(testPrincipal, writePriv, false); AccessControlEntry[] entries = acl.getAccessControlEntries(); assertEquals(3, entries.length); JackrabbitAccessControlEntry last = (JackrabbitAccessControlEntry) entries[2]; assertEquals(testPrincipal, last.getPrincipal()); assertACE(last, false, writePriv); } @Test public void testInsertionOrder() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); Privilege[] addNodePriv = privilegesFromNames(JCR_ADD_CHILD_NODES); Map<String, Value> restrictions = Collections.singletonMap(REP_GLOB, getValueFactory().createValue("/.*")); acl.addEntry(testPrincipal, readPriv, true); acl.addEntry(testPrincipal, writePriv, false); acl.addEntry(testPrincipal, addNodePriv, true, restrictions); List<? extends JackrabbitAccessControlEntry> entries = acl.getEntries(); assertACE(entries.get(0), true, readPriv); assertACE(entries.get(1), false, writePriv); assertACE(entries.get(2), true, addNodePriv); } @Test public void testInsertionOrder2() throws Exception { Privilege[] readPriv = privilegesFromNames(JCR_READ); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); Privilege[] addNodePriv = privilegesFromNames(JCR_ADD_CHILD_NODES); Map<String, Value> restrictions = Collections.singletonMap(REP_GLOB, getValueFactory().createValue("/.*")); acl.addEntry(testPrincipal, readPriv, true); acl.addEntry(testPrincipal, addNodePriv, true, restrictions); acl.addEntry(testPrincipal, writePriv, false); List<? extends JackrabbitAccessControlEntry> entries = acl.getEntries(); assertACE(entries.get(0), true, readPriv); assertACE(entries.get(1), true, addNodePriv); assertACE(entries.get(2), false, writePriv); } @Test public void testRestrictions() throws Exception { String[] names = acl.getRestrictionNames(); assertNotNull(names); assertArrayEquals(new String[] {REP_GLOB, REP_NT_NAMES, REP_PREFIXES, REP_ITEM_NAMES, REP_CURRENT, REP_GLOBS, REP_SUBTREES}, names); assertEquals(PropertyType.STRING, acl.getRestrictionType(names[0])); assertEquals(PropertyType.NAME, acl.getRestrictionType(names[1])); assertEquals(PropertyType.STRING, acl.getRestrictionType(names[2])); assertEquals(PropertyType.NAME, acl.getRestrictionType(names[3])); Privilege[] writePriv = privilegesFromNames(JCR_WRITE); // add entry without restr. -> must succeed assertTrue(acl.addAccessControlEntry(testPrincipal, writePriv)); assertEquals(1, acl.getAccessControlEntries().length); // ... again -> no modification. assertFalse(acl.addAccessControlEntry(testPrincipal, writePriv)); assertEquals(1, acl.getAccessControlEntries().length); // ... again using different method -> no modification. assertFalse(acl.addEntry(testPrincipal, writePriv, true)); assertEquals(1, acl.getAccessControlEntries().length); // ... complementary entry -> must modify the acl assertTrue(acl.addEntry(testPrincipal, writePriv, false)); assertEquals(1, acl.getAccessControlEntries().length); // add an entry with a restrictions: Map<String, Value> restrictions = Collections.singletonMap(REP_GLOB, getValueFactory().createValue("/.*")); assertTrue(acl.addEntry(testPrincipal, writePriv, false, restrictions)); assertEquals(2, acl.getAccessControlEntries().length); // ... same again -> no modification. assertFalse(acl.addEntry(testPrincipal, writePriv, false, restrictions)); assertEquals(2, acl.getAccessControlEntries().length); // ... complementary entry -> must modify the acl. assertTrue(acl.addEntry(testPrincipal, writePriv, true, restrictions)); assertEquals(2, acl.getAccessControlEntries().length); } @Test public void testMvRestrictions() throws Exception { ValueFactory vf = getValueFactory(); Value[] vs = new Value[] { vf.createValue(JcrConstants.NT_FILE, PropertyType.NAME), vf.createValue(JcrConstants.NT_FOLDER, PropertyType.NAME) }; Map<String, Value[]> mvRestrictions = Collections.singletonMap(REP_NT_NAMES, vs); Map<String, Value> restrictions = Collections.singletonMap(REP_GLOB, vf.createValue("/.*")); assertTrue(acl.addEntry(testPrincipal, testPrivileges, false, restrictions, mvRestrictions)); assertFalse(acl.addEntry(testPrincipal, testPrivileges, false, restrictions, mvRestrictions)); assertEquals(1, acl.getAccessControlEntries().length); JackrabbitAccessControlEntry ace = (JackrabbitAccessControlEntry) acl.getAccessControlEntries()[0]; try { ace.getRestriction(REP_NT_NAMES); fail(); } catch (ValueFormatException e) { // success } Value[] vvs = ace.getRestrictions(REP_NT_NAMES); assertArrayEquals(vs, vvs); } @Test public void testUnsupportedRestrictions() throws Exception { Map<String, Value> restrictions = Collections.singletonMap("unknownRestriction", getValueFactory().createValue("value")); try { acl.addEntry(testPrincipal, testPrivileges, false, restrictions); fail("Invalid restrictions -> AccessControlException expected"); } catch (AccessControlException e) { // success } } @Test(expected = AccessControlException.class) public void testUnsupportedRestrictions2() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("restr", Type.NAME, false); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); acl.addEntry(testPrincipal, testPrivileges, false, Collections.singletonMap("unsupported", getValueFactory().createValue("value"))); } @Test(expected = AccessControlException.class) public void testInvalidRestrictionType() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("restr", Type.NAME, false); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); acl.addEntry(testPrincipal, testPrivileges, false, Collections.singletonMap("restr", getValueFactory().createValue(true))); } @Test(expected = AccessControlException.class) public void testMandatoryRestrictions() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("mandatory", Type.NAME, true); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); acl.addEntry(testPrincipal, testPrivileges, false, Collections.emptyMap(), Collections.emptyMap()); } @Test public void testMandatoryRestrictionsPresent() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("mandatory", Type.NAME, true); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); assertTrue(acl.addEntry(testPrincipal, testPrivileges, false, Collections.singletonMap("mandatory", getValueFactory(root).createValue("name", PropertyType.NAME)), Collections.emptyMap())); } @Test(expected = AccessControlException.class) public void testMandatoryRestrictionsPresentAsMV() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("mandatory", Type.NAME, true); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); acl.addEntry(testPrincipal, testPrivileges, false, Collections.emptyMap(), Collections.singletonMap("mandatory", new Value[] {getValueFactory(root).createValue("name", PropertyType.NAME)})); } @Test(expected = AccessControlException.class) public void testMandatoryMVRestrictions() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("mandatory", Type.NAMES, true); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); acl.addEntry(testPrincipal, testPrivileges, false, Collections.emptyMap(), Collections.emptyMap()); } @Test(expected = AccessControlException.class) public void testMandatoryMVRestrictionsPresentAsSingle() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("mandatory", Type.NAMES, true); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); acl.addEntry(testPrincipal, testPrivileges, false, Collections.singletonMap("mandatory", getValueFactory(root).createValue("name", PropertyType.NAME)), Collections.emptyMap()); } @Test public void testMandatoryMVRestrictionsPresent() throws Exception { RestrictionProvider rp = new TestRestrictionProvider("mandatory", Type.NAMES, true); JackrabbitAccessControlList acl = createACL(TEST_PATH, new ArrayList<>(), getNamePathMapper(), rp); assertTrue(acl.addEntry(testPrincipal, testPrivileges, false, Collections.emptyMap(), Collections.singletonMap("mandatory", new Value[] {getValueFactory(root).createValue("name", PropertyType.NAME)}))); } //-------------------------------------------------------------------------- private static final class TestRestrictionProvider extends AbstractRestrictionProvider { private TestRestrictionProvider(@NotNull String name, @NotNull Type type, boolean isMandatory) { super(Collections.singletonMap(name, new RestrictionDefinitionImpl(name, type, isMandatory))); } @NotNull @Override public RestrictionPattern getPattern(@Nullable String oakPath, @NotNull Tree tree) { throw new UnsupportedOperationException(); } @NotNull @Override public RestrictionPattern getPattern(@Nullable String oakPath, @NotNull Set<Restriction> restrictions) { throw new UnsupportedOperationException(); } } }
apache/jackrabbit
36,953
jackrabbit-jcr-tests/src/main/java/org/apache/jackrabbit/test/api/version/VersionTest.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.test.api.version; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.Version; import javax.jcr.version.VersionManager; import javax.jcr.ItemVisitor; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Property; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.ItemNotFoundException; import javax.jcr.PropertyIterator; import javax.jcr.Value; import javax.jcr.PropertyType; import javax.jcr.Repository; import javax.jcr.lock.LockException; import javax.jcr.lock.LockManager; import java.util.GregorianCalendar; import java.util.Calendar; import java.util.List; import java.util.Arrays; import java.io.InputStream; import java.io.ByteArrayInputStream; /** * <code>VersionTest</code> covers tests related to the methods of the {@link * javax.jcr.version.Version} class. * */ public class VersionTest extends AbstractVersionTest { private VersionManager versionManager; private Version version; private Version version2; /** * helper class used in testAccept() */ private class ItemVisitorTest implements ItemVisitor { Node ivtNode; public ItemVisitorTest(Version v) { ivtNode = v; } public void visit(Node node) throws RepositoryException { assertTrue("Version.accept(ItemVisitor) does not provide the right node to the ItemVisitor", ivtNode.isSame(node)); } public void visit(Property property) throws RepositoryException { } } protected void setUp() throws Exception { super.setUp(); versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); // create two versions version = versionManager.checkin(versionableNode.getPath()); versionManager.checkout(versionableNode.getPath()); version2 = versionManager.checkin(versionableNode.getPath()); } protected void tearDown() throws Exception { // check the node out, so that it can be removed versionManager.checkout(versionableNode.getPath()); version = null; version2 = null; super.tearDown(); } /** * Tests if <code>Version.accept(ItemVisitor)</code> accepts a ItemVisitor * and if the right Node is provided to that visitor. */ public void testAccept() throws Exception { ItemVisitorTest ivt = new ItemVisitorTest(version); version.accept(ivt); } /** * Tests if <code>Version.addMixin(String)</code> throws a {@link * javax.jcr.nodetype.ConstraintViolationException} */ public void testAddMixin() throws Exception { try { version.addMixin(mixVersionable); fail("Version should be read-only: Version.addMixin(String) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.addNode(String)</code> and * <code>Version.addNode(String, String)</code> throw a {@link * javax.jcr.nodetype.ConstraintViolationException} */ public void testAddNode() throws Exception { try { version.addNode(nodeName4); version.getSession().save(); fail("Version should be read-only: Version.addNode(String) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.addNode(nodeName4, ntBase); version.getSession().save(); fail("Version should be read-only: Version.addNode(String,String) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.canAddMixin(String)</code> returns * <code>false</code> */ public void testCanAddMixin() throws Exception { assertFalse("Version should be read-only: Version.canAddMixin(String) returned true", version.canAddMixin(mixVersionable)); } /** * Tests if <code>Version.cancelMerge(Version)</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testCancelMerge() throws Exception { try { version.cancelMerge(version2); fail("Version.cancelMerge(Version) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.cancelMerge(Version)</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testCancelMergeJcr2() throws Exception { try { versionManager.cancelMerge(version.getPath(), version2); fail("Version.cancelMerge(Version) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.checkin()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testCheckin() throws Exception { try { version.checkin(); fail("Version.checkin() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.checkin()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testCheckinJcr2() throws Exception { try { versionManager.checkin(version.getPath()); fail("Version.checkin() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.checkout()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testCheckout() throws Exception { try { version.checkout(); fail("Version.checkout() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.checkout()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testCheckoutJcr2() throws Exception { try { versionManager.checkout(version.getPath()); fail("Version.checkout() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.doneMerge(Version)</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testDoneMerge() throws Exception { try { version.doneMerge(version2); fail("Version should not be versionable: Version.doneMerge(Version) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.doneMerge(Version)</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testDoneMergeJcr2() throws Exception { try { versionManager.doneMerge(version.getPath(), version2); fail("Version should not be versionable: Version.doneMerge(Version) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.getAncestor(int)</code> returns the right * ancestor */ public void testGetAncestor() throws Exception { assertTrue("Version.getAncestor(int) does not work", superuser.getRootNode().isSame(version.getAncestor(0))); } /** * Tests if <code>Version.getBaseVersion()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testGetBaseVersion() throws Exception { try { version.getBaseVersion(); fail("Version.getBaseVersion() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.getBaseVersion()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testGetBaseVersionJcr2() throws Exception { try { versionManager.getBaseVersion(version.getPath()); fail("Version.getBaseVersion() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.getCorrespondingNodePath(String)</code> returns * the right path */ public void testGetCorrespondingNodePath() throws Exception { assertEquals("Version.getCorrespondingNodePath(String) did not return the right path", version.getPath(), version.getCorrespondingNodePath(workspaceName)); } /** * Tests if <code>Version.getDepth()</code> returns the right depth */ public void testGetDepth() throws Exception { assertTrue("Version.getDepth() mismatch", version.getDepth() >= 4); } /** * Tests if <code>Version.getIndex()</code> returns the right index */ public void testGetIndex() throws Exception { assertEquals("Version.getIndex() mismatch", 1, version.getIndex()); } /** * Tests if <code>Version.getLock()</code> throws a {@link * javax.jcr.lock.LockException} */ public void testGetLock() throws Exception { try { version.getLock(); fail("Version should not be lockable: Version.getLock() did not throw a LockException"); } catch (LockException success) { } catch (UnsupportedRepositoryOperationException maybe) { assertFalse(isSupported(Repository.OPTION_LOCKING_SUPPORTED)); } } /** * Tests if <code>Version.getLock()</code> throws a {@link * javax.jcr.lock.LockException} */ public void testGetLockJcr2() throws Exception { ensureLockingSupported(); try { version.getSession().getWorkspace().getLockManager().getLock(version.getPath()); fail("Version should not be lockable: Version.getLock() did not throw a LockException"); } catch (LockException success) { } } /** * Tests if <code>Version.getMixinNodeTypes()</code> does not return null. */ public void testGetMixinNodeTypes() throws Exception { NodeType[] ntArray = version.getMixinNodeTypes(); assertNotNull("Version.getMixinNodeTypes returns null array", ntArray); } /** * Tests if <code>Version.getName()</code> returns the right name */ public void testGetName() throws Exception { assertTrue("Version.getName() does not return the right name", versionableNode.getVersionHistory().getVersion(version.getName()).isSame(version)); } /** * Tests if <code>Version.getNode(String)</code> returns the right child * Node */ public void testGetNode() throws Exception { assertTrue("Version.getNode(String) does not return a sub-node of type nt:frozenNode", version.getNode(jcrFrozenNode).isNodeType(ntFrozenNode)); } /** * Tests if <code>Version.getNodes()</code> and <code>Version.getNodes(String)</code> * returns the right child Node */ public void testGetNodes() throws Exception { assertTrue("Version.getNodes() does not return a sub-node of type nt:frozenNode", version.getNodes().nextNode().isNodeType(ntFrozenNode)); assertTrue("Version.getNodes(String) does not return a sub-node of type nt:frozenNode", version.getNodes(superuser.getNamespacePrefix(NS_JCR_URI) + ":*").nextNode().isNodeType(ntFrozenNode)); } /** * Tests if <code>Version.getParent()</code> returns the right parent Node */ public void testGetParent() throws Exception { assertTrue("Version.getParent() does not return a parent-node of type nt:versionHistory", version.getParent().isNodeType(ntVersionHistory)); } /** * Tests if <code>Version.getPath()</code> returns the right path */ public void testGetPath() throws Exception { assertTrue("Version.getPath() does not return the right path", version.getPath().startsWith("/" + superuser.getNamespacePrefix(NS_JCR_URI) + ":system/" + superuser.getNamespacePrefix(NS_JCR_URI) + ":versionStorage/")); } /** * Tests if <code>Version.getPrimaryItem()</code> throws a {@link * javax.jcr.ItemNotFoundException} */ public void testGetPrimaryItem() throws Exception { try { version.getPrimaryItem(); fail("Version.getPrimaryItem() did not throw a ItemNotFoundException"); } catch (ItemNotFoundException success) { } } /** * Tests if <code>Version.getPrimaryNodeType()</code> returns the right * primary node type <code>nt:version</code> */ public void testGetPrimaryNodeType() throws Exception { assertEquals("Version does not have the primary node type nt:version", ntVersion, version.getPrimaryNodeType().getName()); } /** * Tests if <code>Version.getProperties()</code> and * <code>Version.getProperties(String)</code> return the right property */ public void testGetProperties() throws Exception { PropertyIterator pi = version.getProperties(); boolean hasPropertyCreated = false; while (pi.hasNext()) { if (pi.nextProperty().getName().equals(jcrCreated)) { hasPropertyCreated = true; } } assertTrue("Version.getProperties() does not return property jcr:created", hasPropertyCreated); pi = version.getProperties(superuser.getNamespacePrefix(NS_JCR_URI) + ":*"); hasPropertyCreated = false; while (pi.hasNext()) { if (pi.nextProperty().getName().equals(jcrCreated)) { hasPropertyCreated = true; } } assertTrue("Version.getProperties(String) does not return property jcr:created", hasPropertyCreated); } /** * Tests if <code>Version.getProperty(String)</code> returns the right * property */ public void testGetProperty() throws Exception { assertTrue("Version.getProperty(String) does not return property jcr:created", version.getProperty(jcrCreated).getName().equals(jcrCreated)); } /** * Tests if <code>Version.getSession()</code> returns the right session */ public void testGetSession() throws Exception { assertSame("Version.getSession() did not return the right session", superuser, version.getSession()); } /** * Tests if <code>Version.getVersionHistory()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testGetVersionHistory() throws Exception { try { version.getVersionHistory(); fail("Version.getVersionHistory() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.getVersionHistory()</code> throws an {@link * javax.jcr.UnsupportedRepositoryOperationException} */ public void testGetVersionHistoryJcr2() throws Exception { try { versionManager.getVersionHistory(version.getPath()); fail("Version.getVersionHistory() did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.getUUID()</code> returns the right UUID */ public void testGetUUID() throws Exception { List<Value> successorValues = Arrays.asList(versionableNode.getVersionHistory().getRootVersion().getProperty(jcrSuccessors).getValues()); assertTrue("Version.getUUID() did not return the right UUID", successorValues.contains(superuser.getValueFactory().createValue(version))); } /** * Tests if <code>Version.hasNode(String)</code> returns the right * <code>boolean</code> value */ public void testHasNode() throws Exception { assertTrue("Version.hasNode(String) did not return true", version.hasNode(jcrFrozenNode)); } /** * Tests if <code>Version.hasNodes()</code> returns <code>true</code> */ public void testHasNodes() throws Exception { assertTrue("Version.hasNodes() did not return true", version.hasNodes()); } /** * Tests if <code>Version.hasProperties()</code> returns <code>true</code> */ public void testHasProperties() throws Exception { assertTrue("Version.hasProperties() did not return true", version.hasProperties()); } /** * Tests if <code>Version.hasProperty(String)</code> returns the right * <code>boolean</code> value */ public void testHasProperty() throws Exception { assertTrue("Version.hasProperty(String) did not return true", version.hasProperty(jcrCreated)); } /** * Tests if <code>Version.holdsLock()</code> returns <code>false</code> */ public void testHoldsLock() throws Exception { ensureLockingSupported(); assertFalse("Version.holdsLock() did not return false", version.holdsLock()); } /** * Tests if <code>Version.holdsLock()</code> returns <code>false</code> */ public void testHoldsLockJcr2() throws Exception { ensureLockingSupported(); assertFalse("Version.holdsLock() did not return false", version.getSession().getWorkspace().getLockManager().holdsLock(version.getPath())); } /** * Tests if <code>Version.isCheckedOut()</code> returns <code>true</code> */ public void testIsCheckedOut() throws Exception { assertTrue("Version.isCheckedOut() did not return true", version.isCheckedOut()); } /** * Tests if <code>Version.isCheckedOut()</code> returns <code>true</code> */ public void testIsCheckedOutJcr2() throws Exception { assertTrue("Version.isCheckedOut() did not return true", versionManager.isCheckedOut(version.getPath())); } /** * Tests if <code>Version.isLocked()</code> returns <code>false</code> */ public void testIsLocked() throws Exception { assertFalse("Version.isLocked() did not return false", version.isLocked()); } /** * Tests if <code>Version.isLocked()</code> returns <code>false</code> */ public void testIsLockedJcr2() throws Exception { ensureLockingSupported(); assertFalse("Version.isLocked() did not return false", version.getSession().getWorkspace().getLockManager().isLocked(version.getPath())); } /** * Tests if <code>Version.isModified()</code> returns <code>false</code> */ public void testIsModified() throws Exception { assertFalse("Version.isModified() did not return false", version.isModified()); } /** * Tests if <code>Version.isNew()</code> returns <code>false</code> */ public void testIsNew() throws Exception { assertFalse("Version.isNew() did not return false", version.isNew()); } /** * Tests if <code>Version.isNode()</code> returns <code>true</code> */ public void testIsNode() throws Exception { assertTrue("Version.isNode() did not return true", version.isNode()); } /** * Tests if <code>Version.isNodeType(String)</code> returns the right * <code>boolean</code> value */ public void testIsNodeType() throws Exception { assertTrue("Version.isNodeType(String) did not return true for nt:version", version.isNodeType(ntVersion)); } /** * Tests if <code>Version.isSame()</code> returns the right * <code>boolean</code> value */ public void testIsSame() throws Exception { assertTrue("Version.isSame(Item) did not return true", version2.isSame(versionableNode.getBaseVersion())); } /** * Tests if <code>Version.isSame()</code> returns the right * <code>boolean</code> value */ public void testIsSameJcr2() throws Exception { assertTrue("Version.isSame(Item) did not return true", version2.isSame(versionManager.getBaseVersion(versionableNode.getPath()))); } /** * Tests if <code>Version.lock(boolean, boolean)</code> throws a {@link * LockException} */ public void testLock() throws Exception { ensureLockingSupported(); try { version.lock(true, true); fail("Version should not be lockable: Version.lock(true,true) did not throw a LockException"); } catch (LockException success) { } try { version.lock(true, false); fail("Version should not be lockable: Version.lock(true,false) did not throw a LockException"); } catch (LockException success) { } try { version.lock(false, true); fail("Version should not be lockable: Version.lock(false,true) did not throw a LockException"); } catch (LockException success) { } try { version.lock(false, false); fail("Version should not be lockable: Version.lock(false,false) did not throw a LockException"); } catch (LockException success) { } } /** * Tests if <code>Version.lock(boolean, boolean)</code> throws a {@link * LockException} */ public void testLockJcr2() throws Exception { ensureLockingSupported(); LockManager lockManager = version.getSession().getWorkspace().getLockManager(); String path = version.getPath(); try { lockManager.lock(path, true, true, 60, ""); fail("Version should not be lockable: Version.lock(true,true) did not throw a LockException"); } catch (LockException success) { } try { lockManager.lock(path, true, false, 60, ""); fail("Version should not be lockable: Version.lock(true,false) did not throw a LockException"); } catch (LockException success) { } try { lockManager.lock(path, false, true, 60, ""); fail("Version should not be lockable: Version.lock(false,true) did not throw a LockException"); } catch (LockException success) { } try { lockManager.lock(path, false, false, 60, ""); fail("Version should not be lockable: Version.lock(false,false) did not throw a LockException"); } catch (LockException success) { } } /** * Tests if <code>Version.merge(String)</code> throws an * {@link javax.jcr.nodetype.ConstraintViolationException} */ public void testMerge() throws Exception { try { version.merge(workspaceName, true); fail("Version.merge(String, true) did not throw an ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.merge(workspaceName, false); fail("Version.merge(String, false) did not throw an ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.merge(String)</code> throws an * {@link javax.jcr.nodetype.ConstraintViolationException} */ /* TODO: check why this fails public void testMergeJcr2() throws Exception { try { versionManager.merge(version.getPath(), workspaceName, true); fail("Version.merge(String, true) did not throw an ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { versionManager.merge(version.getPath(),workspaceName, false); fail("Version.merge(String, false) did not throw an ConstraintViolationException"); } catch (ConstraintViolationException success) { } } */ /** * Tests if <code>Version.orderBefore(String, String)</code> throws an * {@link javax.jcr.UnsupportedRepositoryOperationException} */ public void testOrderBefore() throws Exception { try { version.orderBefore(jcrFrozenNode, null); fail("Version.orderBefore(String,String) did not throw an UnsupportedRepositoryOperationException or a ConstraintViolationException"); } catch (UnsupportedRepositoryOperationException success) { } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.refresh(boolean)</code> works as expected (do * nothing and return quietly) */ public void testRefresh() throws Exception { // should do nothing and return quietly version.refresh(true); version.refresh(false); } /** * Tests if <code>Version.remove()</code> throws an {@link * javax.jcr.nodetype.ConstraintViolationException} */ public void testRemove() throws Exception { try { version.remove(); versionableNode.getSession().save(); fail("Version should be read-only: Version.remove() did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.removeMixin(String)</code> throws an {@link * javax.jcr.nodetype.ConstraintViolationException} */ public void testRemoveMixin() throws Exception { try { version.removeMixin(mixVersionable); fail("Version should be read-only: Version.removeMixin(String) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.restore(String, boolean)</code> and * <code>Version.restore(Version, boolean)</code> throw an * {@link UnsupportedRepositoryOperationException} and * <code>Version.restore(Version, String, boolean)</code> throws a * {@link ConstraintViolationException}. */ public void testRestore() throws Exception { try { version.restore("abc", true); fail("Version.restore(String,boolean) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } try { version.restore(version2, true); fail("Version.restore(Version,boolean) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } try { version.restore(version2, "abc", true); fail("Version.restore(Version,String,boolean) did not throw an ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.restore(String, boolean)</code> and * <code>Version.restore(Version, boolean)</code> throw an * {@link UnsupportedRepositoryOperationException} and * <code>Version.restore(Version, String, boolean)</code> throws a * {@link ConstraintViolationException}. */ public void testRestoreJcr2() throws Exception { try { versionManager.restore(version.getPath(), "abc", true); fail("Version.restore(String,boolean) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.restoreByLabel(String, boolean)</code> throws an * {@link javax.jcr.UnsupportedRepositoryOperationException} */ public void testRestoreByLabel() throws Exception { try { version.restoreByLabel("abc", true); fail("Version.restoreByLabel(String,boolean) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if <code>Version.restoreByLabel(String, boolean)</code> throws an * {@link javax.jcr.UnsupportedRepositoryOperationException} */ public void testRestoreByLabelJcr2() throws Exception { try { versionManager.restoreByLabel(version.getPath(), "abc", true); fail("Version.restoreByLabel(String,boolean) did not throw an UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException success) { } } /** * Tests if * <ul> <li><code>Version.setProperty(String, String[])</code></li> * <li><code>Version.setProperty(String, String[], int)</code></li> * <li><code>Version.setProperty(String, Value[])</code></li> * <li><code>Version.setProperty(String, Value[], int)</code></li> * <li><code>Version.setProperty(String, boolean)</code></li> * <li><code>Version.setProperty(String, double)</code></li> * <li><code>Version.setProperty(String, InputStream)</code></li> * <li><code>Version.setProperty(String, String)</code></li> * <li><code>Version.setProperty(String, Calendar)</code></li> * <li><code>Version.setProperty(String, Node)</code></li> * <li><code>Version.setProperty(String, Value)</code></li> * <li><code>Version.setProperty(String, long)</code></li> * </ul> all throw a * {@link javax.jcr.nodetype.ConstraintViolationException} */ public void testSetProperty() throws Exception { // create Value[] object Value[] vArray = new Value[3]; vArray[0] = superuser.getValueFactory().createValue("abc"); vArray[1] = superuser.getValueFactory().createValue("xyz"); vArray[2] = superuser.getValueFactory().createValue("123"); // create String array String[] s = {"abc", "xyz", "123"}; try { version.setProperty(propertyName1, s); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,String[]) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, s, PropertyType.STRING); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,String[],int) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, vArray); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,Value[]) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, vArray, PropertyType.STRING); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,Value[],int]) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, true); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,boolean) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, 123); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,double) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { byte[] bytes = {73, 26, 32, -36, 40, -43, -124}; InputStream inpStream = new ByteArrayInputStream(bytes); version.setProperty(propertyName1, inpStream); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,InputStream) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, "abc"); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,String) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { Calendar c = new GregorianCalendar(1945, 1, 6, 16, 20, 0); version.setProperty(propertyName1, c); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,Calendar) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, version); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,Node) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { Value v = superuser.getValueFactory().createValue("abc"); version.setProperty(propertyName1, v); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,Value) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } try { version.setProperty(propertyName1, -2147483650L); version.getSession().save(); fail("Version should be read-only: Version.setProperty(String,long) did not throw a ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if <code>Version.unlock()</code> throws a {@link * javax.jcr.lock.LockException} */ public void testUnlock() throws Exception { try { version.unlock(); fail("Version should not be lockable: Version.unlock() did not throw a LockException"); } catch (LockException success) { } catch (UnsupportedRepositoryOperationException maybe) { assertFalse(isSupported(Repository.OPTION_LOCKING_SUPPORTED)); } } /** * Tests if <code>Version.unlock()</code> throws a {@link * javax.jcr.lock.LockException} */ public void testUnlockJcr2() throws Exception { ensureLockingSupported(); try { version.getSession().getWorkspace().getLockManager().unlock(version.getPath()); fail("Version should not be lockable: Version.unlock() did not throw a LockException"); } catch (LockException success) { } } /** * Tests if <code>VersionHistory.update(String)</code> throws an * {@link javax.jcr.nodetype.ConstraintViolationException} */ public void testUpdate() throws Exception { try { version.update(workspaceName); fail("VersionHistory.update(String) did not throw an ConstraintViolationException"); } catch (ConstraintViolationException success) { } } /** * Tests if the jcr:frozenUuid property has the correct type * @throws Exception */ public void testFrozenUUID() throws Exception { Property p = version.getNode(jcrFrozenNode).getProperty(jcrFrozenUuid); assertEquals("jcr:fronzenUuid should be of type string", PropertyType.TYPENAME_STRING, PropertyType.nameFromValue(p.getType())); } }
google/error-prone
35,972
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/SuggesterTest.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.inlineme; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugCheckerRefactoringTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for the {@link Suggester}. */ @RunWith(JUnit4.class) public class SuggesterTest { private final BugCheckerRefactoringTestHelper refactoringTestHelper = BugCheckerRefactoringTestHelper.newInstance(Suggester.class, getClass()); @Test public void buildAnnotation_withImports() { assertThat( InlineMeData.buildAnnotation( "REPLACEMENT", ImmutableSet.of("java.time.Duration", "java.time.Instant"), ImmutableSet.of())) .isEqualTo( "@InlineMe(replacement = \"REPLACEMENT\", " + "imports = {\"java.time.Duration\", \"java.time.Instant\"})\n"); } @Test public void buildAnnotation_withSingleImport() { assertThat( InlineMeData.buildAnnotation( "REPLACEMENT", ImmutableSet.of("java.time.Duration"), ImmutableSet.of())) .isEqualTo( "@InlineMe(replacement = \"REPLACEMENT\", " + "imports = \"java.time.Duration\")\n"); } @Test public void instanceMethodNewImport() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { private Duration deadline = Duration.ofSeconds(5); @Deprecated public void setDeadline(long millis) { setDeadline(Duration.ofMillis(millis)); } public void setDeadline(Duration deadline) { this.deadline = deadline; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client { private Duration deadline = Duration.ofSeconds(5); @InlineMe( replacement = "this.setDeadline(Duration.ofMillis(millis))", imports = "java.time.Duration") @Deprecated public void setDeadline(long millis) { setDeadline(Duration.ofMillis(millis)); } public void setDeadline(Duration deadline) { this.deadline = deadline; } } """) .doTest(); } @Test public void staticMethodInNewClass() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { @Deprecated public Duration fromMillis(long millis) { return Duration.ofMillis(millis); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client { @InlineMe(replacement = "Duration.ofMillis(millis)", imports = "java.time.Duration") @Deprecated public Duration fromMillis(long millis) { return Duration.ofMillis(millis); } } """) .doTest(); } @Test public void unqualifiedStaticFieldReference() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { public static final String STR = "kurt"; @Deprecated public int stringLength() { return STR.length(); } } """) .addOutputLines( "Client.java", "package com.google.frobber;", "import com.google.errorprone.annotations.InlineMe;", "public final class Client {", " public static final String STR = \"kurt\";", // TODO(b/234643232): this is a bug; it should be "Client.STR.length()" plus an import " @InlineMe(replacement = \"STR.length()\")", " @Deprecated", " public int stringLength() {", " return STR.length();", " }", "}") .doTest(); } @Test public void qualifiedStaticFieldReference() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { public static final String STR = "kurt"; @Deprecated public int stringLength() { return Client.STR.length(); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; public final class Client { public static final String STR = "kurt"; @InlineMe(replacement = "Client.STR.length()", imports = "com.google.frobber.Client") @Deprecated public int stringLength() { return Client.STR.length(); } } """) .doTest(); } @Test public void protectedConstructor() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { @Deprecated protected Client() {} } """) .expectUnchanged() .doTest(); } @Test public void returnField() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { @Deprecated public Duration getZero() { return Duration.ZERO; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client { @InlineMe(replacement = "Duration.ZERO", imports = "java.time.Duration") @Deprecated public Duration getZero() { return Duration.ZERO; } } """) .doTest(); } @Test public void implementationSplitOverMultipleLines() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; import java.time.Instant; public final class Client { @Deprecated public Duration getElapsed() { return Duration.between(Instant.ofEpochMilli(42), Instant.now()); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; import java.time.Instant; public final class Client { @InlineMe( replacement = "Duration.between(Instant.ofEpochMilli(42), Instant.now())", imports = {"java.time.Duration", "java.time.Instant"}) @Deprecated public Duration getElapsed() { return Duration.between(Instant.ofEpochMilli(42), Instant.now()); } } """) .doTest(); } @Test public void anonymousClass() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { @Deprecated public Object getUselessObject() { return new Object() { @Override public int hashCode() { return 42; } }; } } """) .expectUnchanged() .doTest(); } @Test public void methodReference() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; import java.util.Optional; public final class Client { @Deprecated public Optional<Duration> silly(Optional<Long> input) { return input.map(Duration::ofMillis); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; import java.util.Optional; public final class Client { @InlineMe(replacement = "input.map(Duration::ofMillis)", imports = "java.time.Duration") @Deprecated public Optional<Duration> silly(Optional<Long> input) { return input.map(Duration::ofMillis); } } """) .doTest(); } @Test public void newClass() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import org.joda.time.Instant; public final class Client { @Deprecated public Instant silly() { return new Instant(); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import org.joda.time.Instant; public final class Client { @InlineMe(replacement = "new Instant()", imports = "org.joda.time.Instant") @Deprecated public Instant silly() { return new Instant(); } } """) .doTest(); } @Test public void newArray() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import org.joda.time.Instant; public final class Client { @Deprecated public Instant[] silly() { return new Instant[42]; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import org.joda.time.Instant; public final class Client { @InlineMe(replacement = "new Instant[42]", imports = "org.joda.time.Instant") @Deprecated public Instant[] silly() { return new Instant[42]; } } """) .doTest(); } @Test public void newNestedClass() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { @Deprecated public NestedClass silly() { return new NestedClass(); } public static class NestedClass {} } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; public final class Client { @InlineMe(replacement = "new NestedClass()", imports = "com.google.frobber.Client.NestedClass") @Deprecated public NestedClass silly() { return new NestedClass(); } public static class NestedClass {} } """) .doTest(); } @Test public void returnStringLiteral() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { @Deprecated public String getName() { return "kurt"; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; public final class Client { @InlineMe(replacement = "\\"kurt\\"") @Deprecated public String getName() { return "kurt"; } } """) .doTest(); } @Test public void callMethodWithStringLiteral() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { @Deprecated public String getName() { return getName("kurt"); } public String getName(String defaultValue) { return "test"; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; public final class Client { @InlineMe(replacement = "this.getName(\\"kurt\\")") @Deprecated public String getName() { return getName("kurt"); } public String getName(String defaultValue) { return "test"; } } """) .doTest(); } @Test public void returnPrivateVariable() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { private final Duration myDuration = Duration.ZERO; @Deprecated public Duration getMyDuration() { return myDuration; } } """) .expectUnchanged() .doTest(); } @Test public void returnPrivateVariable_qualifiedWithThis() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { private final Duration myDuration = Duration.ZERO; @Deprecated public Duration getMyDuration() { return this.myDuration; } } """) .expectUnchanged() .doTest(); } @Test public void settingPrivateVariable() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { private Duration duration = Duration.ZERO; @Deprecated public void setDuration(Duration duration) { this.duration = duration; } } """) .expectUnchanged() .doTest(); } @Test public void delegateToParentClass() { refactoringTestHelper .addInputLines( "Parent.java", """ package com.google.frobber; import java.time.Duration; public class Parent { private Duration duration = Duration.ZERO; public final Duration after() { return duration; } } """) .expectUnchanged() .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client extends Parent { private Duration duration = Duration.ZERO; @Deprecated public final Duration before() { return after(); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client extends Parent { private Duration duration = Duration.ZERO; @InlineMe(replacement = "this.after()") @Deprecated public final Duration before() { return after(); } } """) .doTest(); } @Test public void withCast() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { @Deprecated public void setDuration(Object duration) { foo((Duration) duration); } public void foo(Duration duration) {} } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client { @InlineMe(replacement = "this.foo((Duration) duration)", imports = "java.time.Duration") @Deprecated public void setDuration(Object duration) { foo((Duration) duration); } public void foo(Duration duration) {} } """) .doTest(); } @Test public void accessPrivateVariable() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { private final Duration myDuration = Duration.ZERO; @Deprecated public boolean silly() { return myDuration.isZero(); } } """) .expectUnchanged() .doTest(); } @Test public void accessPrivateMethod() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public final class Client { @Deprecated public boolean silly() { return privateDelegate(); } private boolean privateDelegate() { return false; } } """) .expectUnchanged() .doTest(); } @Test public void tryWithResources() { refactoringTestHelper .addInputLines( "Client.java", """ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Client { @Deprecated public String readLine(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } } """) .expectUnchanged() .doTest(); } @Test public void ifStatement() { refactoringTestHelper .addInputLines( "Client.java", """ public class Client { @Deprecated public void foo(String input) { if (input.equals("hi")) { return; } } } """) .expectUnchanged() .doTest(); } @Test public void nestedBlock() { refactoringTestHelper .addInputLines( "Client.java", """ public class Client { @Deprecated public String foo(String input) { { return input.toLowerCase(); } } } """) .expectUnchanged() .doTest(); } @Test public void ternaryOverMultipleLines() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { @Deprecated public Duration getDeadline(Duration deadline) { return (deadline.compareTo(Duration.ZERO) > 0 ? Duration.ofSeconds(42) : Duration.ZERO); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client { @InlineMe( replacement = "(deadline.compareTo(Duration.ZERO) > 0 ? Duration.ofSeconds(42) : Duration.ZERO)", imports = "java.time.Duration") @Deprecated public Duration getDeadline(Duration deadline) { return (deadline.compareTo(Duration.ZERO) > 0 ? Duration.ofSeconds(42) : Duration.ZERO); } } """) .doTest(); } @Test public void staticCallingAnotherQualifiedStatic() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.time.Duration; public final class Client { @Deprecated public static Duration getDeadline() { return Client.getDeadline2(); } public static Duration getDeadline2() { return Duration.ZERO; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final class Client { @InlineMe(replacement = "Client.getDeadline2()", imports = "com.google.frobber.Client") @Deprecated public static Duration getDeadline() { return Client.getDeadline2(); } public static Duration getDeadline2() { return Duration.ZERO; } } """) .doTest(); } @Test public void staticReferenceToJavaLang() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import static java.lang.String.format; public final class Client { @Deprecated public static String myFormat(String template, String arg) { return format(template, arg); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import static java.lang.String.format; import com.google.errorprone.annotations.InlineMe; public final class Client { @InlineMe(replacement = "format(template, arg)", staticImports = "java.lang.String.format") @Deprecated public static String myFormat(String template, String arg) { return format(template, arg); } } """) .doTest(); } @Test public void replacementContainsGenericInvocation() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.util.ArrayList; import java.util.List; public final class Client { @Deprecated public static List<Void> newArrayList() { return new ArrayList<Void>(); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.util.ArrayList; import java.util.List; public final class Client { @InlineMe(replacement = "new ArrayList<Void>()", imports = "java.util.ArrayList") @Deprecated public static List<Void> newArrayList() { return new ArrayList<Void>(); } } """) .doTest(); } @Test public void suggestedFinalOnOtherwiseGoodMethod() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public class Client { @Deprecated public int method() { return 42; } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; public class Client { @InlineMe(replacement = "42") @Deprecated public final int method() { return 42; } } """) .doTest(); } @Test public void dontSuggestOnDefaultMethods() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public interface Client { @Deprecated public default int method() { return 42; } } """) .expectUnchanged() .doTest(); } // Since constructors can't be "overridden" in the same way as other non-final methods, it's // OK to inline them even if there could be a subclass of the surrounding class. @Test public void deprecatedConstructorInNonFinalClass() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public class Client { @Deprecated public Client() { this(42); } public Client(int value) {} } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; public class Client { @InlineMe(replacement = "this(42)") @Deprecated public Client() { this(42); } public Client(int value) {} } """) .doTest(); } @Test public void publicStaticFactoryCallsPrivateConstructor() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; public class Client { @Deprecated public static Client create() { return new Client(); } private Client() {} } """) .expectUnchanged() .doTest(); } @Test public void deprecatedMethodWithDoNotCall() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.DoNotCall; public class Client { @DoNotCall @Deprecated public void before() { after(); } public void after() {} } """) .expectUnchanged() .doTest(); } @Test public void implementationUsingPublicStaticField() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.frobber; import java.util.function.Supplier; public class Client { public static final Supplier<Integer> MAGIC = () -> 42; @Deprecated public static int before() { return after(MAGIC.get()); } public static int after(int value) { return value; } } """) // TODO(b/202145711): MAGIC.get() should be Client.MAGIC.get() .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.util.function.Supplier; public class Client { public static final Supplier<Integer> MAGIC = () -> 42; @InlineMe(replacement = "Client.after(MAGIC.get())", imports = "com.google.frobber.Client") @Deprecated public static int before() { return after(MAGIC.get()); } public static int after(int value) { return value; } } """) .doTest(); } @Test public void apisLikelyUsedReflectively() { refactoringTestHelper .addInputLines( "Test.java", """ import com.google.errorprone.annotations.Keep; import com.google.inject.Provides; import java.time.Duration; import java.util.Optional; public class Test { @Deprecated @Provides public Optional<Duration> provides(Optional<Long> input) { return input.map(Duration::ofMillis); } @Deprecated @Keep public Optional<Duration> reflective(Optional<Long> input) { return input.map(Duration::ofMillis); } } """) .expectUnchanged() .doTest(); } @Test public void importStatic_getsCorrectlySuggestedAsStaticImports() { refactoringTestHelper .addInputLines( "KeymasterEncrypter.java", """ package com.google.security.keymaster; import static java.nio.charset.StandardCharsets.US_ASCII; import com.google.errorprone.annotations.InlineMe; public final class KeymasterEncrypter { @Deprecated public final byte[] encryptASCII(String plaintext) { return encrypt(plaintext.getBytes(US_ASCII)); } public byte[] encrypt(byte[] plaintext) { return plaintext; } } """) .addOutputLines( "KeymasterEncrypter.java", """ package com.google.security.keymaster; import static java.nio.charset.StandardCharsets.US_ASCII; import com.google.errorprone.annotations.InlineMe; public final class KeymasterEncrypter { @InlineMe( replacement = "this.encrypt(plaintext.getBytes(US_ASCII))", staticImports = "java.nio.charset.StandardCharsets.US_ASCII") @Deprecated public final byte[] encryptASCII(String plaintext) { return encrypt(plaintext.getBytes(US_ASCII)); } public byte[] encrypt(byte[] plaintext) { return plaintext; } } """) .doTest(); } @Test public void importStatic_getsIncorrectlySuggestedAsImportsInsteadOfStaticImports() { refactoringTestHelper .addInputLines( "KeymasterCrypter.java", """ package com.google.security.keymaster; import static java.nio.charset.StandardCharsets.US_ASCII; import com.google.errorprone.annotations.InlineMe; public final class KeymasterCrypter { @Deprecated public final String decryptASCII(byte[] ciphertext) { return new String(decrypt(ciphertext), US_ASCII); } public byte[] decrypt(byte[] ciphertext) { return ciphertext; } } """) .addOutputLines( "KeymasterCrypter.java", "package com.google.security.keymaster;", "import static java.nio.charset.StandardCharsets.US_ASCII;", "import com.google.errorprone.annotations.InlineMe;", "public final class KeymasterCrypter {", // TODO(b/242890437): This line is wrong: " @InlineMe(replacement = \"new String(this.decrypt(ciphertext), US_ASCII)\", imports" + " = \"US_ASCII\")", // It should be this instead: // " @InlineMe(", // " replacement = \"new String(this.decrypt(ciphertext), US_ASCII)\",", // " staticImports =\"java.nio.charset.StandardCharsets.US_ASCII\")", " @Deprecated", " public final String decryptASCII(byte[] ciphertext) {", " return new String(decrypt(ciphertext), US_ASCII);", " }", " public byte[] decrypt(byte[] ciphertext) {", " return ciphertext;", " }", "}") .doTest(); } @Test public void noInlineMeSuggestionWhenParameterNamesAreArgN() { refactoringTestHelper .addInputLines( "Client.java", """ public final class Client { @Deprecated public void before(int arg0, int arg1) { after(arg0, arg1); } public void after(int arg0, int arg1) {} } """) .expectUnchanged() .doTest(); } @Test public void inlineMeSuggestionWhenParameterNamesAreNotArgN() { refactoringTestHelper .addInputLines( "Client.java", """ public final class Client { @Deprecated public void before(int int0, int int1) { after(int0, int1); } public void after(int int0, int int1) {} } """) .addOutputLines( "Client.java", """ import com.google.errorprone.annotations.InlineMe; public final class Client { @InlineMe(replacement = "this.after(int0, int1)") @Deprecated public void before(int int0, int int1) { after(int0, int1); } public void after(int int0, int int1) {} } """) .doTest(); } @Test public void deprecatedConstructorSuperCall() { refactoringTestHelper .addInputLines( "ExecutionError.java", """ public final class ExecutionError extends Error { @Deprecated public ExecutionError(String message) { super(message); } } """) .expectUnchanged() .doTest(); } }
googleapis/google-cloud-java
36,887
java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/ListLocationsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1beta1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1beta1; /** * * * <pre> * ListLocationsResponse returns the list of all GKE locations and their * recommendation state. * </pre> * * Protobuf type {@code google.container.v1beta1.ListLocationsResponse} */ public final class ListLocationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1beta1.ListLocationsResponse) ListLocationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListLocationsResponse.newBuilder() to construct. private ListLocationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListLocationsResponse() { locations_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListLocationsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListLocationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.ListLocationsResponse.class, com.google.container.v1beta1.ListLocationsResponse.Builder.class); } public static final int LOCATIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.container.v1beta1.Location> locations_; /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ @java.lang.Override public java.util.List<com.google.container.v1beta1.Location> getLocationsList() { return locations_; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.container.v1beta1.LocationOrBuilder> getLocationsOrBuilderList() { return locations_; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ @java.lang.Override public int getLocationsCount() { return locations_.size(); } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ @java.lang.Override public com.google.container.v1beta1.Location getLocations(int index) { return locations_.get(index); } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ @java.lang.Override public com.google.container.v1beta1.LocationOrBuilder getLocationsOrBuilder(int index) { return locations_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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 < locations_.size(); i++) { output.writeMessage(1, locations_.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 < locations_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, locations_.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.container.v1beta1.ListLocationsResponse)) { return super.equals(obj); } com.google.container.v1beta1.ListLocationsResponse other = (com.google.container.v1beta1.ListLocationsResponse) obj; if (!getLocationsList().equals(other.getLocationsList())) 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 (getLocationsCount() > 0) { hash = (37 * hash) + LOCATIONS_FIELD_NUMBER; hash = (53 * hash) + getLocationsList().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.container.v1beta1.ListLocationsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.ListLocationsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1beta1.ListLocationsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.ListLocationsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1beta1.ListLocationsResponse 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> * ListLocationsResponse returns the list of all GKE locations and their * recommendation state. * </pre> * * Protobuf type {@code google.container.v1beta1.ListLocationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1beta1.ListLocationsResponse) com.google.container.v1beta1.ListLocationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListLocationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.ListLocationsResponse.class, com.google.container.v1beta1.ListLocationsResponse.Builder.class); } // Construct using com.google.container.v1beta1.ListLocationsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (locationsBuilder_ == null) { locations_ = java.util.Collections.emptyList(); } else { locations_ = null; locationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListLocationsResponse_descriptor; } @java.lang.Override public com.google.container.v1beta1.ListLocationsResponse getDefaultInstanceForType() { return com.google.container.v1beta1.ListLocationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.container.v1beta1.ListLocationsResponse build() { com.google.container.v1beta1.ListLocationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1beta1.ListLocationsResponse buildPartial() { com.google.container.v1beta1.ListLocationsResponse result = new com.google.container.v1beta1.ListLocationsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.container.v1beta1.ListLocationsResponse result) { if (locationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { locations_ = java.util.Collections.unmodifiableList(locations_); bitField0_ = (bitField0_ & ~0x00000001); } result.locations_ = locations_; } else { result.locations_ = locationsBuilder_.build(); } } private void buildPartial0(com.google.container.v1beta1.ListLocationsResponse 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.container.v1beta1.ListLocationsResponse) { return mergeFrom((com.google.container.v1beta1.ListLocationsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1beta1.ListLocationsResponse other) { if (other == com.google.container.v1beta1.ListLocationsResponse.getDefaultInstance()) return this; if (locationsBuilder_ == null) { if (!other.locations_.isEmpty()) { if (locations_.isEmpty()) { locations_ = other.locations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureLocationsIsMutable(); locations_.addAll(other.locations_); } onChanged(); } } else { if (!other.locations_.isEmpty()) { if (locationsBuilder_.isEmpty()) { locationsBuilder_.dispose(); locationsBuilder_ = null; locations_ = other.locations_; bitField0_ = (bitField0_ & ~0x00000001); locationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getLocationsFieldBuilder() : null; } else { locationsBuilder_.addAllMessages(other.locations_); } } } 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.container.v1beta1.Location m = input.readMessage( com.google.container.v1beta1.Location.parser(), extensionRegistry); if (locationsBuilder_ == null) { ensureLocationsIsMutable(); locations_.add(m); } else { locationsBuilder_.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.container.v1beta1.Location> locations_ = java.util.Collections.emptyList(); private void ensureLocationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { locations_ = new java.util.ArrayList<com.google.container.v1beta1.Location>(locations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1beta1.Location, com.google.container.v1beta1.Location.Builder, com.google.container.v1beta1.LocationOrBuilder> locationsBuilder_; /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public java.util.List<com.google.container.v1beta1.Location> getLocationsList() { if (locationsBuilder_ == null) { return java.util.Collections.unmodifiableList(locations_); } else { return locationsBuilder_.getMessageList(); } } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public int getLocationsCount() { if (locationsBuilder_ == null) { return locations_.size(); } else { return locationsBuilder_.getCount(); } } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public com.google.container.v1beta1.Location getLocations(int index) { if (locationsBuilder_ == null) { return locations_.get(index); } else { return locationsBuilder_.getMessage(index); } } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder setLocations(int index, com.google.container.v1beta1.Location value) { if (locationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocationsIsMutable(); locations_.set(index, value); onChanged(); } else { locationsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder setLocations( int index, com.google.container.v1beta1.Location.Builder builderForValue) { if (locationsBuilder_ == null) { ensureLocationsIsMutable(); locations_.set(index, builderForValue.build()); onChanged(); } else { locationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder addLocations(com.google.container.v1beta1.Location value) { if (locationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocationsIsMutable(); locations_.add(value); onChanged(); } else { locationsBuilder_.addMessage(value); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder addLocations(int index, com.google.container.v1beta1.Location value) { if (locationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocationsIsMutable(); locations_.add(index, value); onChanged(); } else { locationsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder addLocations(com.google.container.v1beta1.Location.Builder builderForValue) { if (locationsBuilder_ == null) { ensureLocationsIsMutable(); locations_.add(builderForValue.build()); onChanged(); } else { locationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder addLocations( int index, com.google.container.v1beta1.Location.Builder builderForValue) { if (locationsBuilder_ == null) { ensureLocationsIsMutable(); locations_.add(index, builderForValue.build()); onChanged(); } else { locationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder addAllLocations( java.lang.Iterable<? extends com.google.container.v1beta1.Location> values) { if (locationsBuilder_ == null) { ensureLocationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, locations_); onChanged(); } else { locationsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder clearLocations() { if (locationsBuilder_ == null) { locations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { locationsBuilder_.clear(); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public Builder removeLocations(int index) { if (locationsBuilder_ == null) { ensureLocationsIsMutable(); locations_.remove(index); onChanged(); } else { locationsBuilder_.remove(index); } return this; } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public com.google.container.v1beta1.Location.Builder getLocationsBuilder(int index) { return getLocationsFieldBuilder().getBuilder(index); } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public com.google.container.v1beta1.LocationOrBuilder getLocationsOrBuilder(int index) { if (locationsBuilder_ == null) { return locations_.get(index); } else { return locationsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public java.util.List<? extends com.google.container.v1beta1.LocationOrBuilder> getLocationsOrBuilderList() { if (locationsBuilder_ != null) { return locationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(locations_); } } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public com.google.container.v1beta1.Location.Builder addLocationsBuilder() { return getLocationsFieldBuilder() .addBuilder(com.google.container.v1beta1.Location.getDefaultInstance()); } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public com.google.container.v1beta1.Location.Builder addLocationsBuilder(int index) { return getLocationsFieldBuilder() .addBuilder(index, com.google.container.v1beta1.Location.getDefaultInstance()); } /** * * * <pre> * A full list of GKE locations. * </pre> * * <code>repeated .google.container.v1beta1.Location locations = 1;</code> */ public java.util.List<com.google.container.v1beta1.Location.Builder> getLocationsBuilderList() { return getLocationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1beta1.Location, com.google.container.v1beta1.Location.Builder, com.google.container.v1beta1.LocationOrBuilder> getLocationsFieldBuilder() { if (locationsBuilder_ == null) { locationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1beta1.Location, com.google.container.v1beta1.Location.Builder, com.google.container.v1beta1.LocationOrBuilder>( locations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); locations_ = null; } return locationsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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> * Only return ListLocationsResponse that occur after the page_token. This * value should be populated from the ListLocationsResponse.next_page_token if * that response token was set (which happens when listing more Locations than * fit in a single ListLocationsResponse). * </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.container.v1beta1.ListLocationsResponse) } // @@protoc_insertion_point(class_scope:google.container.v1beta1.ListLocationsResponse) private static final com.google.container.v1beta1.ListLocationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1beta1.ListLocationsResponse(); } public static com.google.container.v1beta1.ListLocationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListLocationsResponse> PARSER = new com.google.protobuf.AbstractParser<ListLocationsResponse>() { @java.lang.Override public ListLocationsResponse 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<ListLocationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListLocationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1beta1.ListLocationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/directory-server
36,805
core-avl/src/main/java/org/apache/directory/server/core/avltree/ArrayTree.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.server.core.avltree; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * A data structure simulating a tree (ie, a sorted list of elements) using an array. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ArrayTree<K> { /** The Comparator used for comparing the keys */ private Comparator<K> comparator; /** The array containing the data */ private K[] array; /** The current number of elements in the array. May be lower than the array size */ private int size; /** The extend size to use when increasing the array size */ private static final int INCREMENT = 16; /** * Creates a new instance of AVLTree. * * @param comparator the comparator to be used for comparing keys */ public ArrayTree( Comparator<K> comparator ) { this.comparator = comparator; array = ( K[] ) new Object[INCREMENT]; size = 0; } /** * Creates a new instance of AVLTree. * * @param comparator the comparator to be used for comparing keys * @param array The array of keys */ public ArrayTree( Comparator<K> comparator, K[] array ) { this.comparator = comparator; if ( array != null ) { size = array.length; int arraySize = size; if ( size % INCREMENT != 0 ) { arraySize += INCREMENT - size % INCREMENT; } this.array = ( K[] ) new Object[arraySize]; System.arraycopy( array, 0, this.array, 0, size ); } } /** * @return the comparator associated with this tree */ public Comparator<K> getComparator() { return comparator; } /** * Inserts a key. Null value insertion is not allowed. * * @param key the item to be inserted, should not be null * @return the replaced key if it already exists * Note: Ignores if the given key already exists. */ public K insert( K key ) { if ( key == null ) { // We don't allow null values in the tree return null; } // Check if the key already exists, and if so, return the // existing one K existing = find( key ); if ( existing != null ) { return existing; } if ( size == array.length ) { // The array is full, let's extend it K[] newArray = ( K[] ) new Object[size + INCREMENT]; System.arraycopy( array, 0, newArray, 0, size ); array = newArray; } // Currently, just add the element at the end of the array // and sort the array. We could be more efficient by inserting the // element at the right position by splitting the array in two // parts and copying the right part one slot on the right. array[size++] = key; Arrays.sort( array, 0, size, comparator ); return null; } /**q< * Reduce the array size if neede */ private void reduceArray() { // We will reduce the array size when the number of elements // in it is leaving twice the number of INCREMENT empty slots. // We then remove INCREMENT slots if ( ( array.length - size ) > ( INCREMENT << 1 ) ) { K[] newArray = ( K[] ) new Object[array.length - INCREMENT]; System.arraycopy( array, 0, newArray, 0, array.length ); } } /** * Removes a key present in the tree * * @param key the value to be removed * @return the removed key, if any, or null if the key does not exist */ public K remove( K key ) { // Search for the key position in the tree int pos = getPosition( key ); if ( pos != -1 ) { // Found... if ( pos != size - 1 ) { // If the element is not the last one, we have to // move the end of the array one step to the left System.arraycopy( array, pos + 1, array, pos, size - pos - 1 ); reduceArray(); } size--; return key; } else { return null; } } /** * Tests if the tree is empty. * * @return true if the tree is empty, false otherwise */ public boolean isEmpty() { return size == 0; } /** * returns the number of nodes present in this tree. * * @return the number of nodes present in this tree */ public int size() { return size; } /** * @return a list of the stored keys in this tree */ public List<K> getKeys() { List<K> list = new ArrayList<>( size ); for ( int i = 0; i < size; i++ ) { list.add( array[i] ); } return list; } /** * Prints the contents of AVL tree in pretty format */ public void printTree() { if ( isEmpty() ) { System.out.println( "Tree is empty" ); return; } boolean isFirst = true; for ( K key : array ) { if ( isFirst ) { isFirst = false; } else { System.out.print( ", " ); } System.out.println( key ); } } /** * Get the element at a given position * @param position The position in the tree * @return The found key, or null if the position is out of scope */ public K get( int position ) { if ( ( position < 0 ) || ( position >= size ) ) { throw new ArrayIndexOutOfBoundsException(); } return array[position]; } /** * Get the first element in the tree. It sets the current position to this * element. * @return The first element of this tree */ public K getFirst() { if ( size != 0 ) { return array[0]; } else { return null; } } /** * Get the last element in the tree. It sets the current position to this * element. * @return The last element in this tree */ public K getLast() { if ( size != 0 ) { return array[size - 1]; } else { return null; } } /** * Finds a key higher than the given key. Sets the current position to this * element. * * @param key the key to find * @return the LinkedAvlNode whose key is greater than the given key ,<br> * null if there is no node with a higher key than the given key. */ public K findGreater( K key ) { if ( key == null ) { return null; } switch ( size ) { case 0: return null; case 1: if ( comparator.compare( array[0], key ) > 0 ) { return array[0]; } else { return null; } case 2: if ( comparator.compare( array[0], key ) > 0 ) { return array[0]; } else if ( comparator.compare( array[1], key ) > 0 ) { return array[1]; } else { return null; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { // Current can't be equal to zero at this point return array[current + 1]; } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: int res = comparator.compare( array[start], key ); if ( res <= 0 ) { if ( start == size ) { return null; } else { return array[start + 1]; } } return array[start]; case 2: res = comparator.compare( array[start], key ); if ( res <= 0 ) { res = comparator.compare( array[start + 1], key ); if ( res <= 0 ) { if ( start == size - 2 ) { return null; } return array[start + 2]; } return array[start + 1]; } return array[start]; default: return null; } } } /** * Finds a key higher than the given key. * * @param key the key * @return the key chich is greater than the given key ,<br> * null if there is no higher key than the given key. */ public K findGreaterOrEqual( K key ) { if ( key == null ) { return null; } switch ( size ) { case 0: return null; case 1: if ( comparator.compare( array[0], key ) >= 0 ) { return array[0]; } else { return null; } case 2: if ( comparator.compare( array[0], key ) >= 0 ) { return array[0]; } else if ( comparator.compare( array[1], key ) >= 0 ) { return array[1]; } else { return null; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { return array[current]; } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: int res = comparator.compare( array[start], key ); if ( res >= 0 ) { return array[start]; } else { if ( start == size - 1 ) { return null; } else { return array[start + 1]; } } case 2: res = comparator.compare( array[start], key ); if ( res < 0 ) { res = comparator.compare( array[start + 1], key ); if ( res < 0 ) { if ( start == size - 2 ) { return null; } return array[start + 2]; } return array[start + 1]; } return array[start]; default: return null; } } } /** * Finds a key which is lower than the given key. * * @param key the key * @return the key lower than the given key ,<br> * null if there is no node with a lower key than the given key. */ public K findLess( K key ) { if ( key == null ) { return null; } switch ( size ) { case 0: return null; case 1: if ( comparator.compare( array[0], key ) >= 0 ) { return null; } else { return array[0]; } case 2: if ( comparator.compare( array[0], key ) >= 0 ) { return null; } else if ( comparator.compare( array[1], key ) >= 0 ) { return array[0]; } else { return array[1]; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { // Current can't be equal to zero at this point return array[current - 1]; } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: // Three cases : // o The value is equal to the current position, or below // the current position : // - if the current position is at the beginning // of the array, return null // - otherwise, return the previous position in the array // o The value is above the current position : // - return the current position int res = comparator.compare( array[start], key ); if ( res >= 0 ) { // start can be equal to 0. Check that if ( start == 1 ) { return null; } else { return array[start - 1]; } } else { return array[start]; } case 2: // Four cases : // o the value is equal the current position, or below // the first position : // - if the current position is at the beginning // of the array, return null // - otherwise, return the previous element // o the value is above the first position but below // or equal the second position, return the first position // o otherwise, return the second position res = comparator.compare( array[start], key ); if ( res >= 0 ) { if ( start == 0 ) { return null; } else { return array[start - 1]; } } else if ( comparator.compare( array[start + 1], key ) >= 0 ) { return array[start]; } else { return array[start + 1]; } default: return null; } } } /** * Finds a key chich is lower than the given key. * * @param key the key * @return the key which is lower than the given key ,<br> * null if there is no node with a lower key than the given key. */ public K findLessOrEqual( K key ) { if ( key == null ) { return null; } switch ( size ) { case 0: return null; case 1: if ( comparator.compare( array[0], key ) <= 0 ) { return array[0]; } else { return null; } case 2: int res = comparator.compare( array[0], key ); if ( res > 0 ) { return null; } else if ( res == 0 ) { return array[0]; } res = comparator.compare( array[1], key ); if ( res == 0 ) { return array[1]; } else if ( comparator.compare( array[1], key ) > 0 ) { return array[0]; } else { return array[1]; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { res = comparator.compare( array[current], key ); if ( res == 0 ) { return array[current]; } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: // Three cases : // o The value is equal to the current position, or below // the current position : // - if the current position is at the beginning // of the array, return null // - otherwise, return the previous position in the array // o The value is above the current position : // - return the current position res = comparator.compare( array[start], key ); if ( res > 0 ) { // start can be equal to 0. Check that if ( start == 1 ) { return null; } else { return array[start - 1]; } } else { return array[start]; } case 2: // Four cases : // o the value is equal the current position, or below // the first position : // - if the current position is at the beginning // of the array, return null // - otherwise, return the previous element // o the value is above the first position but below // or equal the second position, return the first position // o otherwise, return the second position res = comparator.compare( array[start], key ); if ( res > 0 ) { if ( start == 0 ) { return null; } else { return array[start - 1]; } } res = comparator.compare( array[start + 1], key ); if ( res > 0 ) { return array[start]; } else { return array[start + 1]; } default: return null; } } } /** * Find an element in the array. * * @param key the key to find * @return the found node, or null */ public K find( K key ) { if ( key == null ) { return null; } switch ( size ) { case 0: return null; case 1: if ( comparator.compare( array[0], key ) == 0 ) { return array[0]; } else { return null; } case 2: if ( comparator.compare( array[0], key ) == 0 ) { return array[0]; } else if ( comparator.compare( array[1], key ) == 0 ) { return array[1]; } else { return null; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { return array[current]; } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: if ( comparator.compare( array[start], key ) == 0 ) { return array[start]; } else { return null; } case 2: if ( comparator.compare( array[start], key ) == 0 ) { return array[start]; } else if ( comparator.compare( array[end], key ) == 0 ) { return array[end]; } else { return null; } default: return null; } } } /** * Find the element position in the array. * * @param key the key to find * @return the position in the array, or -1 if not found */ public int getPosition( K key ) { if ( key == null ) { return -1; } switch ( size ) { case 0: return -1; case 1: if ( comparator.compare( array[0], key ) == 0 ) { return 0; } else { return -1; } case 2: if ( comparator.compare( array[0], key ) == 0 ) { return 0; } else if ( comparator.compare( array[1], key ) == 0 ) { return 1; } else { return -1; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { return current; } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: if ( comparator.compare( array[start], key ) == 0 ) { return start; } else { return -1; } case 2: if ( comparator.compare( array[start], key ) == 0 ) { return start; } else if ( comparator.compare( array[end], key ) == 0 ) { return end; } else { return -1; } default: return -1; } } } /** * Find the element position in the array, or the position of the closest greater element in the array. * * @param key the key to find * @return the position in the array, or -1 if not found */ public int getAfterPosition( K key ) { if ( key == null ) { return -1; } switch ( size ) { case 0: return -1; case 1: if ( comparator.compare( array[0], key ) > 0 ) { return 0; } else { return -1; } case 2: if ( comparator.compare( array[0], key ) > 0 ) { return 0; } if ( comparator.compare( array[1], key ) > 0 ) { return 1; } else { return -1; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { if ( current != size - 1 ) { return current + 1; } else { return -1; } } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: if ( comparator.compare( array[start], key ) > 0 ) { return start; } else { return -1; } case 2: if ( comparator.compare( array[start], key ) > 0 ) { return start; } if ( comparator.compare( array[end], key ) > 0 ) { return end; } else { return -1; } default: return -1; } } } /** * Find the element position in the array, or the position of the closest greater element in the array. * * @param key the key to find * @return the position in the array, or -1 if not found */ public int getBeforePosition( K key ) { if ( key == null ) { return -1; } switch ( size ) { case 0: return -1; case 1: if ( comparator.compare( array[0], key ) < 0 ) { return 0; } else { return -1; } case 2: if ( comparator.compare( array[1], key ) < 0 ) { return 1; } if ( comparator.compare( array[0], key ) < 0 ) { return 0; } else { return -1; } default: // Split the array in two parts, the left part an the right part int current = size >> 1; int start = 0; int end = size - 1; while ( end - start + 1 > 2 ) { int res = comparator.compare( array[current], key ); if ( res == 0 ) { if ( current == 0 ) { return -1; } else { return current - 1; } } else if ( res < 0 ) { start = current; current = ( current + end + 1 ) >> 1; } else { end = current; current = ( current + start + 1 ) >> 1; } } switch ( end - start + 1 ) { case 1: if ( comparator.compare( array[start], key ) < 0 ) { return start; } else { return -1; } case 2: if ( comparator.compare( array[end], key ) < 0 ) { return end; } if ( comparator.compare( array[start], key ) < 0 ) { return start; } else { return -1; } default: return -1; } } } /** * Tells if a key exist in the array. * * @param key The key to look for * @return true if the key exist in the array */ public boolean contains( K key ) { return find( key ) != null; } /** * {@inheritDoc} */ public String toString() { if ( isEmpty() ) { return "[]"; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( int i = 0; i < size; i++ ) { K key = array[i]; if ( isFirst ) { isFirst = false; } else { sb.append( ", " ); } sb.append( key ); } return sb.toString(); } }
apache/inlong
36,798
inlong-tubemq/tubemq-server/src/main/java/org/apache/inlong/tubemq/server/master/MasterConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.inlong.tubemq.server.master; import org.apache.inlong.tubemq.corebase.TBaseConstants; import org.apache.inlong.tubemq.corebase.config.TLSConfig; import org.apache.inlong.tubemq.corebase.utils.AddressUtils; import org.apache.inlong.tubemq.corebase.utils.MixedUtils; import org.apache.inlong.tubemq.corebase.utils.TStringUtils; import org.apache.inlong.tubemq.corerpc.RpcConstants; import org.apache.inlong.tubemq.server.common.TServerConstants; import org.apache.inlong.tubemq.server.common.fileconfig.AbstractFileConfig; import org.apache.inlong.tubemq.server.common.fileconfig.BdbMetaConfig; import org.apache.inlong.tubemq.server.common.fileconfig.PrometheusConfig; import org.apache.inlong.tubemq.server.common.fileconfig.ZKMetaConfig; import org.apache.commons.lang3.builder.ToStringBuilder; import org.ini4j.Ini; import org.ini4j.Profile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; /** * Basic config for master service */ public class MasterConfig extends AbstractFileConfig { private static final Logger logger = LoggerFactory.getLogger(MasterConfig.class); private String hostName; private int port; private int webPort = 8080; private TLSConfig tlsConfig; private boolean useBdbStoreMetaData = false; private ZKMetaConfig zkMetaConfig = null; private BdbMetaConfig bdbMetaConfig = null; private PrometheusConfig promConfig = null; private int consumerBalancePeriodMs = 60 * 1000; private int firstBalanceDelayAfterStartMs = 30 * 1000; private int consumerHeartbeatTimeoutMs = 30 * 1000; private int producerHeartbeatTimeoutMs = 30 * 1000; private int brokerHeartbeatTimeoutMs = 30 * 1000; private long rpcReadTimeoutMs = RpcConstants.CFG_RPC_READ_TIMEOUT_DEFAULT_MS; private long nettyWriteBufferHighWaterMark = 10 * 1024 * 1024; private long nettyWriteBufferLowWaterMark = 5 * 1024 * 1024; private long onlineOnlyReadToRWPeriodMs = 2 * 60 * 1000; private long offlineOnlyReadToRWPeriodMs = 30 * 1000; private long stepChgWaitPeriodMs = 12 * 1000; private String confModAuthToken = "ASDFGHJKL"; private String webResourcePath = "../resources"; private int maxGroupBrokerConsumeRate = 1000; private int maxGroupRebalanceWaitPeriod = 2; private int maxAutoForbiddenCnt = 5; private long socketSendBuffer = -1; private long socketRecvBuffer = -1; private boolean startOffsetResetCheck = false; private int rowLockWaitDurMs = TServerConstants.CFG_ROWLOCK_DEFAULT_DURATION; private boolean startVisitTokenCheck = false; private boolean startProduceAuthenticate = false; private boolean startProduceAuthorize = false; private boolean startConsumeAuthenticate = false; private boolean startConsumeAuthorize = false; private long visitTokenValidPeriodMs = 5 * 60 * 1000; private boolean needBrokerVisitAuth = false; private boolean useWebProxy = false; private String visitName = ""; private String visitPassword = ""; private long authValidTimeStampPeriodMs = TBaseConstants.CFG_DEFAULT_AUTH_TIMESTAMP_VALID_INTERVAL; private int rebalanceParallel = 4; private long maxMetaForceUpdatePeriodMs = TBaseConstants.CFG_DEF_META_FORCE_UPDATE_PERIOD; /** * getters */ public String getHostName() { return hostName; } /** * Is Transport Layer Security enabled ? * * @return true if enabled */ public boolean isTlsEnable() { return this.tlsConfig.isTlsEnable(); } public int getPort() { return port; } public int getWebPort() { return webPort; } public long getOfflineOnlyReadToRWPeriodMs() { return this.offlineOnlyReadToRWPeriodMs; } public String getConfModAuthToken() { return this.confModAuthToken; } public long getOnlineOnlyReadToRWPeriodMs() { return this.onlineOnlyReadToRWPeriodMs; } public long getStepChgWaitPeriodMs() { return this.stepChgWaitPeriodMs; } public long getRpcReadTimeoutMs() { return this.rpcReadTimeoutMs; } public long getNettyWriteBufferHighWaterMark() { return this.nettyWriteBufferHighWaterMark; } public long getNettyWriteBufferLowWaterMark() { return this.nettyWriteBufferLowWaterMark; } public int getConsumerBalancePeriodMs() { return consumerBalancePeriodMs; } public int getFirstBalanceDelayAfterStartMs() { return firstBalanceDelayAfterStartMs; } public String getWebResourcePath() { return webResourcePath; } public String getMetaDataPath() { if (useBdbStoreMetaData) { return this.bdbMetaConfig.getMetaDataPath(); } return null; } /** * Setter * * @param webResourcePath TODO: Have no usage, could be removed? */ public void setWebResourcePath(String webResourcePath) { this.webResourcePath = webResourcePath; } public int getConsumerHeartbeatTimeoutMs() { return consumerHeartbeatTimeoutMs; } public int getProducerHeartbeatTimeoutMs() { return producerHeartbeatTimeoutMs; } public int getBrokerHeartbeatTimeoutMs() { return brokerHeartbeatTimeoutMs; } public int getMaxGroupBrokerConsumeRate() { return maxGroupBrokerConsumeRate; } public boolean isStartOffsetResetCheck() { return startOffsetResetCheck; } public int getMaxGroupRebalanceWaitPeriod() { return maxGroupRebalanceWaitPeriod; } public int getRowLockWaitDurMs() { return rowLockWaitDurMs; } public int getMaxAutoForbiddenCnt() { return maxAutoForbiddenCnt; } public BdbMetaConfig getBdbMetaConfig() { return this.bdbMetaConfig; } public TLSConfig getTlsConfig() { return this.tlsConfig; } public ZKMetaConfig getZkMetaConfig() { return zkMetaConfig; } public PrometheusConfig getPromConfig() { return this.promConfig; } public boolean isStartVisitTokenCheck() { return startVisitTokenCheck; } public long getVisitTokenValidPeriodMs() { return visitTokenValidPeriodMs; } public boolean isStartProduceAuthenticate() { return startProduceAuthenticate; } public boolean isStartProduceAuthorize() { return startProduceAuthorize; } public boolean isNeedBrokerVisitAuth() { return needBrokerVisitAuth; } public boolean isStartConsumeAuthenticate() { return startConsumeAuthenticate; } public boolean isStartConsumeAuthorize() { return startConsumeAuthorize; } public boolean isUseWebProxy() { return useWebProxy; } public long getSocketSendBuffer() { return socketSendBuffer; } public long getSocketRecvBuffer() { return socketRecvBuffer; } public String getVisitName() { return visitName; } public String getVisitPassword() { return visitPassword; } public long getAuthValidTimeStampPeriodMs() { return authValidTimeStampPeriodMs; } public int getRebalanceParallel() { return rebalanceParallel; } public long getMaxMetaForceUpdatePeriodMs() { return maxMetaForceUpdatePeriodMs; } public boolean isUseBdbStoreMetaData() { return useBdbStoreMetaData; } /** * Load file section attributes * * @param iniConf the master ini object */ @Override protected void loadFileSectAttributes(final Ini iniConf) { this.loadSystemConf(iniConf); this.loadMetaDataSectConf(iniConf); this.tlsConfig = this.loadTlsSectConf(iniConf, TBaseConstants.META_DEFAULT_MASTER_TLS_PORT); this.promConfig = this.loadPrometheusSecConf(iniConf); if (this.port == this.webPort || (tlsConfig.isTlsEnable() && (this.tlsConfig.getTlsPort() == this.webPort))) { throw new IllegalArgumentException(new StringBuilder(512) .append("Illegal field value configuration, the value of ") .append("port or tlsPort cannot be the same as the value of webPort!") .toString()); } if (this.promConfig.isPromEnable()) { int promHttpPort = this.promConfig.getPromHttpPort(); if ((promHttpPort == this.port || promHttpPort == this.webPort || (tlsConfig.isTlsEnable() && (this.tlsConfig.getTlsPort() == promHttpPort)))) { throw new IllegalArgumentException(new StringBuilder(512) .append("Illegal port value configuration, the value of ") .append("port or webPort or tlsPort cannot be the same as the value of promHttpPort!") .toString()); } } if (useBdbStoreMetaData) { if (this.port == bdbMetaConfig.getRepNodePort() || (tlsConfig.isTlsEnable() && (this.tlsConfig.getTlsPort() == bdbMetaConfig.getRepNodePort()))) { throw new IllegalArgumentException(new StringBuilder(512) .append("Illegal field value configuration, the value of ") .append("port or tlsPort cannot be the same as the value of repNodePort!") .toString()); } if (this.webPort == bdbMetaConfig.getRepNodePort()) { throw new IllegalArgumentException(new StringBuilder(512) .append("Illegal field value configuration, the value of ") .append("webPort cannot be the same as the value of repNodePort!") .toString()); } if (this.promConfig.isPromEnable() && this.promConfig.getPromHttpPort() == bdbMetaConfig.getRepNodePort()) { throw new IllegalArgumentException(new StringBuilder(512) .append("Illegal field value configuration, the value of ") .append("promHttpPort cannot be the same as the value of repNodePort!") .toString()); } } } /** * Load system config * * @param iniConf the master ini object */ // #lizard forgives private void loadSystemConf(final Ini iniConf) { final Profile.Section masterConf = iniConf.get(SECT_TOKEN_MASTER); if (masterConf == null) { throw new IllegalArgumentException(new StringBuilder(256) .append(SECT_TOKEN_MASTER).append(" configure section is required!").toString()); } Set<String> configKeySet = masterConf.keySet(); if (configKeySet.isEmpty()) { /* Should have a least one config item */ throw new IllegalArgumentException(new StringBuilder(256) .append("Empty configure item in ").append(SECT_TOKEN_MASTER) .append(" section!").toString()); } // port this.port = this.getInt(masterConf, "port", TBaseConstants.META_DEFAULT_MASTER_PORT); // hostname if (TStringUtils.isNotBlank(masterConf.get("hostName"))) { this.hostName = masterConf.get("hostName").trim(); } else { try { this.hostName = AddressUtils.getIPV4LocalAddress(); } catch (Throwable e) { throw new IllegalArgumentException(new StringBuilder(256) .append("Get default master hostName failure : ") .append(e.getMessage()).toString()); } } // web port if (TStringUtils.isNotBlank(masterConf.get("webPort"))) { this.webPort = this.getInt(masterConf, "webPort"); } // web resource path if (TStringUtils.isBlank(masterConf.get("webResourcePath"))) { throw new IllegalArgumentException(new StringBuilder(256) .append("webResourcePath is null or Blank in ").append(SECT_TOKEN_MASTER) .append(" section!").toString()); } this.webResourcePath = masterConf.get("webResourcePath").trim(); if (TStringUtils.isNotBlank(masterConf.get("consumerBalancePeriodMs"))) { this.consumerBalancePeriodMs = this.getInt(masterConf, "consumerBalancePeriodMs"); } if (TStringUtils.isNotBlank(masterConf.get("firstBalanceDelayAfterStartMs"))) { this.firstBalanceDelayAfterStartMs = this.getInt(masterConf, "firstBalanceDelayAfterStartMs"); } if (TStringUtils.isNotBlank(masterConf.get("consumerHeartbeatTimeoutMs"))) { this.consumerHeartbeatTimeoutMs = this.getInt(masterConf, "consumerHeartbeatTimeoutMs"); } if (TStringUtils.isNotBlank(masterConf.get("producerHeartbeatTimeoutMs"))) { this.producerHeartbeatTimeoutMs = this.getInt(masterConf, "producerHeartbeatTimeoutMs"); } if (TStringUtils.isNotBlank(masterConf.get("brokerHeartbeatTimeoutMs"))) { this.brokerHeartbeatTimeoutMs = this.getInt(masterConf, "brokerHeartbeatTimeoutMs"); } if (TStringUtils.isNotBlank(masterConf.get("socketSendBuffer"))) { this.socketSendBuffer = this.getLong(masterConf, "socketSendBuffer"); } if (TStringUtils.isNotBlank(masterConf.get("socketRecvBuffer"))) { this.socketRecvBuffer = this.getLong(masterConf, "socketRecvBuffer"); } if (TStringUtils.isNotBlank(masterConf.get("rpcReadTimeoutMs"))) { this.rpcReadTimeoutMs = this.getLong(masterConf, "rpcReadTimeoutMs"); } if (TStringUtils.isNotBlank(masterConf.get("nettyWriteBufferHighWaterMark"))) { this.nettyWriteBufferHighWaterMark = this.getLong(masterConf, "nettyWriteBufferHighWaterMark"); } if (TStringUtils.isNotBlank(masterConf.get("nettyWriteBufferLowWaterMark"))) { this.nettyWriteBufferLowWaterMark = this.getLong(masterConf, "nettyWriteBufferLowWaterMark"); } if (TStringUtils.isNotBlank(masterConf.get("onlineOnlyReadToRWPeriodMs"))) { this.onlineOnlyReadToRWPeriodMs = this.getLong(masterConf, "onlineOnlyReadToRWPeriodMs"); } if (TStringUtils.isNotBlank(masterConf.get("stepChgWaitPeriodMs"))) { this.stepChgWaitPeriodMs = this.getLong(masterConf, "stepChgWaitPeriodMs"); } if (TStringUtils.isNotBlank(masterConf.get("offlineOnlyReadToRWPeriodMs"))) { this.offlineOnlyReadToRWPeriodMs = this.getLong(masterConf, "offlineOnlyReadToRWPeriodMs"); } if (TStringUtils.isNotBlank(masterConf.get("confModAuthToken"))) { String tmpAuthToken = masterConf.get("confModAuthToken").trim(); if (tmpAuthToken.length() > TServerConstants.CFG_MODAUTHTOKEN_MAX_LENGTH) { throw new IllegalArgumentException( "Invalid value: the length of confModAuthToken's value > " + TServerConstants.CFG_MODAUTHTOKEN_MAX_LENGTH); } this.confModAuthToken = tmpAuthToken; } if (TStringUtils.isNotBlank(masterConf.get("maxGroupBrokerConsumeRate"))) { this.maxGroupBrokerConsumeRate = this.getInt(masterConf, "maxGroupBrokerConsumeRate"); if (this.maxGroupBrokerConsumeRate <= 0) { throw new IllegalArgumentException( "Invalid value: maxGroupBrokerConsumeRate's value must > 0 !"); } } if (TStringUtils.isNotBlank(masterConf.get("maxGroupRebalanceWaitPeriod"))) { this.maxGroupRebalanceWaitPeriod = this.getInt(masterConf, "maxGroupRebalanceWaitPeriod"); } if (TStringUtils.isNotBlank(masterConf.get("startOffsetResetCheck"))) { this.startOffsetResetCheck = this.getBoolean(masterConf, "startOffsetResetCheck"); } if (TStringUtils.isNotBlank(masterConf.get("rowLockWaitDurMs"))) { this.rowLockWaitDurMs = this.getInt(masterConf, "rowLockWaitDurMs"); } if (TStringUtils.isNotBlank(masterConf.get("maxAutoForbiddenCnt"))) { this.maxAutoForbiddenCnt = this.getInt(masterConf, "maxAutoForbiddenCnt"); } if (TStringUtils.isNotBlank(masterConf.get("visitTokenValidPeriodMs"))) { long tmpPeriodMs = this.getLong(masterConf, "visitTokenValidPeriodMs"); if (tmpPeriodMs < 3 * 60 * 1000) { /* Min value is 3 min */ tmpPeriodMs = 3 * 60 * 1000; } this.visitTokenValidPeriodMs = tmpPeriodMs; } if (TStringUtils.isNotBlank(masterConf.get("authValidTimeStampPeriodMs"))) { long tmpPeriodMs = this.getLong(masterConf, "authValidTimeStampPeriodMs"); // must between 5,000 ms and 120,000 ms this.authValidTimeStampPeriodMs = tmpPeriodMs < 5000 ? 5000 : tmpPeriodMs > 120000 ? 120000 : tmpPeriodMs; } if (TStringUtils.isNotBlank(masterConf.get("startVisitTokenCheck"))) { this.startVisitTokenCheck = this.getBoolean(masterConf, "startVisitTokenCheck"); } if (TStringUtils.isNotBlank(masterConf.get("startProduceAuthenticate"))) { this.startProduceAuthenticate = this.getBoolean(masterConf, "startProduceAuthenticate"); } if (TStringUtils.isNotBlank(masterConf.get("startProduceAuthorize"))) { this.startProduceAuthorize = this.getBoolean(masterConf, "startProduceAuthorize"); } if (TStringUtils.isNotBlank(masterConf.get("useWebProxy"))) { this.useWebProxy = this.getBoolean(masterConf, "useWebProxy"); } if (!this.startProduceAuthenticate && this.startProduceAuthorize) { throw new IllegalArgumentException( "startProduceAuthenticate must set true if startProduceAuthorize is true!"); } if (TStringUtils.isNotBlank(masterConf.get("startConsumeAuthenticate"))) { this.startConsumeAuthenticate = this.getBoolean(masterConf, "startConsumeAuthenticate"); } if (TStringUtils.isNotBlank(masterConf.get("startConsumeAuthorize"))) { this.startConsumeAuthorize = this.getBoolean(masterConf, "startConsumeAuthorize"); } if (!this.startConsumeAuthenticate && this.startConsumeAuthorize) { throw new IllegalArgumentException( "startConsumeAuthenticate must set true if startConsumeAuthorize is true!"); } if (TStringUtils.isNotBlank(masterConf.get("needBrokerVisitAuth"))) { this.needBrokerVisitAuth = this.getBoolean(masterConf, "needBrokerVisitAuth"); } if (this.needBrokerVisitAuth) { if (TStringUtils.isBlank(masterConf.get("visitName"))) { throw new IllegalArgumentException(new StringBuilder(256) .append("visitName is null or Blank in ").append(SECT_TOKEN_MASTER) .append(" section!").toString()); } if (TStringUtils.isBlank(masterConf.get("visitPassword"))) { throw new IllegalArgumentException(new StringBuilder(256) .append("visitPassword is null or Blank in ").append(SECT_TOKEN_MASTER) .append(" section!").toString()); } this.visitName = masterConf.get("visitName").trim(); this.visitPassword = masterConf.get("visitPassword").trim(); } if (TStringUtils.isNotBlank(masterConf.get("rebalanceParallel"))) { int tmpParallel = this.getInt(masterConf, "rebalanceParallel"); this.rebalanceParallel = MixedUtils.mid(tmpParallel, 1, 20); } if (TStringUtils.isNotBlank(masterConf.get("maxMetaForceUpdatePeriodMs"))) { long tmpPeriodMs = this.getLong(masterConf, "maxMetaForceUpdatePeriodMs"); if (tmpPeriodMs < TBaseConstants.CFG_MIN_META_FORCE_UPDATE_PERIOD) { tmpPeriodMs = TBaseConstants.CFG_MIN_META_FORCE_UPDATE_PERIOD; } this.maxMetaForceUpdatePeriodMs = tmpPeriodMs; } } /** * Load meta-data section config * * @param iniConf the master ini object */ private void loadMetaDataSectConf(final Ini iniConf) { if (iniConf.get(SECT_TOKEN_META_BDB) != null && iniConf.get(SECT_TOKEN_META_ZK) != null) { throw new IllegalArgumentException(new StringBuilder(256) .append("Cannot configure both ").append(SECT_TOKEN_META_BDB).append(" and ") .append(SECT_TOKEN_META_ZK).append(" meta-data sections in the same time") .append(", please confirm them and retain one first!").toString()); } Profile.Section metaSect = iniConf.get(SECT_TOKEN_META_ZK); if (metaSect != null) { this.useBdbStoreMetaData = false; this.zkMetaConfig = loadZkMetaSectConf(iniConf); return; } metaSect = iniConf.get(SECT_TOKEN_META_BDB); if (metaSect != null) { this.useBdbStoreMetaData = true; this.bdbMetaConfig = loadBdbMetaSectConf(iniConf); return; } metaSect = iniConf.get(SECT_TOKEN_REPLICATION); if (metaSect != null) { this.useBdbStoreMetaData = true; this.bdbMetaConfig = loadReplicationSectConf(iniConf); return; } metaSect = iniConf.get(SECT_TOKEN_BDB); if (metaSect != null) { this.useBdbStoreMetaData = true; this.bdbMetaConfig = loadBdbStoreSectConf(iniConf); return; } throw new IllegalArgumentException(new StringBuilder(256) .append("Missing necessary meta-data section, please select ") .append(SECT_TOKEN_META_ZK).append(" or ").append(SECT_TOKEN_META_BDB) .append(" and configure ini again!").toString()); } /** * Load ZooKeeper store section configure as meta-data storage * * @param iniConf the master ini object * @return the configured information */ private ZKMetaConfig loadZkMetaSectConf(final Ini iniConf) { final Profile.Section zkeeperSect = iniConf.get(SECT_TOKEN_META_ZK); if (zkeeperSect == null) { throw new IllegalArgumentException(new StringBuilder(256) .append(SECT_TOKEN_META_ZK).append(" configure section is required!").toString()); } Set<String> configKeySet = zkeeperSect.keySet(); if (configKeySet.isEmpty()) { throw new IllegalArgumentException(new StringBuilder(256) .append("Empty configure item in ").append(SECT_TOKEN_META_ZK) .append(" section!").toString()); } ZKMetaConfig zkMetaConfig = new ZKMetaConfig(); if (TStringUtils.isNotBlank(zkeeperSect.get("zkServerAddr"))) { zkMetaConfig.setZkServerAddr(zkeeperSect.get("zkServerAddr").trim()); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkNodeRoot"))) { zkMetaConfig.setZkNodeRoot(zkeeperSect.get("zkNodeRoot").trim()); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkSessionTimeoutMs"))) { zkMetaConfig.setZkSessionTimeoutMs(getInt(zkeeperSect, "zkSessionTimeoutMs")); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkConnectionTimeoutMs"))) { zkMetaConfig.setZkConnectionTimeoutMs(getInt(zkeeperSect, "zkConnectionTimeoutMs")); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkSyncTimeMs"))) { zkMetaConfig.setZkSyncTimeMs(getInt(zkeeperSect, "zkSyncTimeMs")); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkCommitPeriodMs"))) { zkMetaConfig.setZkCommitPeriodMs(getLong(zkeeperSect, "zkCommitPeriodMs")); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkCommitFailRetries"))) { zkMetaConfig.setZkCommitFailRetries(getInt(zkeeperSect, "zkCommitFailRetries")); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkMasterCheckPeriodMs"))) { zkMetaConfig.setZkMasterCheckPeriodMs(getInt(zkeeperSect, "zkMasterCheckPeriodMs")); } if (TStringUtils.isNotBlank(zkeeperSect.get("zkRequestTimeoutMs"))) { zkMetaConfig.setZkRequestTimeoutMs(getInt(zkeeperSect, "zkRequestTimeoutMs")); } return zkMetaConfig; } /** * Load Berkeley DB store section configure as meta-data storage * * @param iniConf the master ini object * @return the configured information */ private BdbMetaConfig loadBdbMetaSectConf(final Ini iniConf) { final Profile.Section repSect = iniConf.get(SECT_TOKEN_META_BDB); if (repSect == null) { return null; } Set<String> configKeySet = repSect.keySet(); if (configKeySet.isEmpty()) { throw new IllegalArgumentException(new StringBuilder(256) .append("Empty configure item in ").append(SECT_TOKEN_META_BDB) .append(" section!").toString()); } BdbMetaConfig tmpMetaConfig = new BdbMetaConfig(); // read configure items if (TStringUtils.isNotBlank(repSect.get("repGroupName"))) { tmpMetaConfig.setRepGroupName(repSect.get("repGroupName").trim()); } if (TStringUtils.isBlank(repSect.get("repNodeName"))) { getSimilarConfigField(SECT_TOKEN_META_BDB, configKeySet, "repNodeName"); } else { tmpMetaConfig.setRepNodeName(repSect.get("repNodeName").trim()); } if (TStringUtils.isNotBlank(repSect.get("repNodePort"))) { tmpMetaConfig.setRepNodePort(getInt(repSect, "repNodePort")); } if (TStringUtils.isNotBlank(repSect.get("metaDataPath"))) { tmpMetaConfig.setMetaDataPath(repSect.get("metaDataPath").trim()); } if (TStringUtils.isNotBlank(repSect.get("repHelperHost"))) { tmpMetaConfig.setRepHelperHost(repSect.get("repHelperHost").trim()); } if (TStringUtils.isNotBlank(repSect.get("metaLocalSyncPolicy"))) { tmpMetaConfig.setMetaLocalSyncPolicy(getInt(repSect, "metaLocalSyncPolicy")); } if (TStringUtils.isNotBlank(repSect.get("metaReplicaSyncPolicy"))) { tmpMetaConfig.setMetaReplicaSyncPolicy(getInt(repSect, "metaReplicaSyncPolicy")); } if (TStringUtils.isNotBlank(repSect.get("repReplicaAckPolicy"))) { tmpMetaConfig.setRepReplicaAckPolicy(getInt(repSect, "repReplicaAckPolicy")); } if (TStringUtils.isNotBlank(repSect.get("repStatusCheckTimeoutMs"))) { tmpMetaConfig.setRepStatusCheckTimeoutMs(getLong(repSect, "repStatusCheckTimeoutMs")); } return tmpMetaConfig; } /** * Deprecated: Load Berkeley DB store section config * Just keep `loadBdbStoreSectConf` for backward compatibility * * @param iniConf the master ini object * @return the configured information */ private BdbMetaConfig loadBdbStoreSectConf(final Ini iniConf) { final Profile.Section bdbSect = iniConf.get(SECT_TOKEN_BDB); if (bdbSect == null) { return null; } Set<String> configKeySet = bdbSect.keySet(); if (configKeySet.isEmpty()) { throw new IllegalArgumentException(new StringBuilder(256) .append("Empty configure item in ").append(SECT_TOKEN_BDB) .append(" section!").toString()); } logger.warn("[bdbStore] section is deprecated. Please config in [meta_bdb] section."); // read configure items BdbMetaConfig tmpMetaConfig = new BdbMetaConfig(); if (TStringUtils.isBlank(bdbSect.get("bdbRepGroupName"))) { getSimilarConfigField(SECT_TOKEN_BDB, configKeySet, "bdbRepGroupName"); } else { tmpMetaConfig.setRepGroupName(bdbSect.get("bdbRepGroupName").trim()); } if (TStringUtils.isBlank(bdbSect.get("bdbNodeName"))) { getSimilarConfigField(SECT_TOKEN_BDB, configKeySet, "bdbNodeName"); } else { tmpMetaConfig.setRepNodeName(bdbSect.get("bdbNodeName").trim()); } if (TStringUtils.isNotBlank(bdbSect.get("bdbNodePort"))) { tmpMetaConfig.setRepNodePort(getInt(bdbSect, "bdbNodePort")); } if (TStringUtils.isBlank(bdbSect.get("bdbEnvHome"))) { getSimilarConfigField(SECT_TOKEN_BDB, configKeySet, "bdbEnvHome"); } else { tmpMetaConfig.setMetaDataPath(bdbSect.get("bdbEnvHome").trim()); } if (TStringUtils.isBlank(bdbSect.get("bdbHelperHost"))) { getSimilarConfigField(SECT_TOKEN_BDB, configKeySet, "bdbHelperHost"); } else { tmpMetaConfig.setRepHelperHost(bdbSect.get("bdbHelperHost").trim()); } if (TStringUtils.isNotBlank(bdbSect.get("bdbLocalSync"))) { tmpMetaConfig.setMetaLocalSyncPolicy(getInt(bdbSect, "bdbLocalSync")); } if (TStringUtils.isNotBlank(bdbSect.get("bdbReplicaSync"))) { tmpMetaConfig.setMetaReplicaSyncPolicy(getInt(bdbSect, "bdbReplicaSync")); } if (TStringUtils.isNotBlank(bdbSect.get("bdbReplicaAck"))) { tmpMetaConfig.setRepReplicaAckPolicy(getInt(bdbSect, "bdbReplicaAck")); } if (TStringUtils.isNotBlank(bdbSect.get("bdbStatusCheckTimeoutMs"))) { tmpMetaConfig.setRepStatusCheckTimeoutMs(getLong(bdbSect, "bdbStatusCheckTimeoutMs")); } return tmpMetaConfig; } /** * Deprecated: Load Berkeley DB store section config * Just keep `loadReplicationSectConf` for backward compatibility * * @param iniConf the master ini object * @return the configured information */ private BdbMetaConfig loadReplicationSectConf(final Ini iniConf) { final Profile.Section repSect = iniConf.get(SECT_TOKEN_REPLICATION); if (repSect == null) { return null; } Set<String> configKeySet = repSect.keySet(); if (configKeySet.isEmpty()) { throw new IllegalArgumentException(new StringBuilder(256) .append("Empty configure item in ").append(SECT_TOKEN_REPLICATION) .append(" section!").toString()); } BdbMetaConfig tmpMetaConfig = new BdbMetaConfig(); logger.warn("[replication] section is deprecated. Please config in [meta_bdb] section."); // read configure items if (TStringUtils.isNotBlank(repSect.get("repGroupName"))) { tmpMetaConfig.setRepGroupName(repSect.get("repGroupName").trim()); } if (TStringUtils.isBlank(repSect.get("repNodeName"))) { getSimilarConfigField(SECT_TOKEN_REPLICATION, configKeySet, "repNodeName"); } else { tmpMetaConfig.setRepNodeName(repSect.get("repNodeName").trim()); } if (TStringUtils.isNotBlank(repSect.get("repNodePort"))) { tmpMetaConfig.setRepNodePort(getInt(repSect, "repNodePort")); } // meta data path final Profile.Section masterConf = iniConf.get(SECT_TOKEN_MASTER); if (TStringUtils.isNotBlank(masterConf.get("metaDataPath"))) { tmpMetaConfig.setMetaDataPath(masterConf.get("metaDataPath").trim()); } if (TStringUtils.isNotBlank(repSect.get("repHelperHost"))) { tmpMetaConfig.setRepHelperHost(repSect.get("repHelperHost").trim()); } if (TStringUtils.isNotBlank(repSect.get("metaLocalSyncPolicy"))) { tmpMetaConfig.setMetaLocalSyncPolicy(getInt(repSect, "metaLocalSyncPolicy")); } if (TStringUtils.isNotBlank(repSect.get("metaReplicaSyncPolicy"))) { tmpMetaConfig.setMetaReplicaSyncPolicy(getInt(repSect, "metaReplicaSyncPolicy")); } if (TStringUtils.isNotBlank(repSect.get("repReplicaAckPolicy"))) { tmpMetaConfig.setRepReplicaAckPolicy(getInt(repSect, "repReplicaAckPolicy")); } if (TStringUtils.isNotBlank(repSect.get("repStatusCheckTimeoutMs"))) { tmpMetaConfig.setRepStatusCheckTimeoutMs(getLong(repSect, "repStatusCheckTimeoutMs")); } return tmpMetaConfig; } @Override public String toString() { return new ToStringBuilder(this) .append("hostName", hostName) .append("port", port) .append("webPort", webPort) .append("tlsConfig", tlsConfig) .append("promConfig", promConfig) .append("useBdbStoreMetaData", useBdbStoreMetaData) .append("zkMetaConfig", zkMetaConfig) .append("bdbMetaConfig", bdbMetaConfig) .append("consumerBalancePeriodMs", consumerBalancePeriodMs) .append("firstBalanceDelayAfterStartMs", firstBalanceDelayAfterStartMs) .append("consumerHeartbeatTimeoutMs", consumerHeartbeatTimeoutMs) .append("producerHeartbeatTimeoutMs", producerHeartbeatTimeoutMs) .append("brokerHeartbeatTimeoutMs", brokerHeartbeatTimeoutMs) .append("rpcReadTimeoutMs", rpcReadTimeoutMs) .append("nettyWriteBufferHighWaterMark", nettyWriteBufferHighWaterMark) .append("nettyWriteBufferLowWaterMark", nettyWriteBufferLowWaterMark) .append("onlineOnlyReadToRWPeriodMs", onlineOnlyReadToRWPeriodMs) .append("offlineOnlyReadToRWPeriodMs", offlineOnlyReadToRWPeriodMs) .append("stepChgWaitPeriodMs", stepChgWaitPeriodMs) .append("confModAuthToken", confModAuthToken) .append("webResourcePath", webResourcePath) .append("maxGroupBrokerConsumeRate", maxGroupBrokerConsumeRate) .append("maxGroupRebalanceWaitPeriod", maxGroupRebalanceWaitPeriod) .append("maxAutoForbiddenCnt", maxAutoForbiddenCnt) .append("socketSendBuffer", socketSendBuffer) .append("socketRecvBuffer", socketRecvBuffer) .append("startOffsetResetCheck", startOffsetResetCheck) .append("rowLockWaitDurMs", rowLockWaitDurMs) .append("startVisitTokenCheck", startVisitTokenCheck) .append("startProduceAuthenticate", startProduceAuthenticate) .append("startProduceAuthorize", startProduceAuthorize) .append("startConsumeAuthenticate", startConsumeAuthenticate) .append("startConsumeAuthorize", startConsumeAuthorize) .append("visitTokenValidPeriodMs", visitTokenValidPeriodMs) .append("needBrokerVisitAuth", needBrokerVisitAuth) .append("useWebProxy", useWebProxy) .append("visitName", visitName) .append("visitPassword", visitPassword) .append("authValidTimeStampPeriodMs", authValidTimeStampPeriodMs) .append("rebalanceParallel", rebalanceParallel) .append("maxMetaForceUpdatePeriodMs", maxMetaForceUpdatePeriodMs) .toString(); } }
googleapis/google-cloud-java
36,863
java-shopping-merchant-accounts/proto-google-shopping-merchant-accounts-v1/src/main/java/com/google/shopping/merchant/accounts/v1/ListRegionsResponse.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/regions.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.accounts.v1; /** * * * <pre> * Response message for the `ListRegions` method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1.ListRegionsResponse} */ public final class ListRegionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.accounts.v1.ListRegionsResponse) ListRegionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListRegionsResponse.newBuilder() to construct. private ListRegionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListRegionsResponse() { regions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListRegionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1.RegionsProto .internal_static_google_shopping_merchant_accounts_v1_ListRegionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1.RegionsProto .internal_static_google_shopping_merchant_accounts_v1_ListRegionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1.ListRegionsResponse.class, com.google.shopping.merchant.accounts.v1.ListRegionsResponse.Builder.class); } public static final int REGIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.shopping.merchant.accounts.v1.Region> regions_; /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ @java.lang.Override public java.util.List<com.google.shopping.merchant.accounts.v1.Region> getRegionsList() { return regions_; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.shopping.merchant.accounts.v1.RegionOrBuilder> getRegionsOrBuilderList() { return regions_; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ @java.lang.Override public int getRegionsCount() { return regions_.size(); } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1.Region getRegions(int index) { return regions_.get(index); } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1.RegionOrBuilder getRegionsOrBuilder(int index) { return regions_.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 < regions_.size(); i++) { output.writeMessage(1, regions_.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 < regions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, regions_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.merchant.accounts.v1.ListRegionsResponse)) { return super.equals(obj); } com.google.shopping.merchant.accounts.v1.ListRegionsResponse other = (com.google.shopping.merchant.accounts.v1.ListRegionsResponse) obj; if (!getRegionsList().equals(other.getRegionsList())) 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 (getRegionsCount() > 0) { hash = (37 * hash) + REGIONS_FIELD_NUMBER; hash = (53 * hash) + getRegionsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.accounts.v1.ListRegionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.ListRegionsResponse 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.ListRegionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.ListRegionsResponse 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.ListRegionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1.ListRegionsResponse 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.ListRegionsResponse 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.ListRegionsResponse 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.ListRegionsResponse 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.ListRegionsResponse 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.ListRegionsResponse 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.ListRegionsResponse 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.ListRegionsResponse 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 `ListRegions` method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1.ListRegionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.accounts.v1.ListRegionsResponse) com.google.shopping.merchant.accounts.v1.ListRegionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1.RegionsProto .internal_static_google_shopping_merchant_accounts_v1_ListRegionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1.RegionsProto .internal_static_google_shopping_merchant_accounts_v1_ListRegionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1.ListRegionsResponse.class, com.google.shopping.merchant.accounts.v1.ListRegionsResponse.Builder.class); } // Construct using com.google.shopping.merchant.accounts.v1.ListRegionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (regionsBuilder_ == null) { regions_ = java.util.Collections.emptyList(); } else { regions_ = null; regionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.accounts.v1.RegionsProto .internal_static_google_shopping_merchant_accounts_v1_ListRegionsResponse_descriptor; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListRegionsResponse getDefaultInstanceForType() { return com.google.shopping.merchant.accounts.v1.ListRegionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListRegionsResponse build() { com.google.shopping.merchant.accounts.v1.ListRegionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListRegionsResponse buildPartial() { com.google.shopping.merchant.accounts.v1.ListRegionsResponse result = new com.google.shopping.merchant.accounts.v1.ListRegionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.shopping.merchant.accounts.v1.ListRegionsResponse result) { if (regionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { regions_ = java.util.Collections.unmodifiableList(regions_); bitField0_ = (bitField0_ & ~0x00000001); } result.regions_ = regions_; } else { result.regions_ = regionsBuilder_.build(); } } private void buildPartial0( com.google.shopping.merchant.accounts.v1.ListRegionsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.shopping.merchant.accounts.v1.ListRegionsResponse) { return mergeFrom((com.google.shopping.merchant.accounts.v1.ListRegionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.shopping.merchant.accounts.v1.ListRegionsResponse other) { if (other == com.google.shopping.merchant.accounts.v1.ListRegionsResponse.getDefaultInstance()) return this; if (regionsBuilder_ == null) { if (!other.regions_.isEmpty()) { if (regions_.isEmpty()) { regions_ = other.regions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureRegionsIsMutable(); regions_.addAll(other.regions_); } onChanged(); } } else { if (!other.regions_.isEmpty()) { if (regionsBuilder_.isEmpty()) { regionsBuilder_.dispose(); regionsBuilder_ = null; regions_ = other.regions_; bitField0_ = (bitField0_ & ~0x00000001); regionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRegionsFieldBuilder() : null; } else { regionsBuilder_.addAllMessages(other.regions_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.shopping.merchant.accounts.v1.Region m = input.readMessage( com.google.shopping.merchant.accounts.v1.Region.parser(), extensionRegistry); if (regionsBuilder_ == null) { ensureRegionsIsMutable(); regions_.add(m); } else { regionsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.shopping.merchant.accounts.v1.Region> regions_ = java.util.Collections.emptyList(); private void ensureRegionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { regions_ = new java.util.ArrayList<com.google.shopping.merchant.accounts.v1.Region>(regions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1.Region, com.google.shopping.merchant.accounts.v1.Region.Builder, com.google.shopping.merchant.accounts.v1.RegionOrBuilder> regionsBuilder_; /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public java.util.List<com.google.shopping.merchant.accounts.v1.Region> getRegionsList() { if (regionsBuilder_ == null) { return java.util.Collections.unmodifiableList(regions_); } else { return regionsBuilder_.getMessageList(); } } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public int getRegionsCount() { if (regionsBuilder_ == null) { return regions_.size(); } else { return regionsBuilder_.getCount(); } } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Region getRegions(int index) { if (regionsBuilder_ == null) { return regions_.get(index); } else { return regionsBuilder_.getMessage(index); } } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder setRegions(int index, com.google.shopping.merchant.accounts.v1.Region value) { if (regionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRegionsIsMutable(); regions_.set(index, value); onChanged(); } else { regionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder setRegions( int index, com.google.shopping.merchant.accounts.v1.Region.Builder builderForValue) { if (regionsBuilder_ == null) { ensureRegionsIsMutable(); regions_.set(index, builderForValue.build()); onChanged(); } else { regionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder addRegions(com.google.shopping.merchant.accounts.v1.Region value) { if (regionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRegionsIsMutable(); regions_.add(value); onChanged(); } else { regionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder addRegions(int index, com.google.shopping.merchant.accounts.v1.Region value) { if (regionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRegionsIsMutable(); regions_.add(index, value); onChanged(); } else { regionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder addRegions( com.google.shopping.merchant.accounts.v1.Region.Builder builderForValue) { if (regionsBuilder_ == null) { ensureRegionsIsMutable(); regions_.add(builderForValue.build()); onChanged(); } else { regionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder addRegions( int index, com.google.shopping.merchant.accounts.v1.Region.Builder builderForValue) { if (regionsBuilder_ == null) { ensureRegionsIsMutable(); regions_.add(index, builderForValue.build()); onChanged(); } else { regionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder addAllRegions( java.lang.Iterable<? extends com.google.shopping.merchant.accounts.v1.Region> values) { if (regionsBuilder_ == null) { ensureRegionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, regions_); onChanged(); } else { regionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder clearRegions() { if (regionsBuilder_ == null) { regions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { regionsBuilder_.clear(); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public Builder removeRegions(int index) { if (regionsBuilder_ == null) { ensureRegionsIsMutable(); regions_.remove(index); onChanged(); } else { regionsBuilder_.remove(index); } return this; } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Region.Builder getRegionsBuilder(int index) { return getRegionsFieldBuilder().getBuilder(index); } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public com.google.shopping.merchant.accounts.v1.RegionOrBuilder getRegionsOrBuilder(int index) { if (regionsBuilder_ == null) { return regions_.get(index); } else { return regionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public java.util.List<? extends com.google.shopping.merchant.accounts.v1.RegionOrBuilder> getRegionsOrBuilderList() { if (regionsBuilder_ != null) { return regionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(regions_); } } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Region.Builder addRegionsBuilder() { return getRegionsFieldBuilder() .addBuilder(com.google.shopping.merchant.accounts.v1.Region.getDefaultInstance()); } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public com.google.shopping.merchant.accounts.v1.Region.Builder addRegionsBuilder(int index) { return getRegionsFieldBuilder() .addBuilder(index, com.google.shopping.merchant.accounts.v1.Region.getDefaultInstance()); } /** * * * <pre> * The regions from the specified business. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1.Region regions = 1;</code> */ public java.util.List<com.google.shopping.merchant.accounts.v1.Region.Builder> getRegionsBuilderList() { return getRegionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1.Region, com.google.shopping.merchant.accounts.v1.Region.Builder, com.google.shopping.merchant.accounts.v1.RegionOrBuilder> getRegionsFieldBuilder() { if (regionsBuilder_ == null) { regionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1.Region, com.google.shopping.merchant.accounts.v1.Region.Builder, com.google.shopping.merchant.accounts.v1.RegionOrBuilder>( regions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); regions_ = null; } return regionsBuilder_; } 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.shopping.merchant.accounts.v1.ListRegionsResponse) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.accounts.v1.ListRegionsResponse) private static final com.google.shopping.merchant.accounts.v1.ListRegionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.accounts.v1.ListRegionsResponse(); } public static com.google.shopping.merchant.accounts.v1.ListRegionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListRegionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListRegionsResponse>() { @java.lang.Override public ListRegionsResponse 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<ListRegionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListRegionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.accounts.v1.ListRegionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,902
java-automl/proto-google-cloud-automl-v1beta1/src/main/java/com/google/cloud/automl/v1beta1/ListColumnSpecsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/automl/v1beta1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.automl.v1beta1; /** * * * <pre> * Response message for [AutoMl.ListColumnSpecs][google.cloud.automl.v1beta1.AutoMl.ListColumnSpecs]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.ListColumnSpecsResponse} */ public final class ListColumnSpecsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.ListColumnSpecsResponse) ListColumnSpecsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListColumnSpecsResponse.newBuilder() to construct. private ListColumnSpecsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListColumnSpecsResponse() { columnSpecs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListColumnSpecsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListColumnSpecsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListColumnSpecsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.class, com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.Builder.class); } public static final int COLUMN_SPECS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.automl.v1beta1.ColumnSpec> columnSpecs_; /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.automl.v1beta1.ColumnSpec> getColumnSpecsList() { return columnSpecs_; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder> getColumnSpecsOrBuilderList() { return columnSpecs_; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ @java.lang.Override public int getColumnSpecsCount() { return columnSpecs_.size(); } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ @java.lang.Override public com.google.cloud.automl.v1beta1.ColumnSpec getColumnSpecs(int index) { return columnSpecs_.get(index); } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ @java.lang.Override public com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder getColumnSpecsOrBuilder(int index) { return columnSpecs_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.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 < columnSpecs_.size(); i++) { output.writeMessage(1, columnSpecs_.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 < columnSpecs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, columnSpecs_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.automl.v1beta1.ListColumnSpecsResponse)) { return super.equals(obj); } com.google.cloud.automl.v1beta1.ListColumnSpecsResponse other = (com.google.cloud.automl.v1beta1.ListColumnSpecsResponse) obj; if (!getColumnSpecsList().equals(other.getColumnSpecsList())) 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 (getColumnSpecsCount() > 0) { hash = (37 * hash) + COLUMN_SPECS_FIELD_NUMBER; hash = (53 * hash) + getColumnSpecsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse 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.ListColumnSpecsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse 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.ListColumnSpecsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse 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.ListColumnSpecsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse 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.ListColumnSpecsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse 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.ListColumnSpecsResponse 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.ListColumnSpecsResponse 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.ListColumnSpecsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for [AutoMl.ListColumnSpecs][google.cloud.automl.v1beta1.AutoMl.ListColumnSpecs]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.ListColumnSpecsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.automl.v1beta1.ListColumnSpecsResponse) com.google.cloud.automl.v1beta1.ListColumnSpecsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListColumnSpecsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListColumnSpecsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.class, com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.Builder.class); } // Construct using com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (columnSpecsBuilder_ == null) { columnSpecs_ = java.util.Collections.emptyList(); } else { columnSpecs_ = null; columnSpecsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListColumnSpecsResponse_descriptor; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListColumnSpecsResponse getDefaultInstanceForType() { return com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.automl.v1beta1.ListColumnSpecsResponse build() { com.google.cloud.automl.v1beta1.ListColumnSpecsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListColumnSpecsResponse buildPartial() { com.google.cloud.automl.v1beta1.ListColumnSpecsResponse result = new com.google.cloud.automl.v1beta1.ListColumnSpecsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.automl.v1beta1.ListColumnSpecsResponse result) { if (columnSpecsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { columnSpecs_ = java.util.Collections.unmodifiableList(columnSpecs_); bitField0_ = (bitField0_ & ~0x00000001); } result.columnSpecs_ = columnSpecs_; } else { result.columnSpecs_ = columnSpecsBuilder_.build(); } } private void buildPartial0(com.google.cloud.automl.v1beta1.ListColumnSpecsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.automl.v1beta1.ListColumnSpecsResponse) { return mergeFrom((com.google.cloud.automl.v1beta1.ListColumnSpecsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.automl.v1beta1.ListColumnSpecsResponse other) { if (other == com.google.cloud.automl.v1beta1.ListColumnSpecsResponse.getDefaultInstance()) return this; if (columnSpecsBuilder_ == null) { if (!other.columnSpecs_.isEmpty()) { if (columnSpecs_.isEmpty()) { columnSpecs_ = other.columnSpecs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureColumnSpecsIsMutable(); columnSpecs_.addAll(other.columnSpecs_); } onChanged(); } } else { if (!other.columnSpecs_.isEmpty()) { if (columnSpecsBuilder_.isEmpty()) { columnSpecsBuilder_.dispose(); columnSpecsBuilder_ = null; columnSpecs_ = other.columnSpecs_; bitField0_ = (bitField0_ & ~0x00000001); columnSpecsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getColumnSpecsFieldBuilder() : null; } else { columnSpecsBuilder_.addAllMessages(other.columnSpecs_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.automl.v1beta1.ColumnSpec m = input.readMessage( com.google.cloud.automl.v1beta1.ColumnSpec.parser(), extensionRegistry); if (columnSpecsBuilder_ == null) { ensureColumnSpecsIsMutable(); columnSpecs_.add(m); } else { columnSpecsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.automl.v1beta1.ColumnSpec> columnSpecs_ = java.util.Collections.emptyList(); private void ensureColumnSpecsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { columnSpecs_ = new java.util.ArrayList<com.google.cloud.automl.v1beta1.ColumnSpec>(columnSpecs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.automl.v1beta1.ColumnSpec, com.google.cloud.automl.v1beta1.ColumnSpec.Builder, com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder> columnSpecsBuilder_; /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public java.util.List<com.google.cloud.automl.v1beta1.ColumnSpec> getColumnSpecsList() { if (columnSpecsBuilder_ == null) { return java.util.Collections.unmodifiableList(columnSpecs_); } else { return columnSpecsBuilder_.getMessageList(); } } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public int getColumnSpecsCount() { if (columnSpecsBuilder_ == null) { return columnSpecs_.size(); } else { return columnSpecsBuilder_.getCount(); } } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.ColumnSpec getColumnSpecs(int index) { if (columnSpecsBuilder_ == null) { return columnSpecs_.get(index); } else { return columnSpecsBuilder_.getMessage(index); } } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder setColumnSpecs(int index, com.google.cloud.automl.v1beta1.ColumnSpec value) { if (columnSpecsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureColumnSpecsIsMutable(); columnSpecs_.set(index, value); onChanged(); } else { columnSpecsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder setColumnSpecs( int index, com.google.cloud.automl.v1beta1.ColumnSpec.Builder builderForValue) { if (columnSpecsBuilder_ == null) { ensureColumnSpecsIsMutable(); columnSpecs_.set(index, builderForValue.build()); onChanged(); } else { columnSpecsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder addColumnSpecs(com.google.cloud.automl.v1beta1.ColumnSpec value) { if (columnSpecsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureColumnSpecsIsMutable(); columnSpecs_.add(value); onChanged(); } else { columnSpecsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder addColumnSpecs(int index, com.google.cloud.automl.v1beta1.ColumnSpec value) { if (columnSpecsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureColumnSpecsIsMutable(); columnSpecs_.add(index, value); onChanged(); } else { columnSpecsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder addColumnSpecs( com.google.cloud.automl.v1beta1.ColumnSpec.Builder builderForValue) { if (columnSpecsBuilder_ == null) { ensureColumnSpecsIsMutable(); columnSpecs_.add(builderForValue.build()); onChanged(); } else { columnSpecsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder addColumnSpecs( int index, com.google.cloud.automl.v1beta1.ColumnSpec.Builder builderForValue) { if (columnSpecsBuilder_ == null) { ensureColumnSpecsIsMutable(); columnSpecs_.add(index, builderForValue.build()); onChanged(); } else { columnSpecsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder addAllColumnSpecs( java.lang.Iterable<? extends com.google.cloud.automl.v1beta1.ColumnSpec> values) { if (columnSpecsBuilder_ == null) { ensureColumnSpecsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, columnSpecs_); onChanged(); } else { columnSpecsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder clearColumnSpecs() { if (columnSpecsBuilder_ == null) { columnSpecs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { columnSpecsBuilder_.clear(); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public Builder removeColumnSpecs(int index) { if (columnSpecsBuilder_ == null) { ensureColumnSpecsIsMutable(); columnSpecs_.remove(index); onChanged(); } else { columnSpecsBuilder_.remove(index); } return this; } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.ColumnSpec.Builder getColumnSpecsBuilder(int index) { return getColumnSpecsFieldBuilder().getBuilder(index); } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder getColumnSpecsOrBuilder(int index) { if (columnSpecsBuilder_ == null) { return columnSpecs_.get(index); } else { return columnSpecsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public java.util.List<? extends com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder> getColumnSpecsOrBuilderList() { if (columnSpecsBuilder_ != null) { return columnSpecsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(columnSpecs_); } } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.ColumnSpec.Builder addColumnSpecsBuilder() { return getColumnSpecsFieldBuilder() .addBuilder(com.google.cloud.automl.v1beta1.ColumnSpec.getDefaultInstance()); } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.ColumnSpec.Builder addColumnSpecsBuilder(int index) { return getColumnSpecsFieldBuilder() .addBuilder(index, com.google.cloud.automl.v1beta1.ColumnSpec.getDefaultInstance()); } /** * * * <pre> * The column specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.ColumnSpec column_specs = 1;</code> */ public java.util.List<com.google.cloud.automl.v1beta1.ColumnSpec.Builder> getColumnSpecsBuilderList() { return getColumnSpecsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.automl.v1beta1.ColumnSpec, com.google.cloud.automl.v1beta1.ColumnSpec.Builder, com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder> getColumnSpecsFieldBuilder() { if (columnSpecsBuilder_ == null) { columnSpecsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.automl.v1beta1.ColumnSpec, com.google.cloud.automl.v1beta1.ColumnSpec.Builder, com.google.cloud.automl.v1beta1.ColumnSpecOrBuilder>( columnSpecs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); columnSpecs_ = null; } return columnSpecsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListColumnSpecsRequest.page_token][google.cloud.automl.v1beta1.ListColumnSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.automl.v1beta1.ListColumnSpecsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.ListColumnSpecsResponse) private static final com.google.cloud.automl.v1beta1.ListColumnSpecsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.automl.v1beta1.ListColumnSpecsResponse(); } public static com.google.cloud.automl.v1beta1.ListColumnSpecsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListColumnSpecsResponse> PARSER = new com.google.protobuf.AbstractParser<ListColumnSpecsResponse>() { @java.lang.Override public ListColumnSpecsResponse 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<ListColumnSpecsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListColumnSpecsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListColumnSpecsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,798
java-container/proto-google-cloud-container-v1/src/main/java/com/google/container/v1/StatusCondition.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1; /** * * * <pre> * StatusCondition describes why a cluster or a node pool has a certain status * (e.g., ERROR or DEGRADED). * </pre> * * Protobuf type {@code google.container.v1.StatusCondition} */ public final class StatusCondition extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1.StatusCondition) StatusConditionOrBuilder { private static final long serialVersionUID = 0L; // Use StatusCondition.newBuilder() to construct. private StatusCondition(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private StatusCondition() { code_ = 0; message_ = ""; canonicalCode_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new StatusCondition(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_StatusCondition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_StatusCondition_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.StatusCondition.class, com.google.container.v1.StatusCondition.Builder.class); } /** * * * <pre> * Code for each condition * </pre> * * Protobuf enum {@code google.container.v1.StatusCondition.Code} */ public enum Code implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * UNKNOWN indicates a generic condition. * </pre> * * <code>UNKNOWN = 0;</code> */ UNKNOWN(0), /** * * * <pre> * GCE_STOCKOUT indicates that Google Compute Engine resources are * temporarily unavailable. * </pre> * * <code>GCE_STOCKOUT = 1;</code> */ GCE_STOCKOUT(1), /** * * * <pre> * GKE_SERVICE_ACCOUNT_DELETED indicates that the user deleted their robot * service account. * </pre> * * <code>GKE_SERVICE_ACCOUNT_DELETED = 2;</code> */ GKE_SERVICE_ACCOUNT_DELETED(2), /** * * * <pre> * Google Compute Engine quota was exceeded. * </pre> * * <code>GCE_QUOTA_EXCEEDED = 3;</code> */ GCE_QUOTA_EXCEEDED(3), /** * * * <pre> * Cluster state was manually changed by an SRE due to a system logic error. * </pre> * * <code>SET_BY_OPERATOR = 4;</code> */ SET_BY_OPERATOR(4), /** * * * <pre> * Unable to perform an encrypt operation against the CloudKMS key used for * etcd level encryption. * </pre> * * <code>CLOUD_KMS_KEY_ERROR = 7;</code> */ CLOUD_KMS_KEY_ERROR(7), /** * * * <pre> * Cluster CA is expiring soon. * </pre> * * <code>CA_EXPIRING = 9;</code> */ CA_EXPIRING(9), /** * * * <pre> * Node service account is missing permissions. * </pre> * * <code>NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS = 10;</code> */ NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS(10), /** * * * <pre> * Cloud KMS key version used for etcd level encryption has been destroyed. * This is a permanent error. * </pre> * * <code>CLOUD_KMS_KEY_DESTROYED = 11;</code> */ CLOUD_KMS_KEY_DESTROYED(11), UNRECOGNIZED(-1), ; /** * * * <pre> * UNKNOWN indicates a generic condition. * </pre> * * <code>UNKNOWN = 0;</code> */ public static final int UNKNOWN_VALUE = 0; /** * * * <pre> * GCE_STOCKOUT indicates that Google Compute Engine resources are * temporarily unavailable. * </pre> * * <code>GCE_STOCKOUT = 1;</code> */ public static final int GCE_STOCKOUT_VALUE = 1; /** * * * <pre> * GKE_SERVICE_ACCOUNT_DELETED indicates that the user deleted their robot * service account. * </pre> * * <code>GKE_SERVICE_ACCOUNT_DELETED = 2;</code> */ public static final int GKE_SERVICE_ACCOUNT_DELETED_VALUE = 2; /** * * * <pre> * Google Compute Engine quota was exceeded. * </pre> * * <code>GCE_QUOTA_EXCEEDED = 3;</code> */ public static final int GCE_QUOTA_EXCEEDED_VALUE = 3; /** * * * <pre> * Cluster state was manually changed by an SRE due to a system logic error. * </pre> * * <code>SET_BY_OPERATOR = 4;</code> */ public static final int SET_BY_OPERATOR_VALUE = 4; /** * * * <pre> * Unable to perform an encrypt operation against the CloudKMS key used for * etcd level encryption. * </pre> * * <code>CLOUD_KMS_KEY_ERROR = 7;</code> */ public static final int CLOUD_KMS_KEY_ERROR_VALUE = 7; /** * * * <pre> * Cluster CA is expiring soon. * </pre> * * <code>CA_EXPIRING = 9;</code> */ public static final int CA_EXPIRING_VALUE = 9; /** * * * <pre> * Node service account is missing permissions. * </pre> * * <code>NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS = 10;</code> */ public static final int NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS_VALUE = 10; /** * * * <pre> * Cloud KMS key version used for etcd level encryption has been destroyed. * This is a permanent error. * </pre> * * <code>CLOUD_KMS_KEY_DESTROYED = 11;</code> */ public static final int CLOUD_KMS_KEY_DESTROYED_VALUE = 11; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Code valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static Code forNumber(int value) { switch (value) { case 0: return UNKNOWN; case 1: return GCE_STOCKOUT; case 2: return GKE_SERVICE_ACCOUNT_DELETED; case 3: return GCE_QUOTA_EXCEEDED; case 4: return SET_BY_OPERATOR; case 7: return CLOUD_KMS_KEY_ERROR; case 9: return CA_EXPIRING; case 10: return NODE_SERVICE_ACCOUNT_MISSING_PERMISSIONS; case 11: return CLOUD_KMS_KEY_DESTROYED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Code> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Code> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Code>() { public Code findValueByNumber(int number) { return Code.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.container.v1.StatusCondition.getDescriptor().getEnumTypes().get(0); } private static final Code[] VALUES = values(); public static Code valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private Code(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.container.v1.StatusCondition.Code) } public static final int CODE_FIELD_NUMBER = 1; private int code_ = 0; /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @return The enum numeric value on the wire for code. */ @java.lang.Override @java.lang.Deprecated public int getCodeValue() { return code_; } /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @return The code. */ @java.lang.Override @java.lang.Deprecated public com.google.container.v1.StatusCondition.Code getCode() { com.google.container.v1.StatusCondition.Code result = com.google.container.v1.StatusCondition.Code.forNumber(code_); return result == null ? com.google.container.v1.StatusCondition.Code.UNRECOGNIZED : result; } public static final int MESSAGE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object message_ = ""; /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @return The message. */ @java.lang.Override public java.lang.String getMessage() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } } /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @return The bytes for message. */ @java.lang.Override public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CANONICAL_CODE_FIELD_NUMBER = 3; private int canonicalCode_ = 0; /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @return The enum numeric value on the wire for canonicalCode. */ @java.lang.Override public int getCanonicalCodeValue() { return canonicalCode_; } /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @return The canonicalCode. */ @java.lang.Override public com.google.rpc.Code getCanonicalCode() { com.google.rpc.Code result = com.google.rpc.Code.forNumber(canonicalCode_); return result == null ? com.google.rpc.Code.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (code_ != com.google.container.v1.StatusCondition.Code.UNKNOWN.getNumber()) { output.writeEnum(1, code_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, message_); } if (canonicalCode_ != com.google.rpc.Code.OK.getNumber()) { output.writeEnum(3, canonicalCode_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (code_ != com.google.container.v1.StatusCondition.Code.UNKNOWN.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, code_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(message_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, message_); } if (canonicalCode_ != com.google.rpc.Code.OK.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, canonicalCode_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1.StatusCondition)) { return super.equals(obj); } com.google.container.v1.StatusCondition other = (com.google.container.v1.StatusCondition) obj; if (code_ != other.code_) return false; if (!getMessage().equals(other.getMessage())) return false; if (canonicalCode_ != other.canonicalCode_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CODE_FIELD_NUMBER; hash = (53 * hash) + code_; hash = (37 * hash) + MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getMessage().hashCode(); hash = (37 * hash) + CANONICAL_CODE_FIELD_NUMBER; hash = (53 * hash) + canonicalCode_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1.StatusCondition parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.StatusCondition parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.StatusCondition parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.StatusCondition parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.StatusCondition parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.StatusCondition parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.StatusCondition parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.StatusCondition parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.StatusCondition parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1.StatusCondition parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.StatusCondition parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.StatusCondition parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1.StatusCondition prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * StatusCondition describes why a cluster or a node pool has a certain status * (e.g., ERROR or DEGRADED). * </pre> * * Protobuf type {@code google.container.v1.StatusCondition} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1.StatusCondition) com.google.container.v1.StatusConditionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_StatusCondition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_StatusCondition_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.StatusCondition.class, com.google.container.v1.StatusCondition.Builder.class); } // Construct using com.google.container.v1.StatusCondition.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; code_ = 0; message_ = ""; canonicalCode_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_StatusCondition_descriptor; } @java.lang.Override public com.google.container.v1.StatusCondition getDefaultInstanceForType() { return com.google.container.v1.StatusCondition.getDefaultInstance(); } @java.lang.Override public com.google.container.v1.StatusCondition build() { com.google.container.v1.StatusCondition result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1.StatusCondition buildPartial() { com.google.container.v1.StatusCondition result = new com.google.container.v1.StatusCondition(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.container.v1.StatusCondition result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.code_ = code_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.message_ = message_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.canonicalCode_ = canonicalCode_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1.StatusCondition) { return mergeFrom((com.google.container.v1.StatusCondition) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1.StatusCondition other) { if (other == com.google.container.v1.StatusCondition.getDefaultInstance()) return this; if (other.code_ != 0) { setCodeValue(other.getCodeValue()); } if (!other.getMessage().isEmpty()) { message_ = other.message_; bitField0_ |= 0x00000002; onChanged(); } if (other.canonicalCode_ != 0) { setCanonicalCodeValue(other.getCanonicalCodeValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { code_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { message_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { canonicalCode_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int code_ = 0; /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @return The enum numeric value on the wire for code. */ @java.lang.Override @java.lang.Deprecated public int getCodeValue() { return code_; } /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @param value The enum numeric value on the wire for code to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setCodeValue(int value) { code_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @return The code. */ @java.lang.Override @java.lang.Deprecated public com.google.container.v1.StatusCondition.Code getCode() { com.google.container.v1.StatusCondition.Code result = com.google.container.v1.StatusCondition.Code.forNumber(code_); return result == null ? com.google.container.v1.StatusCondition.Code.UNRECOGNIZED : result; } /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @param value The code to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setCode(com.google.container.v1.StatusCondition.Code value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; code_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Machine-friendly representation of the condition * Deprecated. Use canonical_code instead. * </pre> * * <code>.google.container.v1.StatusCondition.Code code = 1 [deprecated = true];</code> * * @deprecated google.container.v1.StatusCondition.code is deprecated. See * google/container/v1/cluster_service.proto;l=5401 * @return This builder for chaining. */ @java.lang.Deprecated public Builder clearCode() { bitField0_ = (bitField0_ & ~0x00000001); code_ = 0; onChanged(); return this; } private java.lang.Object message_ = ""; /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @return The message. */ public java.lang.String getMessage() { java.lang.Object ref = message_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); message_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @return The bytes for message. */ public com.google.protobuf.ByteString getMessageBytes() { java.lang.Object ref = message_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); message_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @param value The message to set. * @return This builder for chaining. */ public Builder setMessage(java.lang.String value) { if (value == null) { throw new NullPointerException(); } message_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @return This builder for chaining. */ public Builder clearMessage() { message_ = getDefaultInstance().getMessage(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Human-friendly representation of the condition * </pre> * * <code>string message = 2;</code> * * @param value The bytes for message to set. * @return This builder for chaining. */ public Builder setMessageBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); message_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int canonicalCode_ = 0; /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @return The enum numeric value on the wire for canonicalCode. */ @java.lang.Override public int getCanonicalCodeValue() { return canonicalCode_; } /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @param value The enum numeric value on the wire for canonicalCode to set. * @return This builder for chaining. */ public Builder setCanonicalCodeValue(int value) { canonicalCode_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @return The canonicalCode. */ @java.lang.Override public com.google.rpc.Code getCanonicalCode() { com.google.rpc.Code result = com.google.rpc.Code.forNumber(canonicalCode_); return result == null ? com.google.rpc.Code.UNRECOGNIZED : result; } /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @param value The canonicalCode to set. * @return This builder for chaining. */ public Builder setCanonicalCode(com.google.rpc.Code value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; canonicalCode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Canonical code of the condition. * </pre> * * <code>.google.rpc.Code canonical_code = 3;</code> * * @return This builder for chaining. */ public Builder clearCanonicalCode() { bitField0_ = (bitField0_ & ~0x00000004); canonicalCode_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1.StatusCondition) } // @@protoc_insertion_point(class_scope:google.container.v1.StatusCondition) private static final com.google.container.v1.StatusCondition DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1.StatusCondition(); } public static com.google.container.v1.StatusCondition getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<StatusCondition> PARSER = new com.google.protobuf.AbstractParser<StatusCondition>() { @java.lang.Override public StatusCondition parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<StatusCondition> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<StatusCondition> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1.StatusCondition getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,822
java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/SecurityPostureConfig.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1beta1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1beta1; /** * * * <pre> * SecurityPostureConfig defines the flags needed to enable/disable features for * the Security Posture API. * </pre> * * Protobuf type {@code google.container.v1beta1.SecurityPostureConfig} */ public final class SecurityPostureConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1beta1.SecurityPostureConfig) SecurityPostureConfigOrBuilder { private static final long serialVersionUID = 0L; // Use SecurityPostureConfig.newBuilder() to construct. private SecurityPostureConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SecurityPostureConfig() { mode_ = 0; vulnerabilityMode_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SecurityPostureConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_SecurityPostureConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_SecurityPostureConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.SecurityPostureConfig.class, com.google.container.v1beta1.SecurityPostureConfig.Builder.class); } /** * * * <pre> * Mode defines enablement mode for GKE Security posture features. * </pre> * * Protobuf enum {@code google.container.v1beta1.SecurityPostureConfig.Mode} */ public enum Mode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default value not specified. * </pre> * * <code>MODE_UNSPECIFIED = 0;</code> */ MODE_UNSPECIFIED(0), /** * * * <pre> * Disables Security Posture features on the cluster. * </pre> * * <code>DISABLED = 1;</code> */ DISABLED(1), /** * * * <pre> * Applies Security Posture features on the cluster. * </pre> * * <code>BASIC = 2;</code> */ BASIC(2), /** * * * <pre> * Applies the Security Posture off cluster Enterprise level features. * </pre> * * <code>ENTERPRISE = 3;</code> */ ENTERPRISE(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Default value not specified. * </pre> * * <code>MODE_UNSPECIFIED = 0;</code> */ public static final int MODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Disables Security Posture features on the cluster. * </pre> * * <code>DISABLED = 1;</code> */ public static final int DISABLED_VALUE = 1; /** * * * <pre> * Applies Security Posture features on the cluster. * </pre> * * <code>BASIC = 2;</code> */ public static final int BASIC_VALUE = 2; /** * * * <pre> * Applies the Security Posture off cluster Enterprise level features. * </pre> * * <code>ENTERPRISE = 3;</code> */ public static final int ENTERPRISE_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 Mode 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 Mode forNumber(int value) { switch (value) { case 0: return MODE_UNSPECIFIED; case 1: return DISABLED; case 2: return BASIC; case 3: return ENTERPRISE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Mode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Mode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Mode>() { public Mode findValueByNumber(int number) { return Mode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.container.v1beta1.SecurityPostureConfig.getDescriptor() .getEnumTypes() .get(0); } private static final Mode[] VALUES = values(); public static Mode 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 Mode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.container.v1beta1.SecurityPostureConfig.Mode) } /** * * * <pre> * VulnerabilityMode defines enablement mode for vulnerability scanning. * </pre> * * Protobuf enum {@code google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode} */ public enum VulnerabilityMode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default value not specified. * </pre> * * <code>VULNERABILITY_MODE_UNSPECIFIED = 0;</code> */ VULNERABILITY_MODE_UNSPECIFIED(0), /** * * * <pre> * Disables vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_DISABLED = 1;</code> */ VULNERABILITY_DISABLED(1), /** * * * <pre> * Applies basic vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_BASIC = 2;</code> */ VULNERABILITY_BASIC(2), /** * * * <pre> * Applies the Security Posture's vulnerability on cluster Enterprise level * features. * </pre> * * <code>VULNERABILITY_ENTERPRISE = 3;</code> */ VULNERABILITY_ENTERPRISE(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Default value not specified. * </pre> * * <code>VULNERABILITY_MODE_UNSPECIFIED = 0;</code> */ public static final int VULNERABILITY_MODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Disables vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_DISABLED = 1;</code> */ public static final int VULNERABILITY_DISABLED_VALUE = 1; /** * * * <pre> * Applies basic vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_BASIC = 2;</code> */ public static final int VULNERABILITY_BASIC_VALUE = 2; /** * * * <pre> * Applies the Security Posture's vulnerability on cluster Enterprise level * features. * </pre> * * <code>VULNERABILITY_ENTERPRISE = 3;</code> */ public static final int VULNERABILITY_ENTERPRISE_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 VulnerabilityMode 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 VulnerabilityMode forNumber(int value) { switch (value) { case 0: return VULNERABILITY_MODE_UNSPECIFIED; case 1: return VULNERABILITY_DISABLED; case 2: return VULNERABILITY_BASIC; case 3: return VULNERABILITY_ENTERPRISE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<VulnerabilityMode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<VulnerabilityMode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<VulnerabilityMode>() { public VulnerabilityMode findValueByNumber(int number) { return VulnerabilityMode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.container.v1beta1.SecurityPostureConfig.getDescriptor() .getEnumTypes() .get(1); } private static final VulnerabilityMode[] VALUES = values(); public static VulnerabilityMode 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 VulnerabilityMode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode) } private int bitField0_; public static final int MODE_FIELD_NUMBER = 1; private int mode_ = 0; /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return Whether the mode field is set. */ @java.lang.Override public boolean hasMode() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The enum numeric value on the wire for mode. */ @java.lang.Override public int getModeValue() { return mode_; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The mode. */ @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig.Mode getMode() { com.google.container.v1beta1.SecurityPostureConfig.Mode result = com.google.container.v1beta1.SecurityPostureConfig.Mode.forNumber(mode_); return result == null ? com.google.container.v1beta1.SecurityPostureConfig.Mode.UNRECOGNIZED : result; } public static final int VULNERABILITY_MODE_FIELD_NUMBER = 2; private int vulnerabilityMode_ = 0; /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return Whether the vulnerabilityMode field is set. */ @java.lang.Override public boolean hasVulnerabilityMode() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The enum numeric value on the wire for vulnerabilityMode. */ @java.lang.Override public int getVulnerabilityModeValue() { return vulnerabilityMode_; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The vulnerabilityMode. */ @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode getVulnerabilityMode() { com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode result = com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode.forNumber( vulnerabilityMode_); return result == null ? com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeEnum(1, mode_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeEnum(2, vulnerabilityMode_); } 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.computeEnumSize(1, mode_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, vulnerabilityMode_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1beta1.SecurityPostureConfig)) { return super.equals(obj); } com.google.container.v1beta1.SecurityPostureConfig other = (com.google.container.v1beta1.SecurityPostureConfig) obj; if (hasMode() != other.hasMode()) return false; if (hasMode()) { if (mode_ != other.mode_) return false; } if (hasVulnerabilityMode() != other.hasVulnerabilityMode()) return false; if (hasVulnerabilityMode()) { if (vulnerabilityMode_ != other.vulnerabilityMode_) 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 (hasMode()) { hash = (37 * hash) + MODE_FIELD_NUMBER; hash = (53 * hash) + mode_; } if (hasVulnerabilityMode()) { hash = (37 * hash) + VULNERABILITY_MODE_FIELD_NUMBER; hash = (53 * hash) + vulnerabilityMode_; } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.SecurityPostureConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1beta1.SecurityPostureConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.SecurityPostureConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1beta1.SecurityPostureConfig 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> * SecurityPostureConfig defines the flags needed to enable/disable features for * the Security Posture API. * </pre> * * Protobuf type {@code google.container.v1beta1.SecurityPostureConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1beta1.SecurityPostureConfig) com.google.container.v1beta1.SecurityPostureConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_SecurityPostureConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_SecurityPostureConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.SecurityPostureConfig.class, com.google.container.v1beta1.SecurityPostureConfig.Builder.class); } // Construct using com.google.container.v1beta1.SecurityPostureConfig.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; mode_ = 0; vulnerabilityMode_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_SecurityPostureConfig_descriptor; } @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig getDefaultInstanceForType() { return com.google.container.v1beta1.SecurityPostureConfig.getDefaultInstance(); } @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig build() { com.google.container.v1beta1.SecurityPostureConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig buildPartial() { com.google.container.v1beta1.SecurityPostureConfig result = new com.google.container.v1beta1.SecurityPostureConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.container.v1beta1.SecurityPostureConfig result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.mode_ = mode_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.vulnerabilityMode_ = vulnerabilityMode_; 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.container.v1beta1.SecurityPostureConfig) { return mergeFrom((com.google.container.v1beta1.SecurityPostureConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1beta1.SecurityPostureConfig other) { if (other == com.google.container.v1beta1.SecurityPostureConfig.getDefaultInstance()) return this; if (other.hasMode()) { setMode(other.getMode()); } if (other.hasVulnerabilityMode()) { setVulnerabilityMode(other.getVulnerabilityMode()); } 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: { mode_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { vulnerabilityMode_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int mode_ = 0; /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return Whether the mode field is set. */ @java.lang.Override public boolean hasMode() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The enum numeric value on the wire for mode. */ @java.lang.Override public int getModeValue() { return mode_; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @param value The enum numeric value on the wire for mode to set. * @return This builder for chaining. */ public Builder setModeValue(int value) { mode_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The mode. */ @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig.Mode getMode() { com.google.container.v1beta1.SecurityPostureConfig.Mode result = com.google.container.v1beta1.SecurityPostureConfig.Mode.forNumber(mode_); return result == null ? com.google.container.v1beta1.SecurityPostureConfig.Mode.UNRECOGNIZED : result; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @param value The mode to set. * @return This builder for chaining. */ public Builder setMode(com.google.container.v1beta1.SecurityPostureConfig.Mode value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; mode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1beta1.SecurityPostureConfig.Mode mode = 1;</code> * * @return This builder for chaining. */ public Builder clearMode() { bitField0_ = (bitField0_ & ~0x00000001); mode_ = 0; onChanged(); return this; } private int vulnerabilityMode_ = 0; /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return Whether the vulnerabilityMode field is set. */ @java.lang.Override public boolean hasVulnerabilityMode() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The enum numeric value on the wire for vulnerabilityMode. */ @java.lang.Override public int getVulnerabilityModeValue() { return vulnerabilityMode_; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @param value The enum numeric value on the wire for vulnerabilityMode to set. * @return This builder for chaining. */ public Builder setVulnerabilityModeValue(int value) { vulnerabilityMode_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The vulnerabilityMode. */ @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode getVulnerabilityMode() { com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode result = com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode.forNumber( vulnerabilityMode_); return result == null ? com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode.UNRECOGNIZED : result; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @param value The vulnerabilityMode to set. * @return This builder for chaining. */ public Builder setVulnerabilityMode( com.google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; vulnerabilityMode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1beta1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return This builder for chaining. */ public Builder clearVulnerabilityMode() { bitField0_ = (bitField0_ & ~0x00000002); vulnerabilityMode_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1beta1.SecurityPostureConfig) } // @@protoc_insertion_point(class_scope:google.container.v1beta1.SecurityPostureConfig) private static final com.google.container.v1beta1.SecurityPostureConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1beta1.SecurityPostureConfig(); } public static com.google.container.v1beta1.SecurityPostureConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SecurityPostureConfig> PARSER = new com.google.protobuf.AbstractParser<SecurityPostureConfig>() { @java.lang.Override public SecurityPostureConfig 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<SecurityPostureConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SecurityPostureConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1beta1.SecurityPostureConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,874
java-dataform/proto-google-cloud-dataform-v1/src/main/java/com/google/cloud/dataform/v1/SearchFilesRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataform/v1/dataform.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataform.v1; /** * * * <pre> * Configuration containing file search request parameters. * </pre> * * Protobuf type {@code google.cloud.dataform.v1.SearchFilesRequest} */ public final class SearchFilesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataform.v1.SearchFilesRequest) SearchFilesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SearchFilesRequest.newBuilder() to construct. private SearchFilesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchFilesRequest() { workspace_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchFilesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_SearchFilesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_SearchFilesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataform.v1.SearchFilesRequest.class, com.google.cloud.dataform.v1.SearchFilesRequest.Builder.class); } public static final int WORKSPACE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object workspace_ = ""; /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The workspace. */ @java.lang.Override public java.lang.String getWorkspace() { java.lang.Object ref = workspace_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workspace_ = s; return s; } } /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for workspace. */ @java.lang.Override public com.google.protobuf.ByteString getWorkspaceBytes() { java.lang.Object ref = workspace_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workspace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. Maximum number of search results to return. The server may return * fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </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(workspace_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, workspace_); } 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(workspace_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, workspace_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataform.v1.SearchFilesRequest)) { return super.equals(obj); } com.google.cloud.dataform.v1.SearchFilesRequest other = (com.google.cloud.dataform.v1.SearchFilesRequest) obj; if (!getWorkspace().equals(other.getWorkspace())) 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) + WORKSPACE_FIELD_NUMBER; hash = (53 * hash) + getWorkspace().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1.SearchFilesRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataform.v1.SearchFilesRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Configuration containing file search request parameters. * </pre> * * Protobuf type {@code google.cloud.dataform.v1.SearchFilesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataform.v1.SearchFilesRequest) com.google.cloud.dataform.v1.SearchFilesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_SearchFilesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_SearchFilesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataform.v1.SearchFilesRequest.class, com.google.cloud.dataform.v1.SearchFilesRequest.Builder.class); } // Construct using com.google.cloud.dataform.v1.SearchFilesRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; workspace_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_SearchFilesRequest_descriptor; } @java.lang.Override public com.google.cloud.dataform.v1.SearchFilesRequest getDefaultInstanceForType() { return com.google.cloud.dataform.v1.SearchFilesRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataform.v1.SearchFilesRequest build() { com.google.cloud.dataform.v1.SearchFilesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataform.v1.SearchFilesRequest buildPartial() { com.google.cloud.dataform.v1.SearchFilesRequest result = new com.google.cloud.dataform.v1.SearchFilesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dataform.v1.SearchFilesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.workspace_ = workspace_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dataform.v1.SearchFilesRequest) { return mergeFrom((com.google.cloud.dataform.v1.SearchFilesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataform.v1.SearchFilesRequest other) { if (other == com.google.cloud.dataform.v1.SearchFilesRequest.getDefaultInstance()) return this; if (!other.getWorkspace().isEmpty()) { workspace_ = other.workspace_; 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: { workspace_ = 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 workspace_ = ""; /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The workspace. */ public java.lang.String getWorkspace() { java.lang.Object ref = workspace_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workspace_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for workspace. */ public com.google.protobuf.ByteString getWorkspaceBytes() { java.lang.Object ref = workspace_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workspace_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The workspace to set. * @return This builder for chaining. */ public Builder setWorkspace(java.lang.String value) { if (value == null) { throw new NullPointerException(); } workspace_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearWorkspace() { workspace_ = getDefaultInstance().getWorkspace(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The workspace's name. * </pre> * * <code> * string workspace = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for workspace to set. * @return This builder for chaining. */ public Builder setWorkspaceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); workspace_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Maximum number of search results to return. The server may return * fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Maximum number of search results to return. The server may return * fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Maximum number of search results to return. The server may return * fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. Page token received from a previous `SearchFilesRequest` * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `SearchFilesRequest`, * with the exception of `page_size`, must match the call that provided the * page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. Optional filter for the returned list in filtering format. * Filtering is only currently supported on the `path` field. * See https://google.aip.dev/160 for details. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataform.v1.SearchFilesRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dataform.v1.SearchFilesRequest) private static final com.google.cloud.dataform.v1.SearchFilesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataform.v1.SearchFilesRequest(); } public static com.google.cloud.dataform.v1.SearchFilesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchFilesRequest> PARSER = new com.google.protobuf.AbstractParser<SearchFilesRequest>() { @java.lang.Override public SearchFilesRequest 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<SearchFilesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchFilesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataform.v1.SearchFilesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/jmeter
36,941
src/core/src/main/java/org/apache/jmeter/samplers/SampleSaveConfiguration.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.jmeter.samplers; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Properties; import org.apache.jmeter.save.CSVSaveService; import org.apache.jmeter.testelement.TestPlan; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.util.CharUtils; import org.apache.jorphan.util.JMeterError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * N.B. to add a new field, remember the following * - static _xyz * - instance xyz=_xyz * - clone s.xyz = xyz (perhaps) * - setXyz(boolean) * - saveXyz() * - add Xyz to SAVE_CONFIG_NAMES list * - update SampleSaveConfigurationConverter to add new fields to marshall() and shouldSerialiseMember() * - update ctor SampleSaveConfiguration(boolean value) to set the value if it is a boolean property * - update SampleResultConverter and/or HTTPSampleConverter * - update CSVSaveService: CSV_XXXX, makeResultFromDelimitedString, printableFieldNamesToString, static{} * - update messages.properties to add save_xyz entry * - update jmeter.properties to add new property * - update listeners.xml to add new property, CSV and XML names etc. * - take screenshot sample_result_config.png * - update listeners.xml and component_reference.xml with new dimensions (might not change) */ /** * Holds details of which sample attributes to save. * * The pop-up dialogue for this is created by the class SavePropertyDialog, which assumes: * <p> * For each field <em>XXX</em> * <ul> * <li>methods have the signature "boolean save<em>XXX</em>()"</li> * <li>a corresponding "void set<em>XXX</em>(boolean)" method</li> * <li>messages.properties contains the key save_<em>XXX</em></li> * </ul> */ public class SampleSaveConfiguration implements Cloneable, Serializable { private static final long serialVersionUID = 8L; private static final Logger log = LoggerFactory.getLogger(SampleSaveConfiguration.class); // --------------------------------------------------------------------- // PROPERTY FILE CONSTANTS // --------------------------------------------------------------------- /** Indicates that the results file should be in XML format. * */ private static final String XML = "xml"; // $NON_NLS-1$ /** Indicates that the results file should be in CSV format. * */ private static final String CSV = "csv"; // $NON_NLS-1$ /** A properties file indicator for true. * */ private static final String TRUE = "true"; // $NON_NLS-1$ /** A properties file indicator for false. * */ private static final String FALSE = "false"; // $NON_NLS-1$ /** A properties file indicator for milliseconds. * */ public static final String MILLISECONDS = "ms"; // $NON_NLS-1$ /** A properties file indicator for none. * */ public static final String NONE = "none"; // $NON_NLS-1$ /** A properties file indicator for the first of a series. * */ private static final String FIRST = "first"; // $NON_NLS-1$ /** A properties file indicator for all of a series. * */ private static final String ALL = "all"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating which assertion results should be * saved. **************************************************************************/ public static final String ASSERTION_RESULTS_FAILURE_MESSAGE_PROP = "jmeter.save.saveservice.assertion_results_failure_message"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating which assertion results should be * saved. **************************************************************************/ private static final String ASSERTION_RESULTS_PROP = "jmeter.save.saveservice.assertion_results"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating which delimiter should be used when * saving in a delimited values format. **************************************************************************/ public static final String DEFAULT_DELIMITER_PROP = "jmeter.save.saveservice.default_delimiter"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating which format should be used when * saving the results, e.g., xml or csv. **************************************************************************/ private static final String OUTPUT_FORMAT_PROP = "jmeter.save.saveservice.output_format"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether field names should be printed * to a delimited file. **************************************************************************/ private static final String PRINT_FIELD_NAMES_PROP = "jmeter.save.saveservice.print_field_names"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the data type should be * saved. **************************************************************************/ private static final String SAVE_DATA_TYPE_PROP = "jmeter.save.saveservice.data_type"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the label should be saved. **************************************************************************/ private static final String SAVE_LABEL_PROP = "jmeter.save.saveservice.label"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the response code should be * saved. **************************************************************************/ private static final String SAVE_RESPONSE_CODE_PROP = "jmeter.save.saveservice.response_code"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the response data should be * saved. **************************************************************************/ private static final String SAVE_RESPONSE_DATA_PROP = "jmeter.save.saveservice.response_data"; // $NON_NLS-1$ private static final String SAVE_RESPONSE_DATA_ON_ERROR_PROP = "jmeter.save.saveservice.response_data.on_error"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the response message should * be saved. **************************************************************************/ private static final String SAVE_RESPONSE_MESSAGE_PROP = "jmeter.save.saveservice.response_message"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the success indicator should * be saved. **************************************************************************/ private static final String SAVE_SUCCESSFUL_PROP = "jmeter.save.saveservice.successful"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the thread name should be * saved. **************************************************************************/ private static final String SAVE_THREAD_NAME_PROP = "jmeter.save.saveservice.thread_name"; // $NON_NLS-1$ // Save bytes read private static final String SAVE_BYTES_PROP = "jmeter.save.saveservice.bytes"; // $NON_NLS-1$ // Save bytes written private static final String SAVE_SENT_BYTES_PROP = "jmeter.save.saveservice.sent_bytes"; // $NON_NLS-1$ // Save URL private static final String SAVE_URL_PROP = "jmeter.save.saveservice.url"; // $NON_NLS-1$ // Save fileName for ResultSaver private static final String SAVE_FILENAME_PROP = "jmeter.save.saveservice.filename"; // $NON_NLS-1$ // Save hostname for ResultSaver private static final String SAVE_HOSTNAME_PROP = "jmeter.save.saveservice.hostname"; // $NON_NLS-1$ /*************************************************************************** * The name of the property indicating whether the time should be saved. **************************************************************************/ private static final String SAVE_TIME_PROP = "jmeter.save.saveservice.time"; // $NON_NLS-1$ /*************************************************************************** * The name of the property giving the format of the time stamp **************************************************************************/ private static final String TIME_STAMP_FORMAT_PROP = "jmeter.save.saveservice.timestamp_format"; // $NON_NLS-1$ private static final String SUBRESULTS_PROP = "jmeter.save.saveservice.subresults"; // $NON_NLS-1$ private static final String ASSERTIONS_PROP = "jmeter.save.saveservice.assertions"; // $NON_NLS-1$ private static final String LATENCY_PROP = "jmeter.save.saveservice.latency"; // $NON_NLS-1$ private static final String CONNECT_TIME_PROP = "jmeter.save.saveservice.connect_time"; // $NON_NLS-1$ private static final String SAMPLERDATA_PROP = "jmeter.save.saveservice.samplerData"; // $NON_NLS-1$ private static final String RESPONSEHEADERS_PROP = "jmeter.save.saveservice.responseHeaders"; // $NON_NLS-1$ private static final String REQUESTHEADERS_PROP = "jmeter.save.saveservice.requestHeaders"; // $NON_NLS-1$ private static final String ENCODING_PROP = "jmeter.save.saveservice.encoding"; // $NON_NLS-1$ // optional processing instruction for line 2; e.g. // <?xml-stylesheet type="text/xsl" href="../extras/jmeter-results-detail-report_21.xsl"?> private static final String XML_PI = "jmeter.save.saveservice.xml_pi"; // $NON_NLS-1$ private static final String SAVE_THREAD_COUNTS = "jmeter.save.saveservice.thread_counts"; // $NON_NLS-1$ private static final String SAVE_SAMPLE_COUNT = "jmeter.save.saveservice.sample_count"; // $NON_NLS-1$ private static final String SAVE_IDLE_TIME = "jmeter.save.saveservice.idle_time"; // $NON_NLS-1$ // Defaults from properties: private static final boolean TIME; private static final boolean TIMESTAMP; private static final boolean SUCCESS; private static final boolean LABEL; private static final boolean CODE; private static final boolean MESSAGE; private static final boolean THREAD_NAME; private static final boolean IS_XML; private static final boolean RESPONSE_DATA; private static final boolean DATATYPE; private static final boolean ENCODING; private static final boolean ASSERTIONS; private static final boolean LATENCY; private static final boolean CONNECT_TIME; private static final boolean SUB_RESULTS; private static final boolean SAMPLER_DATA; private static final boolean FIELD_NAMES; private static final boolean RESPONSE_HEADERS; private static final boolean REQUEST_HEADERS; private static final boolean RESPONSE_DATA_ON_ERROR; private static final boolean SAVE_ASSERTION_RESULTS_FAILURE_MESSAGE; private static final int ASSERTIONS_RESULT_TO_SAVE; // TODO turn into method? public static final int SAVE_NO_ASSERTIONS = 0; public static final int SAVE_FIRST_ASSERTION = SAVE_NO_ASSERTIONS + 1; public static final int SAVE_ALL_ASSERTIONS = SAVE_FIRST_ASSERTION + 1; private static final boolean PRINT_MILLISECONDS; private static final boolean BYTES; private static final boolean SENT_BYTES; private static final boolean URL; private static final boolean FILE_NAME; private static final boolean HOST_NAME; private static final boolean THREAD_COUNTS; private static final boolean SAMPLE_COUNT; private static final String DATE_FORMAT; /** * The string used to separate fields when stored to disk, for example, the * comma for CSV files. */ private static final String DELIMITER; private static final boolean IDLE_TIME; public static final String DEFAULT_DELIMITER = ","; // $NON_NLS-1$ // Read in the properties having to do with saving from a properties file. static { Properties props = JMeterUtils.getJMeterProperties(); if (props == null) { // If properties are not initialized, proceed with defaults props = new Properties(); } SUB_RESULTS = TRUE.equalsIgnoreCase(props.getProperty(SUBRESULTS_PROP, TRUE)); ASSERTIONS = TRUE.equalsIgnoreCase(props.getProperty(ASSERTIONS_PROP, TRUE)); LATENCY = TRUE.equalsIgnoreCase(props.getProperty(LATENCY_PROP, TRUE)); CONNECT_TIME = TRUE.equalsIgnoreCase(props.getProperty(CONNECT_TIME_PROP, TRUE)); SAMPLER_DATA = TRUE.equalsIgnoreCase(props.getProperty(SAMPLERDATA_PROP, FALSE)); RESPONSE_HEADERS = TRUE.equalsIgnoreCase(props.getProperty(RESPONSEHEADERS_PROP, FALSE)); REQUEST_HEADERS = TRUE.equalsIgnoreCase(props.getProperty(REQUESTHEADERS_PROP, FALSE)); ENCODING = TRUE.equalsIgnoreCase(props.getProperty(ENCODING_PROP, FALSE)); String dlm = JMeterUtils.getDelimiter(props.getProperty(DEFAULT_DELIMITER_PROP, DEFAULT_DELIMITER)); char ch = dlm.charAt(0); if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == CSVSaveService.QUOTING_CHAR){ throw new JMeterError("Delimiter '"+ch+"' must not be alphanumeric or "+CSVSaveService.QUOTING_CHAR+"."); } if (ch != '\t' && !CharUtils.isAscii(ch)){ throw new JMeterError("Delimiter (code "+(int)ch+") must be printable."); } DELIMITER = dlm; FIELD_NAMES = TRUE.equalsIgnoreCase(props.getProperty(PRINT_FIELD_NAMES_PROP, TRUE)); DATATYPE = TRUE.equalsIgnoreCase(props.getProperty(SAVE_DATA_TYPE_PROP, TRUE)); LABEL = TRUE.equalsIgnoreCase(props.getProperty(SAVE_LABEL_PROP, TRUE)); CODE = TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_CODE_PROP, TRUE)); RESPONSE_DATA = TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_DATA_PROP, FALSE)); RESPONSE_DATA_ON_ERROR = TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_DATA_ON_ERROR_PROP, FALSE)); MESSAGE = TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_MESSAGE_PROP, TRUE)); SUCCESS = TRUE.equalsIgnoreCase(props.getProperty(SAVE_SUCCESSFUL_PROP, TRUE)); THREAD_NAME = TRUE.equalsIgnoreCase(props.getProperty(SAVE_THREAD_NAME_PROP, TRUE)); BYTES = TRUE.equalsIgnoreCase(props.getProperty(SAVE_BYTES_PROP, TRUE)); SENT_BYTES = TRUE.equalsIgnoreCase(props.getProperty(SAVE_SENT_BYTES_PROP, TRUE)); URL = TRUE.equalsIgnoreCase(props.getProperty(SAVE_URL_PROP, TRUE)); FILE_NAME = TRUE.equalsIgnoreCase(props.getProperty(SAVE_FILENAME_PROP, FALSE)); HOST_NAME = TRUE.equalsIgnoreCase(props.getProperty(SAVE_HOSTNAME_PROP, FALSE)); TIME = TRUE.equalsIgnoreCase(props.getProperty(SAVE_TIME_PROP, TRUE)); String temporaryTimestampFormat = props.getProperty(TIME_STAMP_FORMAT_PROP, MILLISECONDS); PRINT_MILLISECONDS = MILLISECONDS.equalsIgnoreCase(temporaryTimestampFormat); if (!PRINT_MILLISECONDS && !NONE.equalsIgnoreCase(temporaryTimestampFormat)) { DATE_FORMAT = validateFormat(temporaryTimestampFormat); } else { DATE_FORMAT = null; } TIMESTAMP = !NONE.equalsIgnoreCase(temporaryTimestampFormat);// reversed compare allows for null SAVE_ASSERTION_RESULTS_FAILURE_MESSAGE = TRUE.equalsIgnoreCase(props.getProperty( ASSERTION_RESULTS_FAILURE_MESSAGE_PROP, TRUE)); String whichAssertionResults = props.getProperty(ASSERTION_RESULTS_PROP, NONE); if (NONE.equals(whichAssertionResults)) { ASSERTIONS_RESULT_TO_SAVE = SAVE_NO_ASSERTIONS; } else if (FIRST.equals(whichAssertionResults)) { ASSERTIONS_RESULT_TO_SAVE = SAVE_FIRST_ASSERTION; } else if (ALL.equals(whichAssertionResults)) { ASSERTIONS_RESULT_TO_SAVE = SAVE_ALL_ASSERTIONS; } else { ASSERTIONS_RESULT_TO_SAVE = 0; } String howToSave = props.getProperty(OUTPUT_FORMAT_PROP, CSV); if (XML.equals(howToSave)) { IS_XML = true; } else { if (!CSV.equals(howToSave)) { log.warn("{} has unexpected value: '{}' - assuming 'csv' format", OUTPUT_FORMAT_PROP, howToSave); } IS_XML = false; } THREAD_COUNTS=TRUE.equalsIgnoreCase(props.getProperty(SAVE_THREAD_COUNTS, TRUE)); SAMPLE_COUNT=TRUE.equalsIgnoreCase(props.getProperty(SAVE_SAMPLE_COUNT, FALSE)); IDLE_TIME=TRUE.equalsIgnoreCase(props.getProperty(SAVE_IDLE_TIME, TRUE)); } private static final SampleSaveConfiguration STATIC_SAVE_CONFIGURATION = new SampleSaveConfiguration(); // for test code only static final String CONFIG_GETTER_PREFIX = "save"; // $NON-NLS-1$ // for test code only static final String CONFIG_SETTER_PREFIX = "set"; // $NON-NLS-1$ /** * List of saveXXX/setXXX(boolean) methods which is used to build the Sample Result Save Configuration dialog. * New method names should be added at the end so that existing layouts are not affected. */ // The current order is derived from http://jmeter.apache.org/usermanual/listeners.html#csvlogformat // TODO this may not be the ideal order; fix further and update the screenshot(s) public static final List<String> SAVE_CONFIG_NAMES = Collections.unmodifiableList(Arrays.asList(new String[]{ "AsXml", "FieldNames", // CSV "Timestamp", "Time", // elapsed "Label", "Code", // Response Code "Message", // Response Message "ThreadName", "DataType", "Success", "AssertionResultsFailureMessage", "Bytes", "SentBytes", "ThreadCounts", // grpThreads and allThreads "Url", "FileName", "Latency", "ConnectTime", "Encoding", "SampleCount", // Sample and Error Count "Hostname", "IdleTime", "RequestHeaders", // XML "SamplerData", // XML "ResponseHeaders", // XML "ResponseData", // XML "Subresults", // XML "Assertions", // XML })); // N.B. Remember to update the equals and hashCode methods when adding new variables. // Initialise values from properties private boolean time = TIME; private boolean latency = LATENCY; private boolean connectTime=CONNECT_TIME; private boolean timestamp = TIMESTAMP; private boolean success = SUCCESS; private boolean label = LABEL; private boolean code = CODE; private boolean message = MESSAGE; private boolean threadName = THREAD_NAME; private boolean dataType = DATATYPE; private boolean encoding = ENCODING; private boolean assertions = ASSERTIONS; private boolean subresults = SUB_RESULTS; private boolean responseData = RESPONSE_DATA; private boolean samplerData = SAMPLER_DATA; private boolean xml = IS_XML; private boolean fieldNames = FIELD_NAMES; private boolean responseHeaders = RESPONSE_HEADERS; private boolean requestHeaders = REQUEST_HEADERS; private boolean responseDataOnError = RESPONSE_DATA_ON_ERROR; private boolean saveAssertionResultsFailureMessage = SAVE_ASSERTION_RESULTS_FAILURE_MESSAGE; private boolean url = URL; private boolean bytes = BYTES; private boolean sentBytes = SENT_BYTES; private boolean fileName = FILE_NAME; private boolean hostname = HOST_NAME; private boolean threadCounts = THREAD_COUNTS; private boolean sampleCount = SAMPLE_COUNT; private boolean idleTime = IDLE_TIME; // Does not appear to be used (yet) // it is @SuppressWarnings("FieldCanBeStatic") private final int assertionsResultsToSave = ASSERTIONS_RESULT_TO_SAVE; // Don't save this, as it is derived from the time format private boolean printMilliseconds = PRINT_MILLISECONDS; private transient String dateFormat = DATE_FORMAT; /** A formatter for the time stamp. * Make transient as we don't want to save the DateTimeFormatter class * Also, there's currently no way to change the value via the GUI, so changing it * later means editing the JMX, or recreating the Listener. */ private transient DateTimeFormatter timestampFormatter = dateFormat != null ? DateTimeFormatter.ofPattern(dateFormat) : null; // Don't save this, as not settable via GUI private String delimiter = DELIMITER; // Don't save this - only needed for processing CSV headers currently private transient int varCount = 0; public SampleSaveConfiguration() { } /** * Alternate constructor for use by CsvSaveService * * @param value initial setting for boolean fields used in Config dialogue */ public SampleSaveConfiguration(boolean value) { assertions = value; bytes = value; code = value; connectTime = value; dataType = value; encoding = value; fieldNames = value; fileName = value; hostname = value; idleTime = value; label = value; latency = value; message = value; printMilliseconds = PRINT_MILLISECONDS;//is derived from properties only requestHeaders = value; responseData = value; responseDataOnError = value; responseHeaders = value; sampleCount = value; samplerData = value; saveAssertionResultsFailureMessage = value; sentBytes = value; subresults = value; success = value; threadCounts = value; threadName = value; time = value; timestamp = value; url = value; xml = value; } public int getVarCount() { // Only for use by CSVSaveService return varCount; } public void setVarCount(int varCount) { // Only for use by CSVSaveService this.varCount = varCount; } // Give access to initial configuration public static SampleSaveConfiguration staticConfig() { return STATIC_SAVE_CONFIGURATION; } /** * Convert a config name to the method name of the getter. * The getter method returns a boolean. * @param configName the config name * @return the getter method name */ public static final String getterName(String configName) { return CONFIG_GETTER_PREFIX + configName; } /** * Convert a config name to the method name of the setter * The setter method requires a boolean parameter. * @param configName the config name * @return the setter method name */ public static final String setterName(String configName) { return CONFIG_SETTER_PREFIX + configName; } /** * Validate pattern * @param temporaryTimestampFormat DateFormat pattern * @return format if ok or null */ private static String validateFormat(String temporaryTimestampFormat) { try { new SimpleDateFormat(temporaryTimestampFormat); if(log.isDebugEnabled()) { log.debug("Successfully validated pattern value {} for property {}", temporaryTimestampFormat, TIME_STAMP_FORMAT_PROP); } return temporaryTimestampFormat; } catch(IllegalArgumentException ex) { log.error("Invalid pattern value {} for property {}", temporaryTimestampFormat, TIME_STAMP_FORMAT_PROP, ex); return null; } } private Object readResolve(){ setupDateFormat(DATE_FORMAT); return this; } /** * Initialize threadSafeLenientFormatter * @param pDateFormat String date format */ private void setupDateFormat(String pDateFormat) { this.dateFormat = pDateFormat; if(dateFormat != null) { this.timestampFormatter = DateTimeFormatter.ofPattern(dateFormat); } else { this.timestampFormatter = null; } } @Override public Object clone() { try { SampleSaveConfiguration clone = (SampleSaveConfiguration)super.clone(); if(this.dateFormat != null) { clone.timestampFormatter = this.threadSafeLenientFormatter(); } return clone; } catch(CloneNotSupportedException e) { throw new RuntimeException("Should not happen",e); } } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if((obj == null) || (obj.getClass() != this.getClass())) { return false; } // We know we are comparing to another SampleSaveConfiguration SampleSaveConfiguration s = (SampleSaveConfiguration)obj; boolean primitiveValues = s.time == time && s.latency == latency && s.connectTime == connectTime && s.timestamp == timestamp && s.success == success && s.label == label && s.code == code && s.message == message && s.threadName == threadName && s.dataType == dataType && s.encoding == encoding && s.assertions == assertions && s.subresults == subresults && s.responseData == responseData && s.samplerData == samplerData && s.xml == xml && s.fieldNames == fieldNames && s.responseHeaders == responseHeaders && s.requestHeaders == requestHeaders && s.assertionsResultsToSave == assertionsResultsToSave && s.saveAssertionResultsFailureMessage == saveAssertionResultsFailureMessage && s.printMilliseconds == printMilliseconds && s.responseDataOnError == responseDataOnError && s.url == url && s.bytes == bytes && s.sentBytes == sentBytes && s.fileName == fileName && s.hostname == hostname && s.sampleCount == sampleCount && s.idleTime == idleTime && s.threadCounts == threadCounts; boolean stringValues = false; if(primitiveValues) { stringValues = Objects.equals(delimiter, s.delimiter); } boolean complexValues = false; if(primitiveValues && stringValues) { complexValues = Objects.equals(dateFormat, s.dateFormat); } return primitiveValues && stringValues && complexValues; } @Override public int hashCode() { int hash = 7; hash = 31 * hash + (time ? 1 : 0); hash = 31 * hash + (latency ? 1 : 0); hash = 31 * hash + (connectTime ? 1 : 0); hash = 31 * hash + (timestamp ? 1 : 0); hash = 31 * hash + (success ? 1 : 0); hash = 31 * hash + (label ? 1 : 0); hash = 31 * hash + (code ? 1 : 0); hash = 31 * hash + (message ? 1 : 0); hash = 31 * hash + (threadName ? 1 : 0); hash = 31 * hash + (dataType ? 1 : 0); hash = 31 * hash + (encoding ? 1 : 0); hash = 31 * hash + (assertions ? 1 : 0); hash = 31 * hash + (subresults ? 1 : 0); hash = 31 * hash + (responseData ? 1 : 0); hash = 31 * hash + (samplerData ? 1 : 0); hash = 31 * hash + (xml ? 1 : 0); hash = 31 * hash + (fieldNames ? 1 : 0); hash = 31 * hash + (responseHeaders ? 1 : 0); hash = 31 * hash + (requestHeaders ? 1 : 0); hash = 31 * hash + assertionsResultsToSave; hash = 31 * hash + (saveAssertionResultsFailureMessage ? 1 : 0); hash = 31 * hash + (printMilliseconds ? 1 : 0); hash = 31 * hash + (responseDataOnError ? 1 : 0); hash = 31 * hash + (url ? 1 : 0); hash = 31 * hash + (bytes ? 1 : 0); hash = 31 * hash + (sentBytes ? 1 : 0); hash = 31 * hash + (fileName ? 1 : 0); hash = 31 * hash + (hostname ? 1 : 0); hash = 31 * hash + (threadCounts ? 1 : 0); hash = 31 * hash + (delimiter != null ? delimiter.hashCode() : 0); hash = 31 * hash + (dateFormat != null ? dateFormat.hashCode() : 0); hash = 31 * hash + (sampleCount ? 1 : 0); hash = 31 * hash + (idleTime ? 1 : 0); return hash; } ///////////////////// Start of standard save/set access methods ///////////////////// public boolean saveResponseHeaders() { return responseHeaders; } public void setResponseHeaders(boolean r) { responseHeaders = r; } public boolean saveRequestHeaders() { return requestHeaders; } public void setRequestHeaders(boolean r) { requestHeaders = r; } public boolean saveAssertions() { return assertions; } public void setAssertions(boolean assertions) { this.assertions = assertions; } public boolean saveCode() { return code; } public void setCode(boolean code) { this.code = code; } public boolean saveDataType() { return dataType; } public void setDataType(boolean dataType) { this.dataType = dataType; } public boolean saveEncoding() { return encoding; } public void setEncoding(boolean encoding) { this.encoding = encoding; } public boolean saveLabel() { return label; } public void setLabel(boolean label) { this.label = label; } public boolean saveLatency() { return latency; } public void setLatency(boolean latency) { this.latency = latency; } public boolean saveConnectTime() { return connectTime; } public void setConnectTime(boolean connectTime) { this.connectTime = connectTime; } public boolean saveMessage() { return message; } public void setMessage(boolean message) { this.message = message; } public boolean saveResponseData(SampleResult res) { return responseData || TestPlan.getFunctionalMode() || (responseDataOnError && !res.isSuccessful()); } public boolean saveResponseData() { return responseData; } public void setResponseData(boolean responseData) { this.responseData = responseData; } public boolean saveSamplerData(SampleResult res) { return samplerData || TestPlan.getFunctionalMode() // as per 2.0 branch || (responseDataOnError && !res.isSuccessful()); } public boolean saveSamplerData() { return samplerData; } public void setSamplerData(boolean samplerData) { this.samplerData = samplerData; } public boolean saveSubresults() { return subresults; } public void setSubresults(boolean subresults) { this.subresults = subresults; } public boolean saveSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public boolean saveThreadName() { return threadName; } public void setThreadName(boolean threadName) { this.threadName = threadName; } public boolean saveTime() { return time; } public void setTime(boolean time) { this.time = time; } public boolean saveTimestamp() { return timestamp; } public void setTimestamp(boolean timestamp) { this.timestamp = timestamp; } public boolean saveAsXml() { return xml; } public void setAsXml(boolean xml) { this.xml = xml; } public boolean saveFieldNames() { return fieldNames; } public void setFieldNames(boolean printFieldNames) { this.fieldNames = printFieldNames; } public boolean saveUrl() { return url; } public void setUrl(boolean save) { this.url = save; } public boolean saveBytes() { return bytes; } public void setBytes(boolean save) { this.bytes = save; } public boolean saveSentBytes() { return sentBytes; } public void setSentBytes(boolean save) { this.sentBytes = save; } public boolean saveFileName() { return fileName; } public void setFileName(boolean save) { this.fileName = save; } public boolean saveAssertionResultsFailureMessage() { return saveAssertionResultsFailureMessage; } public void setAssertionResultsFailureMessage(boolean b) { saveAssertionResultsFailureMessage = b; } public boolean saveThreadCounts() { return threadCounts; } public void setThreadCounts(boolean save) { this.threadCounts = save; } public boolean saveSampleCount() { return sampleCount; } public void setSampleCount(boolean save) { this.sampleCount = save; } ///////////////// End of standard field accessors ///////////////////// /** * Intended for use by CsvSaveService (and test cases) * @param fmt * format of the date to be saved. If <code>null</code> * milliseconds since epoch will be printed */ public void setDateFormat(String fmt){ printMilliseconds = fmt == null; // maintain relationship setupDateFormat(fmt); } public boolean printMilliseconds() { return printMilliseconds; } /** * @return {@link DateFormat} non lenient */ public DateFormat strictDateFormatter() { if(dateFormat != null) { return new SimpleDateFormat(dateFormat); } else { return null; } } /** * @return {@link DateTimeFormatter} Thread safe lenient formatter */ public DateTimeFormatter threadSafeLenientFormatter() { // When restored by XStream threadSafeLenientFormatter may not have // been initialized if(timestampFormatter == null) { timestampFormatter = dateFormat != null ? DateTimeFormatter.ofPattern(dateFormat) : null; } return timestampFormatter; } public int assertionsResultsToSave() { return assertionsResultsToSave; } public String getDelimiter() { return delimiter; } public String getXmlPi() { return JMeterUtils.getJMeterProperties().getProperty(XML_PI, ""); // Defaults to empty; } // Used by old Save service public void setDelimiter(String delim) { delimiter=delim; } // Used by SampleSaveConfigurationConverter.unmarshall() public void setDefaultDelimiter() { delimiter=DELIMITER; } // Used by SampleSaveConfigurationConverter.unmarshall() public void setDefaultTimeStampFormat() { printMilliseconds=PRINT_MILLISECONDS; setupDateFormat(DATE_FORMAT); } public boolean saveHostname(){ return hostname; } public void setHostname(boolean save){ hostname = save; } public boolean saveIdleTime() { return idleTime; } public void setIdleTime(boolean save) { idleTime = save; } }
googleapis/google-cloud-java
36,833
java-asset/proto-google-cloud-asset-v1/src/main/java/com/google/cloud/asset/v1/RelationshipAttributes.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/asset/v1/assets.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.asset.v1; /** * * * <pre> * DEPRECATED. This message only presents for the purpose of * backward-compatibility. The server will never populate this message in * responses. * The relationship attributes which include `type`, `source_resource_type`, * `target_resource_type` and `action`. * </pre> * * Protobuf type {@code google.cloud.asset.v1.RelationshipAttributes} */ @java.lang.Deprecated public final class RelationshipAttributes extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.asset.v1.RelationshipAttributes) RelationshipAttributesOrBuilder { private static final long serialVersionUID = 0L; // Use RelationshipAttributes.newBuilder() to construct. private RelationshipAttributes(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RelationshipAttributes() { type_ = ""; sourceResourceType_ = ""; targetResourceType_ = ""; action_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new RelationshipAttributes(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.asset.v1.AssetProto .internal_static_google_cloud_asset_v1_RelationshipAttributes_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.asset.v1.AssetProto .internal_static_google_cloud_asset_v1_RelationshipAttributes_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.asset.v1.RelationshipAttributes.class, com.google.cloud.asset.v1.RelationshipAttributes.Builder.class); } public static final int TYPE_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object type_ = ""; /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @return The type. */ @java.lang.Override public java.lang.String getType() { java.lang.Object ref = type_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); type_ = s; return s; } } /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @return The bytes for type. */ @java.lang.Override public com.google.protobuf.ByteString getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); type_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SOURCE_RESOURCE_TYPE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object sourceResourceType_ = ""; /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @return The sourceResourceType. */ @java.lang.Override public java.lang.String getSourceResourceType() { java.lang.Object ref = sourceResourceType_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sourceResourceType_ = s; return s; } } /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @return The bytes for sourceResourceType. */ @java.lang.Override public com.google.protobuf.ByteString getSourceResourceTypeBytes() { java.lang.Object ref = sourceResourceType_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); sourceResourceType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TARGET_RESOURCE_TYPE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object targetResourceType_ = ""; /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @return The targetResourceType. */ @java.lang.Override public java.lang.String getTargetResourceType() { java.lang.Object ref = targetResourceType_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); targetResourceType_ = s; return s; } } /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @return The bytes for targetResourceType. */ @java.lang.Override public com.google.protobuf.ByteString getTargetResourceTypeBytes() { java.lang.Object ref = targetResourceType_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); targetResourceType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ACTION_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object action_ = ""; /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @return The action. */ @java.lang.Override public java.lang.String getAction() { java.lang.Object ref = action_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); action_ = s; return s; } } /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @return The bytes for action. */ @java.lang.Override public com.google.protobuf.ByteString getActionBytes() { java.lang.Object ref = action_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); action_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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(sourceResourceType_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, sourceResourceType_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(targetResourceType_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, targetResourceType_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(action_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, action_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(type_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, type_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(sourceResourceType_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, sourceResourceType_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(targetResourceType_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, targetResourceType_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(action_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, action_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(type_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, type_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.asset.v1.RelationshipAttributes)) { return super.equals(obj); } com.google.cloud.asset.v1.RelationshipAttributes other = (com.google.cloud.asset.v1.RelationshipAttributes) obj; if (!getType().equals(other.getType())) return false; if (!getSourceResourceType().equals(other.getSourceResourceType())) return false; if (!getTargetResourceType().equals(other.getTargetResourceType())) return false; if (!getAction().equals(other.getAction())) 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) + TYPE_FIELD_NUMBER; hash = (53 * hash) + getType().hashCode(); hash = (37 * hash) + SOURCE_RESOURCE_TYPE_FIELD_NUMBER; hash = (53 * hash) + getSourceResourceType().hashCode(); hash = (37 * hash) + TARGET_RESOURCE_TYPE_FIELD_NUMBER; hash = (53 * hash) + getTargetResourceType().hashCode(); hash = (37 * hash) + ACTION_FIELD_NUMBER; hash = (53 * hash) + getAction().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.asset.v1.RelationshipAttributes parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.asset.v1.RelationshipAttributes 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.asset.v1.RelationshipAttributes parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.asset.v1.RelationshipAttributes 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.asset.v1.RelationshipAttributes parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.asset.v1.RelationshipAttributes parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.asset.v1.RelationshipAttributes parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.asset.v1.RelationshipAttributes 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.asset.v1.RelationshipAttributes parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.asset.v1.RelationshipAttributes 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.asset.v1.RelationshipAttributes parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.asset.v1.RelationshipAttributes 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.asset.v1.RelationshipAttributes 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> * DEPRECATED. This message only presents for the purpose of * backward-compatibility. The server will never populate this message in * responses. * The relationship attributes which include `type`, `source_resource_type`, * `target_resource_type` and `action`. * </pre> * * Protobuf type {@code google.cloud.asset.v1.RelationshipAttributes} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.asset.v1.RelationshipAttributes) com.google.cloud.asset.v1.RelationshipAttributesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.asset.v1.AssetProto .internal_static_google_cloud_asset_v1_RelationshipAttributes_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.asset.v1.AssetProto .internal_static_google_cloud_asset_v1_RelationshipAttributes_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.asset.v1.RelationshipAttributes.class, com.google.cloud.asset.v1.RelationshipAttributes.Builder.class); } // Construct using com.google.cloud.asset.v1.RelationshipAttributes.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; type_ = ""; sourceResourceType_ = ""; targetResourceType_ = ""; action_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.asset.v1.AssetProto .internal_static_google_cloud_asset_v1_RelationshipAttributes_descriptor; } @java.lang.Override public com.google.cloud.asset.v1.RelationshipAttributes getDefaultInstanceForType() { return com.google.cloud.asset.v1.RelationshipAttributes.getDefaultInstance(); } @java.lang.Override public com.google.cloud.asset.v1.RelationshipAttributes build() { com.google.cloud.asset.v1.RelationshipAttributes result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.asset.v1.RelationshipAttributes buildPartial() { com.google.cloud.asset.v1.RelationshipAttributes result = new com.google.cloud.asset.v1.RelationshipAttributes(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.asset.v1.RelationshipAttributes result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.sourceResourceType_ = sourceResourceType_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.targetResourceType_ = targetResourceType_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.action_ = action_; } } @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.asset.v1.RelationshipAttributes) { return mergeFrom((com.google.cloud.asset.v1.RelationshipAttributes) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.asset.v1.RelationshipAttributes other) { if (other == com.google.cloud.asset.v1.RelationshipAttributes.getDefaultInstance()) return this; if (!other.getType().isEmpty()) { type_ = other.type_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getSourceResourceType().isEmpty()) { sourceResourceType_ = other.sourceResourceType_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getTargetResourceType().isEmpty()) { targetResourceType_ = other.targetResourceType_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getAction().isEmpty()) { action_ = other.action_; 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: { sourceResourceType_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 10 case 18: { targetResourceType_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 18 case 26: { action_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 26 case 34: { type_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object type_ = ""; /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @return The type. */ public java.lang.String getType() { java.lang.Object ref = type_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); type_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @return The bytes for type. */ public com.google.protobuf.ByteString getTypeBytes() { java.lang.Object ref = type_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); type_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @param value The type to set. * @return This builder for chaining. */ public Builder setType(java.lang.String value) { if (value == null) { throw new NullPointerException(); } type_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @return This builder for chaining. */ public Builder clearType() { type_ = getDefaultInstance().getType(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The unique identifier of the relationship type. Example: * `INSTANCE_TO_INSTANCEGROUP` * </pre> * * <code>string type = 4;</code> * * @param value The bytes for type to set. * @return This builder for chaining. */ public Builder setTypeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); type_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object sourceResourceType_ = ""; /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @return The sourceResourceType. */ public java.lang.String getSourceResourceType() { java.lang.Object ref = sourceResourceType_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sourceResourceType_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @return The bytes for sourceResourceType. */ public com.google.protobuf.ByteString getSourceResourceTypeBytes() { java.lang.Object ref = sourceResourceType_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); sourceResourceType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @param value The sourceResourceType to set. * @return This builder for chaining. */ public Builder setSourceResourceType(java.lang.String value) { if (value == null) { throw new NullPointerException(); } sourceResourceType_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @return This builder for chaining. */ public Builder clearSourceResourceType() { sourceResourceType_ = getDefaultInstance().getSourceResourceType(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The source asset type. Example: `compute.googleapis.com/Instance` * </pre> * * <code>string source_resource_type = 1;</code> * * @param value The bytes for sourceResourceType to set. * @return This builder for chaining. */ public Builder setSourceResourceTypeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sourceResourceType_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object targetResourceType_ = ""; /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @return The targetResourceType. */ public java.lang.String getTargetResourceType() { java.lang.Object ref = targetResourceType_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); targetResourceType_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @return The bytes for targetResourceType. */ public com.google.protobuf.ByteString getTargetResourceTypeBytes() { java.lang.Object ref = targetResourceType_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); targetResourceType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @param value The targetResourceType to set. * @return This builder for chaining. */ public Builder setTargetResourceType(java.lang.String value) { if (value == null) { throw new NullPointerException(); } targetResourceType_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @return This builder for chaining. */ public Builder clearTargetResourceType() { targetResourceType_ = getDefaultInstance().getTargetResourceType(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * The target asset type. Example: `compute.googleapis.com/Disk` * </pre> * * <code>string target_resource_type = 2;</code> * * @param value The bytes for targetResourceType to set. * @return This builder for chaining. */ public Builder setTargetResourceTypeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); targetResourceType_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object action_ = ""; /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @return The action. */ public java.lang.String getAction() { java.lang.Object ref = action_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); action_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @return The bytes for action. */ public com.google.protobuf.ByteString getActionBytes() { java.lang.Object ref = action_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); action_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @param value The action to set. * @return This builder for chaining. */ public Builder setAction(java.lang.String value) { if (value == null) { throw new NullPointerException(); } action_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @return This builder for chaining. */ public Builder clearAction() { action_ = getDefaultInstance().getAction(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * The detail of the relationship, e.g. `contains`, `attaches` * </pre> * * <code>string action = 3;</code> * * @param value The bytes for action to set. * @return This builder for chaining. */ public Builder setActionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); action_ = value; bitField0_ |= 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.asset.v1.RelationshipAttributes) } // @@protoc_insertion_point(class_scope:google.cloud.asset.v1.RelationshipAttributes) private static final com.google.cloud.asset.v1.RelationshipAttributes DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.asset.v1.RelationshipAttributes(); } public static com.google.cloud.asset.v1.RelationshipAttributes getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RelationshipAttributes> PARSER = new com.google.protobuf.AbstractParser<RelationshipAttributes>() { @java.lang.Override public RelationshipAttributes 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<RelationshipAttributes> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RelationshipAttributes> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.asset.v1.RelationshipAttributes getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/directory-server
36,706
server-integ/src/test/java/org/apache/directory/server/operations/search/PagedSearchIT.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.server.operations.search; import static org.apache.directory.server.integ.ServerIntegrationUtils.getWiredContext; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.SizeLimitExceededException; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import javax.naming.ldap.PagedResultsResponseControl; import org.apache.directory.api.asn1.EncoderException; import org.apache.directory.api.ldap.codec.api.LdapApiService; import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.message.Control; import org.apache.directory.api.ldap.model.message.ResultCodeEnum; import org.apache.directory.api.ldap.model.message.SearchRequest; import org.apache.directory.api.ldap.model.message.SearchRequestImpl; import org.apache.directory.api.ldap.model.message.SearchResultDone; 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.message.controls.PagedResultsImpl; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.util.JndiUtils; import org.apache.directory.api.util.Network; import org.apache.directory.api.util.Strings; import org.apache.directory.ldap.client.api.EntryCursorImpl; import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.core.annotations.ApplyLdifs; import org.apache.directory.server.core.integ.AbstractLdapTestUnit; import org.apache.directory.server.core.integ.ApacheDSTestExtension; import org.apache.directory.server.ldap.LdapServer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; /** * Test the PagedSearchControl. The following tables covers all the * possible cases for both an admin and a simple user, combining the * Server SizeLimit (SL), the requested SizeLimit (RL) and the paged * size limit (PL). The 'X' column tells if we are supposed to receive * a SizeLimitExceededException.<br> * <br> * Administrator<br> * <pre> * +-------+----+----+----+---------------------+----+---+<br> * |test | SL | RL | PL | Nb of responses | nb | X |<br> * +-------+----+----+----+---------------------+----+---+<br> * |test1 | 0 | 0 | 3 | 4 ( 3 + 3 + 3 + 1 ) | 10 | |<br> * |test2 | 0 | 0 | 5 | 2 ( 5 + 5 ) | 10 | |<br> * |test3 | 3 | 0 | 5 | 2 ( 5 + 5 ) | 10 | |<br> * |test4 | 0 | 3 | 5 | 1 ( 3 ) | 3 | Y |<br> * |test5 | 5 | 0 | 3 | 4 ( 3 + 3 + 3 + 1 ) | 10 | |<br> * |test6 | 0 | 9 | 5 | 2 ( 5 + 4 ) | 5 | Y |<br> * |test7 | 5 | 0 | 5 | 2 ( 5 + 5 ) | 10 | |<br> * |test8 | 0 | 5 | 5 | 1 ( 5 ) | 5 | Y |<br> * |test9 | 5 | 4 | 3 | 2 ( 3 + 1 ) | 4 | Y |<br> * |test10 | 4 | 5 | 3 | 2 ( 3 + 2 ) | 5 | Y |<br> * |test11 | 5 | 3 | 4 | 1 ( 3 ) | 3 | Y |<br> * |test12 | 5 | 4 | 3 | 2 ( 3 + 1 ) | 4 | Y |<br> * |test13 | 4 | 5 | 3 | 2 ( 3 + 2 ) | 5 | Y |<br> * |test14 | 4 | 3 | 5 | 1 ( 3 ) | 3 | Y |<br> * |test15 | 3 | 5 | 4 | 2 ( 4 + 1 ) | 5 | Y |<br> * |test16 | 3 | 4 | 5 | 1 ( 4 ) | 4 | Y |<br> * |test17 | 5 | 5 | 5 | 1 ( 5 ) | 5 | Y |<br> * +-------+----+----+----+---------------------+----+---+<br> * <br> * Simple user<br> * <br> * +-------+----+----+----+---------------------+----+---+<br> * |test | SL | RL | PL | Nb of responses | nb | X |<br> * +-------+----+----+----+---------------------+----+---+<br> * |test18 | 0 | 0 | 3 | 4 ( 3 + 3 + 3 + 1 ) | 10 | |<br> * |test19 | 0 | 0 | 5 | 2 ( 5 + 5 ) | 10 | |<br> * |test20 | 3 | 0 | 5 | 1 ( 3 ) | 3 | Y |<br> * |test21 | 0 | 3 | 5 | 1 ( 3 ) | 3 | Y |<br> * |test22 | 5 | 0 | 3 | 2 ( 3 + 2 ) | 5 | Y |<br> * |test23 | 0 | 9 | 5 | 2 ( 5 + 4 ) | 9 | Y |<br> * |test24 | 5 | 0 | 5 | 1 ( 5 ) | 5 | Y |<br> * |test25 | 0 | 5 | 5 | 1 ( 5 ) | 5 | Y |<br> * |test26 | 5 | 4 | 3 | 2 ( 3 + 1 ) | 4 | Y |<br> * |test27 | 4 | 5 | 3 | 2 ( 3 + 1 ) | 4 | Y |<br> * |test28 | 5 | 3 | 4 | 1 ( 3 ) | 3 | Y |<br> * |test29 | 5 | 4 | 3 | 2 ( 3 + 1 ) | 4 | Y |<br> * |test30 | 4 | 5 | 3 | 2 ( 3 + 1 ) | 4 | Y |<br> * |test31 | 4 | 3 | 5 | 1 ( 3 ) | 3 | Y |<br> * |test32 | 3 | 5 | 4 | 1 ( 3 ) | 3 | Y |<br> * |test33 | 3 | 4 | 5 | 1 ( 3 ) | 3 | Y |<br> * |test34 | 5 | 5 | 5 | 1 ( 5 ) | 5 | Y |<br> * +-------+----+----+----+---------------------+----+---+<br> *</pre> * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ @ExtendWith( { ApacheDSTestExtension.class } ) @CreateLdapServer( transports = { @CreateTransport(protocol = "LDAP") }) @ApplyLdifs( { // Add 10 new entries "dn: dc=users,ou=system", "objectClass: top", "objectClass: domain", "dc: users", // "dn: cn=user0,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user0", "sn: user 0", // "dn: cn=user1,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user1", "sn: user 1", // "dn: cn=user2,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user2", "sn: user 2", // "dn: cn=user3,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user3", "sn: user 3", // "dn: cn=user4,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user4", "sn: user 4", // "dn: cn=user5,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user5", "sn: user 5", // "dn: cn=user6,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user6", "sn: user 6", // "dn: cn=user7,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user7", "sn: user 7", // "dn: cn=user8,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user8", "sn: user 8", // "dn: cn=user9,dc=users,ou=system", "objectClass: top", "objectClass: person", "cn: user9", "sn: user 9", "", // Add another user for non admin tests "dn: cn=user,ou=system", "objectClass: top", "objectClass: person", "cn: user", "userPassword: secret", "sn: user" }) public class PagedSearchIT extends AbstractLdapTestUnit { private LdapApiService codec = LdapApiServiceFactory.getSingleton(); /** * Create the searchControls with a paged size * @throws EncoderException on codec failures */ private SearchControls createSearchControls( DirContext ctx, int sizeLimit, int pagedSize ) throws NamingException, EncoderException { SearchControls controls = new SearchControls(); controls.setCountLimit( sizeLimit ); controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); PagedResults pagedSearchControl = new PagedResultsImpl(); pagedSearchControl.setSize( pagedSize ); ( ( LdapContext ) ctx ).setRequestControls( JndiUtils.toJndiControls( codec, new Control[] { pagedSearchControl } ) ); return controls; } /** * Create the searchControls with a paged size * @throws EncoderException on codec failures */ private void createNextSearchControls( DirContext ctx, byte[] cookie, int pagedSize ) throws NamingException, EncoderException { PagedResults pagedSearchControl = new PagedResultsImpl(); pagedSearchControl.setCookie( cookie ); pagedSearchControl.setSize( pagedSize ); ( ( LdapContext ) ctx ).setRequestControls( JndiUtils.toJndiControls( codec, new Control[] { pagedSearchControl } ) ); } /** * Check that we got the correct result set */ private void checkResults( List<SearchResult> results, int expectedSize ) throws NamingException { assertEquals( expectedSize, results.size() ); Set<String> expected = new HashSet<String>(); for ( int i = 0; i < 10; i++ ) { expected.add( "user" + i ); } // check that we have correctly read all the entries for ( int i = 0; i < expectedSize; i++ ) { SearchResult entry = results.get( i ); String user = ( String ) entry.getAttributes().get( "cn" ).get(); assertTrue( expected.contains( user ) ); expected.remove( user ); } assertEquals( 10 - expectedSize, expected.size() ); } /** * Do the loop over the entries, until we can't get any more, or until we * reach a limit. It will check that we have got all the expected entries. * @throws EncoderException on codec failures */ private void doLoop( DirContext ctx, SearchControls controls, int pagedSizeLimit, int expectedLoop, int expectedNbEntries, boolean expectedException ) throws NamingException, EncoderException { // Loop over all the elements int loop = 0; boolean hasSizeLimitException = false; List<SearchResult> results = new ArrayList<SearchResult>(); while ( true ) { loop++; NamingEnumeration<SearchResult> list = null; try { list = ctx.search( "dc=users,ou=system", "(cn=*)", controls ); while ( list.hasMore() ) { SearchResult result = list.next(); results.add( result ); } } catch ( SizeLimitExceededException e ) { hasSizeLimitException = true; break; } finally { // Close the NamingEnumeration if ( list != null ) { list.close(); } } // Now read the next ones javax.naming.ldap.Control[] responseControls = ( ( LdapContext ) ctx ).getResponseControls(); PagedResultsResponseControl responseControl = ( PagedResultsResponseControl ) responseControls[0]; assertEquals( 0, responseControl.getResultSize() ); // check if this is over byte[] cookie = responseControl.getCookie(); if ( Strings.isEmpty( cookie ) ) { // If so, exit the loop break; } // Prepare the next iteration createNextSearchControls( ctx, responseControl.getCookie(), pagedSizeLimit ); } assertEquals( expectedException, hasSizeLimitException ); assertEquals( expectedLoop, loop ); checkResults( results, expectedNbEntries ); // And close the connection closeConnection( ctx ); } /** * Close a connection, and wait a bit to be sure it's done */ private void closeConnection( DirContext ctx ) throws NamingException { if ( ctx != null ) { ctx.close(); try { Thread.sleep( 10 ); } catch ( Exception e ) { } } } /** * Admin = yes <br> * SL = none<br> * RL = none<br> * PL = 3<br> * expected exception : no<br> * expected number of entries returned : 10 ( 3 + 3 + 3 + 1 )<br> */ @Test public void testPagedSearchtest1() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 3 ); doLoop( ctx, controls, 3, 4, 10, false ); } /** * Admin = yes <br> * SL = none<br> * RL = none<br> * PL = 5<br> * expected exception : no<br> * expected number of entries returned : 10 ( 5 + 5 )<br> */ @Test public void testPagedSearchtest2() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 5 ); doLoop( ctx, controls, 5, 2, 10, false ); } /** * Admin = yes <br> * SL = 3<br> * RL = none<br> * PL = 5<br> * expected exception : no<br> * expected number of entries returned : 10 ( 5 + 5 )<br> */ @Test public void testPagedSearchTest3() throws Exception { getLdapServer().setMaxSizeLimit( 3 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 5 ); doLoop( ctx, controls, 5, 2, 10, false ); } /** * Admin = yes <br> * SL = none<br> * RL = 3<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 3<br> */ @Test public void testPagedSearchTest4() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 3, 5 ); doLoop( ctx, controls, 5, 1, 3, true ); } /** * Admin = yes <br> * SL = 5<br> * RL = none<br> * PL = 3<br> * expected exception : no<br> * expected number of entries returned : 10 ( 3 + 3 + 3 + 1 )<br> */ @Test public void testPagedSearchtest5() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 3 ); doLoop( ctx, controls, 3, 4, 10, false ); } /** * Admin = yes <br> * SL = none<br> * RL = 9<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 9 ( 5 + 4 )<br> */ @Test public void testPagedSearchTest6() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 9, 5 ); doLoop( ctx, controls, 5, 2, 9, true ); } /** * Admin = yes <br> * SL = 5<br> * RL = none<br> * PL = 5<br> * expected exception : no<br> * expected number of entries returned : 10 ( 5 + 5 )<br> */ @Test public void testPagedSearchtest7() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 5 ); doLoop( ctx, controls, 5, 2, 10, false ); } /** * Admin = yes <br> * SL = none<br> * RL = 5<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 5<br> */ @Test public void testPagedSearchTest8() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 5, 5 ); doLoop( ctx, controls, 5, 1, 5, true ); } /** * Admin = yes <br> * SL = 5<br> * RL = 4<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 2 ( 3 + 1 )<br> */ @Test public void testPagedSearchTest9() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 4, 3 ); doLoop( ctx, controls, 3, 2, 4, true ); } /** * Admin = yes <br> * SL = 4<br> * RL = 5<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 5 ( 3 + 2 )<br> */ @Test public void testPagedSearchtest10() throws Exception { getLdapServer().setMaxSizeLimit( 4 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 5, 3 ); doLoop( ctx, controls, 3, 2, 5, true ); } /** * Admin = yes <br> * SL = 5<br> * RL = 3<br> * PL = 4<br> * expected exception : yes<br> * expected number of entries returned : 3<br> */ @Test public void testPagedSearchtest11() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 3, 4 ); doLoop( ctx, controls, 4, 1, 3, true ); } /** * Admin = yes <br> * SL = 5<br> * RL = 4<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 4 ( 3 + 1 )<br> */ @Test public void testPagedSearchtest12() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 4, 3 ); doLoop( ctx, controls, 3, 2, 4, true ); } /** * Admin = yes <br> * SL = 4<br> * RL = 5<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 5 ( 3 + 2 )<br> */ @Test public void testPagedSearchtest13() throws Exception { getLdapServer().setMaxSizeLimit( 4 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 5, 3 ); doLoop( ctx, controls, 3, 2, 5, true ); } /** * Admin = yes <br> * SL = 4<br> * RL = 3<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 3 <br> */ @Test public void testPagedSearchtest14() throws Exception { getLdapServer().setMaxSizeLimit( 4 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 3, 5 ); doLoop( ctx, controls, 5, 1, 3, true ); } /** * Admin = yes <br> * SL = 3<br> * RL = 5<br> * PL = 4<br> * expected exception : yes<br> * expected number of entries returned : 5 ( 4 + 1 )<br> */ @Test public void testPagedSearchtest15() throws Exception { getLdapServer().setMaxSizeLimit( 3 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 5, 4 ); doLoop( ctx, controls, 4, 2, 5, true ); } /** * Admin = yes <br> * SL = 3<br> * RL = 4<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 4 <br> */ @Test public void testPagedSearchtest16() throws Exception { getLdapServer().setMaxSizeLimit( 3 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 4, 5 ); doLoop( ctx, controls, 5, 1, 4, true ); } /** * Admin = yes <br> * SL = 5<br> * RL = 5<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 5 <br> */ @Test public void testPagedSearchtest17() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer() ); SearchControls controls = createSearchControls( ctx, 5, 5 ); doLoop( ctx, controls, 5, 1, 5, true ); } /** * Admin = no <br> * SL = none<br> * RL = none<br> * PL = 3<br> * expected exception : no<br> * expected number of entries returned : 10 ( 3 + 3 + 3 + 1 )<br> */ @Test public void testPagedSearchtest18() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 3 ); doLoop( ctx, controls, 3, 4, 10, false ); } /** * Admin = no <br> * SL = none<br> * RL = none<br> * PL = 5<br> * expected exception : no<br> * expected number of entries returned : 10 ( 5 + 5 )<br> */ @Test public void testPagedSearchtest19() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 5 ); doLoop( ctx, controls, 5, 2, 10, false ); } /** * Admin = no <br> * SL = 3<br> * RL = none<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 3<br> */ @Test public void testPagedSearchTest20() throws Exception { getLdapServer().setMaxSizeLimit( 3 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 5 ); doLoop( ctx, controls, 5, 1, 3, true ); } /** * Admin = no <br> * SL = none<br> * RL = 3<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 3<br> */ @Test public void testPagedSearchTest21() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 3, 5 ); doLoop( ctx, controls, 5, 1, 3, true ); } /** * Admin = no <br> * SL = 5<br> * RL = none<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 5 ( 3 + 2 )<br> */ @Test public void testPagedSearchtest22() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 3 ); doLoop( ctx, controls, 3, 2, 5, true ); } /** * Admin = no <br> * SL = none<br> * RL = 9<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 9 ( 5 + 4 )<br> */ @Test public void testPagedSearchTest23() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 9, 5 ); doLoop( ctx, controls, 5, 2, 9, true ); } /** * Admin = no <br> * SL = 5<br> * RL = none<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 5<br> */ @Test public void testPagedSearchtest24() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 5 ); doLoop( ctx, controls, 5, 1, 5, true ); } /** * Admin = no <br> * SL = none<br> * RL = 5<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 5<br> */ @Test public void testPagedSearchTest25() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 5, 5 ); doLoop( ctx, controls, 5, 1, 5, true ); } /** * Admin = no <br> * SL = 5<br> * RL = 4<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 2 ( 3 + 1 )<br> */ @Test public void testPagedSearchTest26() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 4, 3 ); doLoop( ctx, controls, 3, 2, 4, true ); } /** * Admin = no <br> * SL = 4<br> * RL = 5<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 4 ( 3 + 1 )<br> */ @Test public void testPagedSearchtest27() throws Exception { getLdapServer().setMaxSizeLimit( 4 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 5, 3 ); doLoop( ctx, controls, 3, 2, 4, true ); } /** * Admin = no <br> * SL = 5<br> * RL = 3<br> * PL = 4<br> * expected exception : yes<br> * expected number of entries returned : 3<br> */ @Test public void testPagedSearchtest28() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 3, 4 ); doLoop( ctx, controls, 4, 1, 3, true ); } /** * Admin = no <br> * SL = 5<br> * RL = 4<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 4 ( 3 + 1 )<br> */ @Test public void testPagedSearchtest29() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 4, 3 ); doLoop( ctx, controls, 3, 2, 4, true ); } /** * Admin = no <br> * SL = 4<br> * RL = 5<br> * PL = 3<br> * expected exception : yes<br> * expected number of entries returned : 4 ( 3 + 1 )<br> */ @Test public void testPagedSearchtest30() throws Exception { getLdapServer().setMaxSizeLimit( 4 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 5, 3 ); doLoop( ctx, controls, 3, 2, 4, true ); } /** * Admin = no <br> * SL = 4<br> * RL = 3<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 3 <br> */ @Test public void testPagedSearchtest31() throws Exception { getLdapServer().setMaxSizeLimit( 4 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 3, 5 ); doLoop( ctx, controls, 3, 1, 3, true ); } /** * Admin = no <br> * SL = 3<br> * RL = 5<br> * PL = 4<br> * expected exception : yes<br> * expected number of entries returned : 3 <br> */ @Test public void testPagedSearchtest32() throws Exception { getLdapServer().setMaxSizeLimit( 3 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 5, 4 ); doLoop( ctx, controls, 3, 1, 3, true ); } /** * Admin = no <br> * SL = 3<br> * RL = 4<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 3 <br> */ @Test public void testPagedSearchtest33() throws Exception { getLdapServer().setMaxSizeLimit( 3 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 4, 5 ); doLoop( ctx, controls, 3, 1, 3, true ); } /** * Admin = no <br> * SL = 5<br> * RL = 5<br> * PL = 5<br> * expected exception : yes<br> * expected number of entries returned : 5 <br> */ @Test public void testPagedSearchtest34() throws Exception { getLdapServer().setMaxSizeLimit( 5 ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, 5, 5 ); doLoop( ctx, controls, 5, 1, 5, true ); } /** * Admin = no <br> * SL = none<br> * RL = none<br> * PL = -2<br> * expected exception : no<br> * expected number of entries returned : 10 <br> */ @Test public void testPagedSearchWithNegativePL() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, -2 ); doLoop( ctx, controls, -2, 1, 10, false ); } /** * Do a test with a paged search and send a wrong cookie in the middle */ @Test public void testPagedSearchWrongCookie() throws Exception { LdapNetworkConnection connection = new LdapNetworkConnection( Network.LOOPBACK_HOSTNAME, getLdapServer().getPort() ); connection.bind( "uid=admin,ou=system", "secret" ); SearchControls controls = new SearchControls(); controls.setCountLimit( ( int ) LdapServer.NO_SIZE_LIMIT ); controls.setSearchScope( SearchControls.SUBTREE_SCOPE ); PagedResults pagedSearchControl = new PagedResultsImpl(); pagedSearchControl.setSize( 3 ); // Loop over all the elements int loop = 0; List<Entry> results = new ArrayList<Entry>(); boolean hasUnwillingToPerform = false; while ( true ) { loop++; EntryCursor cursor = null; try { SearchRequest searchRequest = new SearchRequestImpl(); searchRequest.setBase( new Dn( "ou=system" ) ); searchRequest.setFilter( "(ObjectClass=*)" ); searchRequest.setScope( SearchScope.SUBTREE ); searchRequest.addAttributes( "*" ); searchRequest.addControl( pagedSearchControl ); cursor = new EntryCursorImpl( connection.search( searchRequest ) ); int i = 0; while ( cursor.next() ) { Entry result = cursor.get(); results.add( result ); ++i; } SearchResultDone result = cursor.getSearchResultDone(); pagedSearchControl = ( PagedResults ) result.getControl( PagedResults.OID ); if ( result.getLdapResult().getResultCode() == ResultCodeEnum.UNWILLING_TO_PERFORM ) { hasUnwillingToPerform = true; break; } } finally { if ( cursor != null ) { cursor.close(); } } // Now read the next ones assertEquals( 0, pagedSearchControl.getSize() ); // check if this is over byte[] cookie = pagedSearchControl.getCookie(); if ( Strings.isEmpty( cookie ) ) { // If so, exit the loop break; } // Prepare the next iteration, sending a bad cookie pagedSearchControl.setCookie( "test".getBytes( "UTF-8" ) ); pagedSearchControl.setSize( 3 ); } assertTrue( hasUnwillingToPerform ); // Cleanup the session connection.unBind(); connection.close(); } /** * Do a test with a paged search, changing the number of entries to * return in the middle of the loop */ @Test public void testPagedSearchModifyingPagedLimit() throws Exception { getLdapServer().setMaxSizeLimit( LdapServer.NO_SIZE_LIMIT ); DirContext ctx = getWiredContext( getLdapServer(), "cn=user,ou=system", "secret" ); SearchControls controls = createSearchControls( ctx, ( int ) LdapServer.NO_SIZE_LIMIT, 4 ); // Loop over all the elements int loop = 0; List<SearchResult> results = new ArrayList<SearchResult>(); // The expected size after each loop. int[] expectedSize = new int[] { 4, 7, 9, 10 }; while ( true ) { loop++; NamingEnumeration<SearchResult> list = ctx.search( "dc=users,ou=system", "(cn=*)", controls ); while ( list.hasMore() ) { SearchResult result = list.next(); results.add( result ); } list.close(); // Now read the next ones javax.naming.ldap.Control[] responseControls = ( ( LdapContext ) ctx ).getResponseControls(); PagedResultsResponseControl responseControl = ( PagedResultsResponseControl ) responseControls[0]; assertEquals( 0, responseControl.getResultSize() ); // check if this is over byte[] cookie = responseControl.getCookie(); if ( Strings.isEmpty( cookie ) ) { // If so, exit the loop break; } // Prepare the next iteration, sending a bad cookie createNextSearchControls( ctx, responseControl.getCookie(), 4 - loop ); assertEquals( expectedSize[loop - 1], results.size() ); } assertEquals( 4, loop ); checkResults( results, 10 ); // And close the connection closeConnection( ctx ); } }
googleapis/google-cloud-java
36,892
java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListFeaturesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/featurestore_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1; /** * * * <pre> * Response message for * [FeaturestoreService.ListFeatures][google.cloud.aiplatform.v1.FeaturestoreService.ListFeatures]. * Response message for * [FeatureRegistryService.ListFeatures][google.cloud.aiplatform.v1.FeatureRegistryService.ListFeatures]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListFeaturesResponse} */ public final class ListFeaturesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListFeaturesResponse) ListFeaturesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListFeaturesResponse.newBuilder() to construct. private ListFeaturesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListFeaturesResponse() { features_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListFeaturesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListFeaturesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListFeaturesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListFeaturesResponse.class, com.google.cloud.aiplatform.v1.ListFeaturesResponse.Builder.class); } public static final int FEATURES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1.Feature> features_; /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1.Feature> getFeaturesList() { return features_; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1.FeatureOrBuilder> getFeaturesOrBuilderList() { return features_; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ @java.lang.Override public int getFeaturesCount() { return features_.size(); } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.Feature getFeatures(int index) { return features_.get(index); } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.FeatureOrBuilder getFeaturesOrBuilder(int index) { return features_.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 * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.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 * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.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 < features_.size(); i++) { output.writeMessage(1, features_.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 < features_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, features_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1.ListFeaturesResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.ListFeaturesResponse other = (com.google.cloud.aiplatform.v1.ListFeaturesResponse) obj; if (!getFeaturesList().equals(other.getFeaturesList())) 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 (getFeaturesCount() > 0) { hash = (37 * hash) + FEATURES_FIELD_NUMBER; hash = (53 * hash) + getFeaturesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.aiplatform.v1.ListFeaturesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for * [FeaturestoreService.ListFeatures][google.cloud.aiplatform.v1.FeaturestoreService.ListFeatures]. * Response message for * [FeatureRegistryService.ListFeatures][google.cloud.aiplatform.v1.FeatureRegistryService.ListFeatures]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListFeaturesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListFeaturesResponse) com.google.cloud.aiplatform.v1.ListFeaturesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListFeaturesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListFeaturesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListFeaturesResponse.class, com.google.cloud.aiplatform.v1.ListFeaturesResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.ListFeaturesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (featuresBuilder_ == null) { features_ = java.util.Collections.emptyList(); } else { features_ = null; featuresBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListFeaturesResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListFeaturesResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.ListFeaturesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.ListFeaturesResponse build() { com.google.cloud.aiplatform.v1.ListFeaturesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListFeaturesResponse buildPartial() { com.google.cloud.aiplatform.v1.ListFeaturesResponse result = new com.google.cloud.aiplatform.v1.ListFeaturesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1.ListFeaturesResponse result) { if (featuresBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { features_ = java.util.Collections.unmodifiableList(features_); bitField0_ = (bitField0_ & ~0x00000001); } result.features_ = features_; } else { result.features_ = featuresBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1.ListFeaturesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1.ListFeaturesResponse) { return mergeFrom((com.google.cloud.aiplatform.v1.ListFeaturesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListFeaturesResponse other) { if (other == com.google.cloud.aiplatform.v1.ListFeaturesResponse.getDefaultInstance()) return this; if (featuresBuilder_ == null) { if (!other.features_.isEmpty()) { if (features_.isEmpty()) { features_ = other.features_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureFeaturesIsMutable(); features_.addAll(other.features_); } onChanged(); } } else { if (!other.features_.isEmpty()) { if (featuresBuilder_.isEmpty()) { featuresBuilder_.dispose(); featuresBuilder_ = null; features_ = other.features_; bitField0_ = (bitField0_ & ~0x00000001); featuresBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getFeaturesFieldBuilder() : null; } else { featuresBuilder_.addAllMessages(other.features_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.aiplatform.v1.Feature m = input.readMessage( com.google.cloud.aiplatform.v1.Feature.parser(), extensionRegistry); if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.add(m); } else { featuresBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.aiplatform.v1.Feature> features_ = java.util.Collections.emptyList(); private void ensureFeaturesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { features_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1.Feature>(features_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.Feature, com.google.cloud.aiplatform.v1.Feature.Builder, com.google.cloud.aiplatform.v1.FeatureOrBuilder> featuresBuilder_; /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.Feature> getFeaturesList() { if (featuresBuilder_ == null) { return java.util.Collections.unmodifiableList(features_); } else { return featuresBuilder_.getMessageList(); } } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public int getFeaturesCount() { if (featuresBuilder_ == null) { return features_.size(); } else { return featuresBuilder_.getCount(); } } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public com.google.cloud.aiplatform.v1.Feature getFeatures(int index) { if (featuresBuilder_ == null) { return features_.get(index); } else { return featuresBuilder_.getMessage(index); } } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder setFeatures(int index, com.google.cloud.aiplatform.v1.Feature value) { if (featuresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFeaturesIsMutable(); features_.set(index, value); onChanged(); } else { featuresBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder setFeatures( int index, com.google.cloud.aiplatform.v1.Feature.Builder builderForValue) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.set(index, builderForValue.build()); onChanged(); } else { featuresBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder addFeatures(com.google.cloud.aiplatform.v1.Feature value) { if (featuresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFeaturesIsMutable(); features_.add(value); onChanged(); } else { featuresBuilder_.addMessage(value); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder addFeatures(int index, com.google.cloud.aiplatform.v1.Feature value) { if (featuresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFeaturesIsMutable(); features_.add(index, value); onChanged(); } else { featuresBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder addFeatures(com.google.cloud.aiplatform.v1.Feature.Builder builderForValue) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.add(builderForValue.build()); onChanged(); } else { featuresBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder addFeatures( int index, com.google.cloud.aiplatform.v1.Feature.Builder builderForValue) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.add(index, builderForValue.build()); onChanged(); } else { featuresBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder addAllFeatures( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.Feature> values) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, features_); onChanged(); } else { featuresBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder clearFeatures() { if (featuresBuilder_ == null) { features_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { featuresBuilder_.clear(); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public Builder removeFeatures(int index) { if (featuresBuilder_ == null) { ensureFeaturesIsMutable(); features_.remove(index); onChanged(); } else { featuresBuilder_.remove(index); } return this; } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public com.google.cloud.aiplatform.v1.Feature.Builder getFeaturesBuilder(int index) { return getFeaturesFieldBuilder().getBuilder(index); } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public com.google.cloud.aiplatform.v1.FeatureOrBuilder getFeaturesOrBuilder(int index) { if (featuresBuilder_ == null) { return features_.get(index); } else { return featuresBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1.FeatureOrBuilder> getFeaturesOrBuilderList() { if (featuresBuilder_ != null) { return featuresBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(features_); } } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public com.google.cloud.aiplatform.v1.Feature.Builder addFeaturesBuilder() { return getFeaturesFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1.Feature.getDefaultInstance()); } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public com.google.cloud.aiplatform.v1.Feature.Builder addFeaturesBuilder(int index) { return getFeaturesFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1.Feature.getDefaultInstance()); } /** * * * <pre> * The Features matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Feature features = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.Feature.Builder> getFeaturesBuilderList() { return getFeaturesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.Feature, com.google.cloud.aiplatform.v1.Feature.Builder, com.google.cloud.aiplatform.v1.FeatureOrBuilder> getFeaturesFieldBuilder() { if (featuresBuilder_ == null) { featuresBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.Feature, com.google.cloud.aiplatform.v1.Feature.Builder, com.google.cloud.aiplatform.v1.FeatureOrBuilder>( features_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); features_ = null; } return featuresBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.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 * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.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 * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.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 * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.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 * [ListFeaturesRequest.page_token][google.cloud.aiplatform.v1.ListFeaturesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ListFeaturesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListFeaturesResponse) private static final com.google.cloud.aiplatform.v1.ListFeaturesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListFeaturesResponse(); } public static com.google.cloud.aiplatform.v1.ListFeaturesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListFeaturesResponse> PARSER = new com.google.protobuf.AbstractParser<ListFeaturesResponse>() { @java.lang.Override public ListFeaturesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListFeaturesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListFeaturesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListFeaturesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-api-java-client-services
36,929
clients/google-api-services-translate/v2/1.26.0/com/google/api/services/translate/Translate.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.translate; /** * Service definition for Translate (v2). * * <p> * The Google Cloud Translation API lets websites and programs integrate with Google Translate programmatically. * </p> * * <p> * For more information about this service, see the * <a href="https://code.google.com/apis/language/translate/v2/getting_started.html" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link TranslateRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class Translate extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.26.0 of the Google Cloud Translation API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://translation.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "language/translate/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch/translate"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Translate(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ Translate(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Detections collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Detections.List request = translate.detections().list(parameters ...)} * </pre> * * @return the resource collection */ public Detections detections() { return new Detections(); } /** * The "detections" collection of methods. */ public class Detections { /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link Detect#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @return the request */ public Detect detect(com.google.api.services.translate.model.DetectLanguageRequest content) throws java.io.IOException { Detect result = new Detect(content); initialize(result); return result; } public class Detect extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link Detect#execute()} method to invoke the remote operation. * <p> {@link * Detect#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @since 1.13 */ protected Detect(com.google.api.services.translate.model.DetectLanguageRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.DetectionsListResponse.class); } @Override public Detect set$Xgafv(java.lang.String $Xgafv) { return (Detect) super.set$Xgafv($Xgafv); } @Override public Detect setAccessToken(java.lang.String accessToken) { return (Detect) super.setAccessToken(accessToken); } @Override public Detect setAlt(java.lang.String alt) { return (Detect) super.setAlt(alt); } @Override public Detect setBearerToken(java.lang.String bearerToken) { return (Detect) super.setBearerToken(bearerToken); } @Override public Detect setCallback(java.lang.String callback) { return (Detect) super.setCallback(callback); } @Override public Detect setFields(java.lang.String fields) { return (Detect) super.setFields(fields); } @Override public Detect setKey(java.lang.String key) { return (Detect) super.setKey(key); } @Override public Detect setOauthToken(java.lang.String oauthToken) { return (Detect) super.setOauthToken(oauthToken); } @Override public Detect setPp(java.lang.Boolean pp) { return (Detect) super.setPp(pp); } @Override public Detect setPrettyPrint(java.lang.Boolean prettyPrint) { return (Detect) super.setPrettyPrint(prettyPrint); } @Override public Detect setQuotaUser(java.lang.String quotaUser) { return (Detect) super.setQuotaUser(quotaUser); } @Override public Detect setUploadType(java.lang.String uploadType) { return (Detect) super.setUploadType(uploadType); } @Override public Detect setUploadProtocol(java.lang.String uploadProtocol) { return (Detect) super.setUploadProtocol(uploadProtocol); } @Override public Detect set(String parameterName, Object value) { return (Detect) super.set(parameterName, value); } } /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @return the request */ public List list(java.util.List<java.lang.String> q) throws java.io.IOException { List result = new List(q); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @since 1.13 */ protected List(java.util.List<java.lang.String> q) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.DetectionsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text upon which to perform language detection. Repeat this parameter to perform language detection on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Languages collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Languages.List request = translate.languages().list(parameters ...)} * </pre> * * @return the resource collection */ public Languages languages() { return new Languages(); } /** * The "languages" collection of methods. */ public class Languages { /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.LanguagesListResponse> { private static final String REST_PATH = "v2/languages"; /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.LanguagesListResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The model type for which supported languages should be returned. */ @com.google.api.client.util.Key private java.lang.String model; /** The model type for which supported languages should be returned. */ public java.lang.String getModel() { return model; } /** The model type for which supported languages should be returned. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language to use to return localized, human readable names of supported languages. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use to return localized, human readable names of supported languages. */ public java.lang.String getTarget() { return target; } /** * The language to use to return localized, human readable names of supported languages. */ public List setTarget(java.lang.String target) { this.target = target; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Translations collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Translations.List request = translate.translations().list(parameters ...)} * </pre> * * @return the resource collection */ public Translations translations() { return new Translations(); } /** * The "translations" collection of methods. */ public class Translations { /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @return the request */ public List list(java.util.List<java.lang.String> q, java.lang.String target) throws java.io.IOException { List result = new List(q, target); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @since 1.13 */ protected List(java.util.List<java.lang.String> q, java.lang.String target) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.TranslationsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); this.target = com.google.api.client.util.Preconditions.checkNotNull(target, "Required parameter target must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text to translate. Repeat this parameter to perform translation operations on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use for translation of the input text, set to one of the language codes listed in Language Support. */ public java.lang.String getTarget() { return target; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ public List setTarget(java.lang.String target) { this.target = target; return this; } /** The customization id for translate */ @com.google.api.client.util.Key private java.util.List<java.lang.String> cid; /** The customization id for translate */ public java.util.List<java.lang.String> getCid() { return cid; } /** The customization id for translate */ public List setCid(java.util.List<java.lang.String> cid) { this.cid = cid; return this; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ @com.google.api.client.util.Key private java.lang.String format; /** The format of the source text, in either HTML (default) or plain-text. A value of "html" indicates HTML and a value of "text" indicates plain-text. */ public java.lang.String getFormat() { return format; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ public List setFormat(java.lang.String format) { this.format = format; return this; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ @com.google.api.client.util.Key private java.lang.String model; /** The `model` type requested for this translation. Valid values are listed in public documentation. */ public java.lang.String getModel() { return model; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ @com.google.api.client.util.Key private java.lang.String source; /** The language of the source text, set to one of the language codes listed in Language Support. If the source language is not specified, the API will attempt to identify the source language automatically and return it within the response. */ public java.lang.String getSource() { return source; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ public List setSource(java.lang.String source) { this.source = source; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link TranslateOperation#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @return the request */ public TranslateOperation translate(com.google.api.services.translate.model.TranslateTextRequest content) throws java.io.IOException { TranslateOperation result = new TranslateOperation(content); initialize(result); return result; } public class TranslateOperation extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link TranslateOperation#execute()} method to invoke the remote * operation. <p> {@link TranslateOperation#initialize(com.google.api.client.googleapis.services.A * bstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @since 1.13 */ protected TranslateOperation(com.google.api.services.translate.model.TranslateTextRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.TranslationsListResponse.class); } @Override public TranslateOperation set$Xgafv(java.lang.String $Xgafv) { return (TranslateOperation) super.set$Xgafv($Xgafv); } @Override public TranslateOperation setAccessToken(java.lang.String accessToken) { return (TranslateOperation) super.setAccessToken(accessToken); } @Override public TranslateOperation setAlt(java.lang.String alt) { return (TranslateOperation) super.setAlt(alt); } @Override public TranslateOperation setBearerToken(java.lang.String bearerToken) { return (TranslateOperation) super.setBearerToken(bearerToken); } @Override public TranslateOperation setCallback(java.lang.String callback) { return (TranslateOperation) super.setCallback(callback); } @Override public TranslateOperation setFields(java.lang.String fields) { return (TranslateOperation) super.setFields(fields); } @Override public TranslateOperation setKey(java.lang.String key) { return (TranslateOperation) super.setKey(key); } @Override public TranslateOperation setOauthToken(java.lang.String oauthToken) { return (TranslateOperation) super.setOauthToken(oauthToken); } @Override public TranslateOperation setPp(java.lang.Boolean pp) { return (TranslateOperation) super.setPp(pp); } @Override public TranslateOperation setPrettyPrint(java.lang.Boolean prettyPrint) { return (TranslateOperation) super.setPrettyPrint(prettyPrint); } @Override public TranslateOperation setQuotaUser(java.lang.String quotaUser) { return (TranslateOperation) super.setQuotaUser(quotaUser); } @Override public TranslateOperation setUploadType(java.lang.String uploadType) { return (TranslateOperation) super.setUploadType(uploadType); } @Override public TranslateOperation setUploadProtocol(java.lang.String uploadProtocol) { return (TranslateOperation) super.setUploadProtocol(uploadProtocol); } @Override public TranslateOperation set(String parameterName, Object value) { return (TranslateOperation) super.set(parameterName, value); } } } /** * Builder for {@link Translate}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, true); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link Translate}. */ @Override public Translate build() { return new Translate(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link TranslateRequestInitializer}. * * @since 1.12 */ public Builder setTranslateRequestInitializer( TranslateRequestInitializer translateRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(translateRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
googleapis/google-api-java-client-services
36,929
clients/google-api-services-translate/v2/1.27.0/com/google/api/services/translate/Translate.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.translate; /** * Service definition for Translate (v2). * * <p> * The Google Cloud Translation API lets websites and programs integrate with Google Translate programmatically. * </p> * * <p> * For more information about this service, see the * <a href="https://code.google.com/apis/language/translate/v2/getting_started.html" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link TranslateRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class Translate extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.27.0 of the Google Cloud Translation API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://translation.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "language/translate/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch/translate"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Translate(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ Translate(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Detections collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Detections.List request = translate.detections().list(parameters ...)} * </pre> * * @return the resource collection */ public Detections detections() { return new Detections(); } /** * The "detections" collection of methods. */ public class Detections { /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link Detect#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @return the request */ public Detect detect(com.google.api.services.translate.model.DetectLanguageRequest content) throws java.io.IOException { Detect result = new Detect(content); initialize(result); return result; } public class Detect extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link Detect#execute()} method to invoke the remote operation. * <p> {@link * Detect#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @since 1.13 */ protected Detect(com.google.api.services.translate.model.DetectLanguageRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.DetectionsListResponse.class); } @Override public Detect set$Xgafv(java.lang.String $Xgafv) { return (Detect) super.set$Xgafv($Xgafv); } @Override public Detect setAccessToken(java.lang.String accessToken) { return (Detect) super.setAccessToken(accessToken); } @Override public Detect setAlt(java.lang.String alt) { return (Detect) super.setAlt(alt); } @Override public Detect setBearerToken(java.lang.String bearerToken) { return (Detect) super.setBearerToken(bearerToken); } @Override public Detect setCallback(java.lang.String callback) { return (Detect) super.setCallback(callback); } @Override public Detect setFields(java.lang.String fields) { return (Detect) super.setFields(fields); } @Override public Detect setKey(java.lang.String key) { return (Detect) super.setKey(key); } @Override public Detect setOauthToken(java.lang.String oauthToken) { return (Detect) super.setOauthToken(oauthToken); } @Override public Detect setPp(java.lang.Boolean pp) { return (Detect) super.setPp(pp); } @Override public Detect setPrettyPrint(java.lang.Boolean prettyPrint) { return (Detect) super.setPrettyPrint(prettyPrint); } @Override public Detect setQuotaUser(java.lang.String quotaUser) { return (Detect) super.setQuotaUser(quotaUser); } @Override public Detect setUploadType(java.lang.String uploadType) { return (Detect) super.setUploadType(uploadType); } @Override public Detect setUploadProtocol(java.lang.String uploadProtocol) { return (Detect) super.setUploadProtocol(uploadProtocol); } @Override public Detect set(String parameterName, Object value) { return (Detect) super.set(parameterName, value); } } /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @return the request */ public List list(java.util.List<java.lang.String> q) throws java.io.IOException { List result = new List(q); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @since 1.13 */ protected List(java.util.List<java.lang.String> q) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.DetectionsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text upon which to perform language detection. Repeat this parameter to perform language detection on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Languages collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Languages.List request = translate.languages().list(parameters ...)} * </pre> * * @return the resource collection */ public Languages languages() { return new Languages(); } /** * The "languages" collection of methods. */ public class Languages { /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.LanguagesListResponse> { private static final String REST_PATH = "v2/languages"; /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.LanguagesListResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The model type for which supported languages should be returned. */ @com.google.api.client.util.Key private java.lang.String model; /** The model type for which supported languages should be returned. */ public java.lang.String getModel() { return model; } /** The model type for which supported languages should be returned. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language to use to return localized, human readable names of supported languages. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use to return localized, human readable names of supported languages. */ public java.lang.String getTarget() { return target; } /** * The language to use to return localized, human readable names of supported languages. */ public List setTarget(java.lang.String target) { this.target = target; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Translations collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Translations.List request = translate.translations().list(parameters ...)} * </pre> * * @return the resource collection */ public Translations translations() { return new Translations(); } /** * The "translations" collection of methods. */ public class Translations { /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @return the request */ public List list(java.util.List<java.lang.String> q, java.lang.String target) throws java.io.IOException { List result = new List(q, target); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @since 1.13 */ protected List(java.util.List<java.lang.String> q, java.lang.String target) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.TranslationsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); this.target = com.google.api.client.util.Preconditions.checkNotNull(target, "Required parameter target must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text to translate. Repeat this parameter to perform translation operations on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use for translation of the input text, set to one of the language codes listed in Language Support. */ public java.lang.String getTarget() { return target; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ public List setTarget(java.lang.String target) { this.target = target; return this; } /** The customization id for translate */ @com.google.api.client.util.Key private java.util.List<java.lang.String> cid; /** The customization id for translate */ public java.util.List<java.lang.String> getCid() { return cid; } /** The customization id for translate */ public List setCid(java.util.List<java.lang.String> cid) { this.cid = cid; return this; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ @com.google.api.client.util.Key private java.lang.String format; /** The format of the source text, in either HTML (default) or plain-text. A value of "html" indicates HTML and a value of "text" indicates plain-text. */ public java.lang.String getFormat() { return format; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ public List setFormat(java.lang.String format) { this.format = format; return this; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ @com.google.api.client.util.Key private java.lang.String model; /** The `model` type requested for this translation. Valid values are listed in public documentation. */ public java.lang.String getModel() { return model; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ @com.google.api.client.util.Key private java.lang.String source; /** The language of the source text, set to one of the language codes listed in Language Support. If the source language is not specified, the API will attempt to identify the source language automatically and return it within the response. */ public java.lang.String getSource() { return source; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ public List setSource(java.lang.String source) { this.source = source; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link TranslateOperation#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @return the request */ public TranslateOperation translate(com.google.api.services.translate.model.TranslateTextRequest content) throws java.io.IOException { TranslateOperation result = new TranslateOperation(content); initialize(result); return result; } public class TranslateOperation extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link TranslateOperation#execute()} method to invoke the remote * operation. <p> {@link TranslateOperation#initialize(com.google.api.client.googleapis.services.A * bstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @since 1.13 */ protected TranslateOperation(com.google.api.services.translate.model.TranslateTextRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.TranslationsListResponse.class); } @Override public TranslateOperation set$Xgafv(java.lang.String $Xgafv) { return (TranslateOperation) super.set$Xgafv($Xgafv); } @Override public TranslateOperation setAccessToken(java.lang.String accessToken) { return (TranslateOperation) super.setAccessToken(accessToken); } @Override public TranslateOperation setAlt(java.lang.String alt) { return (TranslateOperation) super.setAlt(alt); } @Override public TranslateOperation setBearerToken(java.lang.String bearerToken) { return (TranslateOperation) super.setBearerToken(bearerToken); } @Override public TranslateOperation setCallback(java.lang.String callback) { return (TranslateOperation) super.setCallback(callback); } @Override public TranslateOperation setFields(java.lang.String fields) { return (TranslateOperation) super.setFields(fields); } @Override public TranslateOperation setKey(java.lang.String key) { return (TranslateOperation) super.setKey(key); } @Override public TranslateOperation setOauthToken(java.lang.String oauthToken) { return (TranslateOperation) super.setOauthToken(oauthToken); } @Override public TranslateOperation setPp(java.lang.Boolean pp) { return (TranslateOperation) super.setPp(pp); } @Override public TranslateOperation setPrettyPrint(java.lang.Boolean prettyPrint) { return (TranslateOperation) super.setPrettyPrint(prettyPrint); } @Override public TranslateOperation setQuotaUser(java.lang.String quotaUser) { return (TranslateOperation) super.setQuotaUser(quotaUser); } @Override public TranslateOperation setUploadType(java.lang.String uploadType) { return (TranslateOperation) super.setUploadType(uploadType); } @Override public TranslateOperation setUploadProtocol(java.lang.String uploadProtocol) { return (TranslateOperation) super.setUploadProtocol(uploadProtocol); } @Override public TranslateOperation set(String parameterName, Object value) { return (TranslateOperation) super.set(parameterName, value); } } } /** * Builder for {@link Translate}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, true); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link Translate}. */ @Override public Translate build() { return new Translate(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link TranslateRequestInitializer}. * * @since 1.12 */ public Builder setTranslateRequestInitializer( TranslateRequestInitializer translateRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(translateRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
googleapis/google-api-java-client-services
36,929
clients/google-api-services-translate/v2/1.28.0/com/google/api/services/translate/Translate.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.translate; /** * Service definition for Translate (v2). * * <p> * The Google Cloud Translation API lets websites and programs integrate with Google Translate programmatically. * </p> * * <p> * For more information about this service, see the * <a href="https://code.google.com/apis/language/translate/v2/getting_started.html" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link TranslateRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class Translate extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.28.0 of the Google Cloud Translation API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://translation.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "language/translate/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch/translate"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Translate(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ Translate(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Detections collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Detections.List request = translate.detections().list(parameters ...)} * </pre> * * @return the resource collection */ public Detections detections() { return new Detections(); } /** * The "detections" collection of methods. */ public class Detections { /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link Detect#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @return the request */ public Detect detect(com.google.api.services.translate.model.DetectLanguageRequest content) throws java.io.IOException { Detect result = new Detect(content); initialize(result); return result; } public class Detect extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link Detect#execute()} method to invoke the remote operation. * <p> {@link * Detect#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @since 1.13 */ protected Detect(com.google.api.services.translate.model.DetectLanguageRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.DetectionsListResponse.class); } @Override public Detect set$Xgafv(java.lang.String $Xgafv) { return (Detect) super.set$Xgafv($Xgafv); } @Override public Detect setAccessToken(java.lang.String accessToken) { return (Detect) super.setAccessToken(accessToken); } @Override public Detect setAlt(java.lang.String alt) { return (Detect) super.setAlt(alt); } @Override public Detect setBearerToken(java.lang.String bearerToken) { return (Detect) super.setBearerToken(bearerToken); } @Override public Detect setCallback(java.lang.String callback) { return (Detect) super.setCallback(callback); } @Override public Detect setFields(java.lang.String fields) { return (Detect) super.setFields(fields); } @Override public Detect setKey(java.lang.String key) { return (Detect) super.setKey(key); } @Override public Detect setOauthToken(java.lang.String oauthToken) { return (Detect) super.setOauthToken(oauthToken); } @Override public Detect setPp(java.lang.Boolean pp) { return (Detect) super.setPp(pp); } @Override public Detect setPrettyPrint(java.lang.Boolean prettyPrint) { return (Detect) super.setPrettyPrint(prettyPrint); } @Override public Detect setQuotaUser(java.lang.String quotaUser) { return (Detect) super.setQuotaUser(quotaUser); } @Override public Detect setUploadType(java.lang.String uploadType) { return (Detect) super.setUploadType(uploadType); } @Override public Detect setUploadProtocol(java.lang.String uploadProtocol) { return (Detect) super.setUploadProtocol(uploadProtocol); } @Override public Detect set(String parameterName, Object value) { return (Detect) super.set(parameterName, value); } } /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @return the request */ public List list(java.util.List<java.lang.String> q) throws java.io.IOException { List result = new List(q); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @since 1.13 */ protected List(java.util.List<java.lang.String> q) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.DetectionsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text upon which to perform language detection. Repeat this parameter to perform language detection on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Languages collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Languages.List request = translate.languages().list(parameters ...)} * </pre> * * @return the resource collection */ public Languages languages() { return new Languages(); } /** * The "languages" collection of methods. */ public class Languages { /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.LanguagesListResponse> { private static final String REST_PATH = "v2/languages"; /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.LanguagesListResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The model type for which supported languages should be returned. */ @com.google.api.client.util.Key private java.lang.String model; /** The model type for which supported languages should be returned. */ public java.lang.String getModel() { return model; } /** The model type for which supported languages should be returned. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language to use to return localized, human readable names of supported languages. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use to return localized, human readable names of supported languages. */ public java.lang.String getTarget() { return target; } /** * The language to use to return localized, human readable names of supported languages. */ public List setTarget(java.lang.String target) { this.target = target; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Translations collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Translations.List request = translate.translations().list(parameters ...)} * </pre> * * @return the resource collection */ public Translations translations() { return new Translations(); } /** * The "translations" collection of methods. */ public class Translations { /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @return the request */ public List list(java.util.List<java.lang.String> q, java.lang.String target) throws java.io.IOException { List result = new List(q, target); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @since 1.13 */ protected List(java.util.List<java.lang.String> q, java.lang.String target) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.TranslationsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); this.target = com.google.api.client.util.Preconditions.checkNotNull(target, "Required parameter target must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text to translate. Repeat this parameter to perform translation operations on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use for translation of the input text, set to one of the language codes listed in Language Support. */ public java.lang.String getTarget() { return target; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ public List setTarget(java.lang.String target) { this.target = target; return this; } /** The customization id for translate */ @com.google.api.client.util.Key private java.util.List<java.lang.String> cid; /** The customization id for translate */ public java.util.List<java.lang.String> getCid() { return cid; } /** The customization id for translate */ public List setCid(java.util.List<java.lang.String> cid) { this.cid = cid; return this; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ @com.google.api.client.util.Key private java.lang.String format; /** The format of the source text, in either HTML (default) or plain-text. A value of "html" indicates HTML and a value of "text" indicates plain-text. */ public java.lang.String getFormat() { return format; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ public List setFormat(java.lang.String format) { this.format = format; return this; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ @com.google.api.client.util.Key private java.lang.String model; /** The `model` type requested for this translation. Valid values are listed in public documentation. */ public java.lang.String getModel() { return model; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ @com.google.api.client.util.Key private java.lang.String source; /** The language of the source text, set to one of the language codes listed in Language Support. If the source language is not specified, the API will attempt to identify the source language automatically and return it within the response. */ public java.lang.String getSource() { return source; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ public List setSource(java.lang.String source) { this.source = source; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link TranslateOperation#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @return the request */ public TranslateOperation translate(com.google.api.services.translate.model.TranslateTextRequest content) throws java.io.IOException { TranslateOperation result = new TranslateOperation(content); initialize(result); return result; } public class TranslateOperation extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link TranslateOperation#execute()} method to invoke the remote * operation. <p> {@link TranslateOperation#initialize(com.google.api.client.googleapis.services.A * bstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @since 1.13 */ protected TranslateOperation(com.google.api.services.translate.model.TranslateTextRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.TranslationsListResponse.class); } @Override public TranslateOperation set$Xgafv(java.lang.String $Xgafv) { return (TranslateOperation) super.set$Xgafv($Xgafv); } @Override public TranslateOperation setAccessToken(java.lang.String accessToken) { return (TranslateOperation) super.setAccessToken(accessToken); } @Override public TranslateOperation setAlt(java.lang.String alt) { return (TranslateOperation) super.setAlt(alt); } @Override public TranslateOperation setBearerToken(java.lang.String bearerToken) { return (TranslateOperation) super.setBearerToken(bearerToken); } @Override public TranslateOperation setCallback(java.lang.String callback) { return (TranslateOperation) super.setCallback(callback); } @Override public TranslateOperation setFields(java.lang.String fields) { return (TranslateOperation) super.setFields(fields); } @Override public TranslateOperation setKey(java.lang.String key) { return (TranslateOperation) super.setKey(key); } @Override public TranslateOperation setOauthToken(java.lang.String oauthToken) { return (TranslateOperation) super.setOauthToken(oauthToken); } @Override public TranslateOperation setPp(java.lang.Boolean pp) { return (TranslateOperation) super.setPp(pp); } @Override public TranslateOperation setPrettyPrint(java.lang.Boolean prettyPrint) { return (TranslateOperation) super.setPrettyPrint(prettyPrint); } @Override public TranslateOperation setQuotaUser(java.lang.String quotaUser) { return (TranslateOperation) super.setQuotaUser(quotaUser); } @Override public TranslateOperation setUploadType(java.lang.String uploadType) { return (TranslateOperation) super.setUploadType(uploadType); } @Override public TranslateOperation setUploadProtocol(java.lang.String uploadProtocol) { return (TranslateOperation) super.setUploadProtocol(uploadProtocol); } @Override public TranslateOperation set(String parameterName, Object value) { return (TranslateOperation) super.set(parameterName, value); } } } /** * Builder for {@link Translate}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, true); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link Translate}. */ @Override public Translate build() { return new Translate(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link TranslateRequestInitializer}. * * @since 1.12 */ public Builder setTranslateRequestInitializer( TranslateRequestInitializer translateRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(translateRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
googleapis/google-api-java-client-services
36,929
clients/google-api-services-translate/v2/1.29.2/com/google/api/services/translate/Translate.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.translate; /** * Service definition for Translate (v2). * * <p> * The Google Cloud Translation API lets websites and programs integrate with Google Translate programmatically. * </p> * * <p> * For more information about this service, see the * <a href="https://code.google.com/apis/language/translate/v2/getting_started.html" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link TranslateRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class Translate extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.29.2 of the Google Cloud Translation API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://translation.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "language/translate/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch/translate"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Translate(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ Translate(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Detections collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Detections.List request = translate.detections().list(parameters ...)} * </pre> * * @return the resource collection */ public Detections detections() { return new Detections(); } /** * The "detections" collection of methods. */ public class Detections { /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link Detect#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @return the request */ public Detect detect(com.google.api.services.translate.model.DetectLanguageRequest content) throws java.io.IOException { Detect result = new Detect(content); initialize(result); return result; } public class Detect extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link Detect#execute()} method to invoke the remote operation. * <p> {@link * Detect#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @since 1.13 */ protected Detect(com.google.api.services.translate.model.DetectLanguageRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.DetectionsListResponse.class); } @Override public Detect set$Xgafv(java.lang.String $Xgafv) { return (Detect) super.set$Xgafv($Xgafv); } @Override public Detect setAccessToken(java.lang.String accessToken) { return (Detect) super.setAccessToken(accessToken); } @Override public Detect setAlt(java.lang.String alt) { return (Detect) super.setAlt(alt); } @Override public Detect setBearerToken(java.lang.String bearerToken) { return (Detect) super.setBearerToken(bearerToken); } @Override public Detect setCallback(java.lang.String callback) { return (Detect) super.setCallback(callback); } @Override public Detect setFields(java.lang.String fields) { return (Detect) super.setFields(fields); } @Override public Detect setKey(java.lang.String key) { return (Detect) super.setKey(key); } @Override public Detect setOauthToken(java.lang.String oauthToken) { return (Detect) super.setOauthToken(oauthToken); } @Override public Detect setPp(java.lang.Boolean pp) { return (Detect) super.setPp(pp); } @Override public Detect setPrettyPrint(java.lang.Boolean prettyPrint) { return (Detect) super.setPrettyPrint(prettyPrint); } @Override public Detect setQuotaUser(java.lang.String quotaUser) { return (Detect) super.setQuotaUser(quotaUser); } @Override public Detect setUploadType(java.lang.String uploadType) { return (Detect) super.setUploadType(uploadType); } @Override public Detect setUploadProtocol(java.lang.String uploadProtocol) { return (Detect) super.setUploadProtocol(uploadProtocol); } @Override public Detect set(String parameterName, Object value) { return (Detect) super.set(parameterName, value); } } /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @return the request */ public List list(java.util.List<java.lang.String> q) throws java.io.IOException { List result = new List(q); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @since 1.13 */ protected List(java.util.List<java.lang.String> q) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.DetectionsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text upon which to perform language detection. Repeat this parameter to perform language detection on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Languages collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Languages.List request = translate.languages().list(parameters ...)} * </pre> * * @return the resource collection */ public Languages languages() { return new Languages(); } /** * The "languages" collection of methods. */ public class Languages { /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.LanguagesListResponse> { private static final String REST_PATH = "v2/languages"; /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.LanguagesListResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The model type for which supported languages should be returned. */ @com.google.api.client.util.Key private java.lang.String model; /** The model type for which supported languages should be returned. */ public java.lang.String getModel() { return model; } /** The model type for which supported languages should be returned. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language to use to return localized, human readable names of supported languages. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use to return localized, human readable names of supported languages. */ public java.lang.String getTarget() { return target; } /** * The language to use to return localized, human readable names of supported languages. */ public List setTarget(java.lang.String target) { this.target = target; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Translations collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Translations.List request = translate.translations().list(parameters ...)} * </pre> * * @return the resource collection */ public Translations translations() { return new Translations(); } /** * The "translations" collection of methods. */ public class Translations { /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @return the request */ public List list(java.util.List<java.lang.String> q, java.lang.String target) throws java.io.IOException { List result = new List(q, target); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @since 1.13 */ protected List(java.util.List<java.lang.String> q, java.lang.String target) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.TranslationsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); this.target = com.google.api.client.util.Preconditions.checkNotNull(target, "Required parameter target must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text to translate. Repeat this parameter to perform translation operations on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use for translation of the input text, set to one of the language codes listed in Language Support. */ public java.lang.String getTarget() { return target; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ public List setTarget(java.lang.String target) { this.target = target; return this; } /** The customization id for translate */ @com.google.api.client.util.Key private java.util.List<java.lang.String> cid; /** The customization id for translate */ public java.util.List<java.lang.String> getCid() { return cid; } /** The customization id for translate */ public List setCid(java.util.List<java.lang.String> cid) { this.cid = cid; return this; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ @com.google.api.client.util.Key private java.lang.String format; /** The format of the source text, in either HTML (default) or plain-text. A value of "html" indicates HTML and a value of "text" indicates plain-text. */ public java.lang.String getFormat() { return format; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ public List setFormat(java.lang.String format) { this.format = format; return this; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ @com.google.api.client.util.Key private java.lang.String model; /** The `model` type requested for this translation. Valid values are listed in public documentation. */ public java.lang.String getModel() { return model; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ @com.google.api.client.util.Key private java.lang.String source; /** The language of the source text, set to one of the language codes listed in Language Support. If the source language is not specified, the API will attempt to identify the source language automatically and return it within the response. */ public java.lang.String getSource() { return source; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ public List setSource(java.lang.String source) { this.source = source; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link TranslateOperation#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @return the request */ public TranslateOperation translate(com.google.api.services.translate.model.TranslateTextRequest content) throws java.io.IOException { TranslateOperation result = new TranslateOperation(content); initialize(result); return result; } public class TranslateOperation extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link TranslateOperation#execute()} method to invoke the remote * operation. <p> {@link TranslateOperation#initialize(com.google.api.client.googleapis.services.A * bstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @since 1.13 */ protected TranslateOperation(com.google.api.services.translate.model.TranslateTextRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.TranslationsListResponse.class); } @Override public TranslateOperation set$Xgafv(java.lang.String $Xgafv) { return (TranslateOperation) super.set$Xgafv($Xgafv); } @Override public TranslateOperation setAccessToken(java.lang.String accessToken) { return (TranslateOperation) super.setAccessToken(accessToken); } @Override public TranslateOperation setAlt(java.lang.String alt) { return (TranslateOperation) super.setAlt(alt); } @Override public TranslateOperation setBearerToken(java.lang.String bearerToken) { return (TranslateOperation) super.setBearerToken(bearerToken); } @Override public TranslateOperation setCallback(java.lang.String callback) { return (TranslateOperation) super.setCallback(callback); } @Override public TranslateOperation setFields(java.lang.String fields) { return (TranslateOperation) super.setFields(fields); } @Override public TranslateOperation setKey(java.lang.String key) { return (TranslateOperation) super.setKey(key); } @Override public TranslateOperation setOauthToken(java.lang.String oauthToken) { return (TranslateOperation) super.setOauthToken(oauthToken); } @Override public TranslateOperation setPp(java.lang.Boolean pp) { return (TranslateOperation) super.setPp(pp); } @Override public TranslateOperation setPrettyPrint(java.lang.Boolean prettyPrint) { return (TranslateOperation) super.setPrettyPrint(prettyPrint); } @Override public TranslateOperation setQuotaUser(java.lang.String quotaUser) { return (TranslateOperation) super.setQuotaUser(quotaUser); } @Override public TranslateOperation setUploadType(java.lang.String uploadType) { return (TranslateOperation) super.setUploadType(uploadType); } @Override public TranslateOperation setUploadProtocol(java.lang.String uploadProtocol) { return (TranslateOperation) super.setUploadProtocol(uploadProtocol); } @Override public TranslateOperation set(String parameterName, Object value) { return (TranslateOperation) super.set(parameterName, value); } } } /** * Builder for {@link Translate}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, true); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link Translate}. */ @Override public Translate build() { return new Translate(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link TranslateRequestInitializer}. * * @since 1.12 */ public Builder setTranslateRequestInitializer( TranslateRequestInitializer translateRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(translateRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
googleapis/google-api-java-client-services
36,930
clients/google-api-services-translate/v2/1.30.1/com/google/api/services/translate/Translate.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.translate; /** * Service definition for Translate (v2). * * <p> * The Google Cloud Translation API lets websites and programs integrate with Google Translate programmatically. * </p> * * <p> * For more information about this service, see the * <a href="https://code.google.com/apis/language/translate/v2/getting_started.html" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link TranslateRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class Translate extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.30.10 of the Google Cloud Translation API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://translation.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = "language/translate/"; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch/translate"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Translate(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ Translate(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Detections collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Detections.List request = translate.detections().list(parameters ...)} * </pre> * * @return the resource collection */ public Detections detections() { return new Detections(); } /** * The "detections" collection of methods. */ public class Detections { /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link Detect#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @return the request */ public Detect detect(com.google.api.services.translate.model.DetectLanguageRequest content) throws java.io.IOException { Detect result = new Detect(content); initialize(result); return result; } public class Detect extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.detect". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link Detect#execute()} method to invoke the remote operation. * <p> {@link * Detect#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.DetectLanguageRequest} * @since 1.13 */ protected Detect(com.google.api.services.translate.model.DetectLanguageRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.DetectionsListResponse.class); } @Override public Detect set$Xgafv(java.lang.String $Xgafv) { return (Detect) super.set$Xgafv($Xgafv); } @Override public Detect setAccessToken(java.lang.String accessToken) { return (Detect) super.setAccessToken(accessToken); } @Override public Detect setAlt(java.lang.String alt) { return (Detect) super.setAlt(alt); } @Override public Detect setBearerToken(java.lang.String bearerToken) { return (Detect) super.setBearerToken(bearerToken); } @Override public Detect setCallback(java.lang.String callback) { return (Detect) super.setCallback(callback); } @Override public Detect setFields(java.lang.String fields) { return (Detect) super.setFields(fields); } @Override public Detect setKey(java.lang.String key) { return (Detect) super.setKey(key); } @Override public Detect setOauthToken(java.lang.String oauthToken) { return (Detect) super.setOauthToken(oauthToken); } @Override public Detect setPp(java.lang.Boolean pp) { return (Detect) super.setPp(pp); } @Override public Detect setPrettyPrint(java.lang.Boolean prettyPrint) { return (Detect) super.setPrettyPrint(prettyPrint); } @Override public Detect setQuotaUser(java.lang.String quotaUser) { return (Detect) super.setQuotaUser(quotaUser); } @Override public Detect setUploadType(java.lang.String uploadType) { return (Detect) super.setUploadType(uploadType); } @Override public Detect setUploadProtocol(java.lang.String uploadProtocol) { return (Detect) super.setUploadProtocol(uploadProtocol); } @Override public Detect set(String parameterName, Object value) { return (Detect) super.set(parameterName, value); } } /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @return the request */ public List list(java.util.List<java.lang.String> q) throws java.io.IOException { List result = new List(q); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.DetectionsListResponse> { private static final String REST_PATH = "v2/detect"; /** * Detects the language of text within a request. * * Create a request for the method "detections.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text upon which to perform language detection. Repeat this parameter to perform language * detection on multiple text inputs. * @since 1.13 */ protected List(java.util.List<java.lang.String> q) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.DetectionsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text upon which to perform language detection. Repeat this parameter to perform language detection on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text upon which to perform language detection. Repeat this parameter to perform * language detection on multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Languages collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Languages.List request = translate.languages().list(parameters ...)} * </pre> * * @return the resource collection */ public Languages languages() { return new Languages(); } /** * The "languages" collection of methods. */ public class Languages { /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @return the request */ public List list() throws java.io.IOException { List result = new List(); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.LanguagesListResponse> { private static final String REST_PATH = "v2/languages"; /** * Returns a list of supported languages for translation. * * Create a request for the method "languages.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @since 1.13 */ protected List() { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.LanguagesListResponse.class); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The model type for which supported languages should be returned. */ @com.google.api.client.util.Key private java.lang.String model; /** The model type for which supported languages should be returned. */ public java.lang.String getModel() { return model; } /** The model type for which supported languages should be returned. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language to use to return localized, human readable names of supported languages. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use to return localized, human readable names of supported languages. */ public java.lang.String getTarget() { return target; } /** * The language to use to return localized, human readable names of supported languages. */ public List setTarget(java.lang.String target) { this.target = target; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Translations collection. * * <p>The typical use is:</p> * <pre> * {@code Translate translate = new Translate(...);} * {@code Translate.Translations.List request = translate.translations().list(parameters ...)} * </pre> * * @return the resource collection */ public Translations translations() { return new Translations(); } /** * The "translations" collection of methods. */ public class Translations { /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @return the request */ public List list(java.util.List<java.lang.String> q, java.lang.String target) throws java.io.IOException { List result = new List(q, target); initialize(result); return result; } public class List extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.list". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param q The input text to translate. Repeat this parameter to perform translation operations on multiple * text inputs. * @param target The language to use for translation of the input text, set to one of the language codes listed in * Language Support. * @since 1.13 */ protected List(java.util.List<java.lang.String> q, java.lang.String target) { super(Translate.this, "GET", REST_PATH, null, com.google.api.services.translate.model.TranslationsListResponse.class); this.q = com.google.api.client.util.Preconditions.checkNotNull(q, "Required parameter q must be specified."); this.target = com.google.api.client.util.Preconditions.checkNotNull(target, "Required parameter target must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setBearerToken(java.lang.String bearerToken) { return (List) super.setBearerToken(bearerToken); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPp(java.lang.Boolean pp) { return (List) super.setPp(pp); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> q; /** The input text to translate. Repeat this parameter to perform translation operations on multiple text inputs. */ public java.util.List<java.lang.String> getQ() { return q; } /** * The input text to translate. Repeat this parameter to perform translation operations on * multiple text inputs. */ public List setQ(java.util.List<java.lang.String> q) { this.q = q; return this; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ @com.google.api.client.util.Key private java.lang.String target; /** The language to use for translation of the input text, set to one of the language codes listed in Language Support. */ public java.lang.String getTarget() { return target; } /** * The language to use for translation of the input text, set to one of the language codes * listed in Language Support. */ public List setTarget(java.lang.String target) { this.target = target; return this; } /** The customization id for translate */ @com.google.api.client.util.Key private java.util.List<java.lang.String> cid; /** The customization id for translate */ public java.util.List<java.lang.String> getCid() { return cid; } /** The customization id for translate */ public List setCid(java.util.List<java.lang.String> cid) { this.cid = cid; return this; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ @com.google.api.client.util.Key private java.lang.String format; /** The format of the source text, in either HTML (default) or plain-text. A value of "html" indicates HTML and a value of "text" indicates plain-text. */ public java.lang.String getFormat() { return format; } /** * The format of the source text, in either HTML (default) or plain-text. A value of "html" * indicates HTML and a value of "text" indicates plain-text. */ public List setFormat(java.lang.String format) { this.format = format; return this; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ @com.google.api.client.util.Key private java.lang.String model; /** The `model` type requested for this translation. Valid values are listed in public documentation. */ public java.lang.String getModel() { return model; } /** * The `model` type requested for this translation. Valid values are listed in public * documentation. */ public List setModel(java.lang.String model) { this.model = model; return this; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ @com.google.api.client.util.Key private java.lang.String source; /** The language of the source text, set to one of the language codes listed in Language Support. If the source language is not specified, the API will attempt to identify the source language automatically and return it within the response. */ public java.lang.String getSource() { return source; } /** * The language of the source text, set to one of the language codes listed in Language * Support. If the source language is not specified, the API will attempt to identify the * source language automatically and return it within the response. */ public List setSource(java.lang.String source) { this.source = source; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the translate server. After setting any optional * parameters, call the {@link TranslateOperation#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @return the request */ public TranslateOperation translate(com.google.api.services.translate.model.TranslateTextRequest content) throws java.io.IOException { TranslateOperation result = new TranslateOperation(content); initialize(result); return result; } public class TranslateOperation extends TranslateRequest<com.google.api.services.translate.model.TranslationsListResponse> { private static final String REST_PATH = "v2"; /** * Translates input text, returning translated text. * * Create a request for the method "translations.translate". * * This request holds the parameters needed by the the translate server. After setting any * optional parameters, call the {@link TranslateOperation#execute()} method to invoke the remote * operation. <p> {@link TranslateOperation#initialize(com.google.api.client.googleapis.services.A * bstractGoogleClientRequest)} must be called to initialize this instance immediately after * invoking the constructor. </p> * * @param content the {@link com.google.api.services.translate.model.TranslateTextRequest} * @since 1.13 */ protected TranslateOperation(com.google.api.services.translate.model.TranslateTextRequest content) { super(Translate.this, "POST", REST_PATH, content, com.google.api.services.translate.model.TranslationsListResponse.class); } @Override public TranslateOperation set$Xgafv(java.lang.String $Xgafv) { return (TranslateOperation) super.set$Xgafv($Xgafv); } @Override public TranslateOperation setAccessToken(java.lang.String accessToken) { return (TranslateOperation) super.setAccessToken(accessToken); } @Override public TranslateOperation setAlt(java.lang.String alt) { return (TranslateOperation) super.setAlt(alt); } @Override public TranslateOperation setBearerToken(java.lang.String bearerToken) { return (TranslateOperation) super.setBearerToken(bearerToken); } @Override public TranslateOperation setCallback(java.lang.String callback) { return (TranslateOperation) super.setCallback(callback); } @Override public TranslateOperation setFields(java.lang.String fields) { return (TranslateOperation) super.setFields(fields); } @Override public TranslateOperation setKey(java.lang.String key) { return (TranslateOperation) super.setKey(key); } @Override public TranslateOperation setOauthToken(java.lang.String oauthToken) { return (TranslateOperation) super.setOauthToken(oauthToken); } @Override public TranslateOperation setPp(java.lang.Boolean pp) { return (TranslateOperation) super.setPp(pp); } @Override public TranslateOperation setPrettyPrint(java.lang.Boolean prettyPrint) { return (TranslateOperation) super.setPrettyPrint(prettyPrint); } @Override public TranslateOperation setQuotaUser(java.lang.String quotaUser) { return (TranslateOperation) super.setQuotaUser(quotaUser); } @Override public TranslateOperation setUploadType(java.lang.String uploadType) { return (TranslateOperation) super.setUploadType(uploadType); } @Override public TranslateOperation setUploadProtocol(java.lang.String uploadProtocol) { return (TranslateOperation) super.setUploadProtocol(uploadProtocol); } @Override public TranslateOperation set(String parameterName, Object value) { return (TranslateOperation) super.set(parameterName, value); } } } /** * Builder for {@link Translate}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, true); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link Translate}. */ @Override public Translate build() { return new Translate(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link TranslateRequestInitializer}. * * @since 1.12 */ public Builder setTranslateRequestInitializer( TranslateRequestInitializer translateRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(translateRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
googleapis/google-cloud-java
37,180
java-run/google-cloud-run/src/main/java/com/google/cloud/run/v2/stub/HttpJsonWorkerPoolsStub.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.run.v2.stub; import static com.google.cloud.run.v2.WorkerPoolsClient.ListWorkerPoolsPagedResponse; 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.api.pathtemplate.PathTemplate; import com.google.cloud.run.v2.CreateWorkerPoolRequest; import com.google.cloud.run.v2.DeleteWorkerPoolRequest; import com.google.cloud.run.v2.GetWorkerPoolRequest; import com.google.cloud.run.v2.ListWorkerPoolsRequest; import com.google.cloud.run.v2.ListWorkerPoolsResponse; import com.google.cloud.run.v2.UpdateWorkerPoolRequest; import com.google.cloud.run.v2.WorkerPool; import com.google.common.collect.ImmutableMap; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.protobuf.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 WorkerPools service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonWorkerPoolsStub extends WorkerPoolsStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder().add(WorkerPool.getDescriptor()).build(); private static final ApiMethodDescriptor<CreateWorkerPoolRequest, Operation> createWorkerPoolMethodDescriptor = ApiMethodDescriptor.<CreateWorkerPoolRequest, Operation>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/CreateWorkerPool") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CreateWorkerPoolRequest>newBuilder() .setPath( "/v2/{parent=projects/*/locations/*}/workerPools", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CreateWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CreateWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam( fields, "workerPoolId", request.getWorkerPoolId()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("workerPool", request.getWorkerPool(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (CreateWorkerPoolRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<GetWorkerPoolRequest, WorkerPool> getWorkerPoolMethodDescriptor = ApiMethodDescriptor.<GetWorkerPoolRequest, WorkerPool>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/GetWorkerPool") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetWorkerPoolRequest>newBuilder() .setPath( "/v2/{name=projects/*/locations/*/workerPools/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<WorkerPool>newBuilder() .setDefaultInstance(WorkerPool.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<ListWorkerPoolsRequest, ListWorkerPoolsResponse> listWorkerPoolsMethodDescriptor = ApiMethodDescriptor.<ListWorkerPoolsRequest, ListWorkerPoolsResponse>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/ListWorkerPools") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListWorkerPoolsRequest>newBuilder() .setPath( "/v2/{parent=projects/*/locations/*}/workerPools", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListWorkerPoolsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListWorkerPoolsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "pageSize", request.getPageSize()); serializer.putQueryParam(fields, "pageToken", request.getPageToken()); serializer.putQueryParam( fields, "showDeleted", request.getShowDeleted()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListWorkerPoolsResponse>newBuilder() .setDefaultInstance(ListWorkerPoolsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<UpdateWorkerPoolRequest, Operation> updateWorkerPoolMethodDescriptor = ApiMethodDescriptor.<UpdateWorkerPoolRequest, Operation>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/UpdateWorkerPool") .setHttpMethod("PATCH") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<UpdateWorkerPoolRequest>newBuilder() .setPath( "/v2/{workerPool.name=projects/*/locations/*/workerPools/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<UpdateWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam( fields, "workerPool.name", request.getWorkerPool().getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<UpdateWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam( fields, "allowMissing", request.getAllowMissing()); serializer.putQueryParam( fields, "forceNewRevision", request.getForceNewRevision()); serializer.putQueryParam(fields, "updateMask", request.getUpdateMask()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("workerPool", request.getWorkerPool(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (UpdateWorkerPoolRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<DeleteWorkerPoolRequest, Operation> deleteWorkerPoolMethodDescriptor = ApiMethodDescriptor.<DeleteWorkerPoolRequest, Operation>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/DeleteWorkerPool") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteWorkerPoolRequest>newBuilder() .setPath( "/v2/{name=projects/*/locations/*/workerPools/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteWorkerPoolRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "etag", request.getEtag()); serializer.putQueryParam( fields, "validateOnly", request.getValidateOnly()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeleteWorkerPoolRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor = ApiMethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/GetIamPolicy") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetIamPolicyRequest>newBuilder() .setPath( "/v2/{resource=projects/*/locations/*/workerPools/*}:getIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "options", request.getOptions()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor = ApiMethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/SetIamPolicy") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<SetIamPolicyRequest>newBuilder() .setPath( "/v2/{resource=projects/*/locations/*/workerPools/*}:setIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsMethodDescriptor = ApiMethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setFullMethodName("google.cloud.run.v2.WorkerPools/TestIamPermissions") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<TestIamPermissionsRequest>newBuilder() .setPath( "/v2/{resource=projects/*/locations/*/workerPools/*}:testIamPermissions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<TestIamPermissionsResponse>newBuilder() .setDefaultInstance(TestIamPermissionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<CreateWorkerPoolRequest, Operation> createWorkerPoolCallable; private final OperationCallable<CreateWorkerPoolRequest, WorkerPool, WorkerPool> createWorkerPoolOperationCallable; private final UnaryCallable<GetWorkerPoolRequest, WorkerPool> getWorkerPoolCallable; private final UnaryCallable<ListWorkerPoolsRequest, ListWorkerPoolsResponse> listWorkerPoolsCallable; private final UnaryCallable<ListWorkerPoolsRequest, ListWorkerPoolsPagedResponse> listWorkerPoolsPagedCallable; private final UnaryCallable<UpdateWorkerPoolRequest, Operation> updateWorkerPoolCallable; private final OperationCallable<UpdateWorkerPoolRequest, WorkerPool, WorkerPool> updateWorkerPoolOperationCallable; private final UnaryCallable<DeleteWorkerPoolRequest, Operation> deleteWorkerPoolCallable; private final OperationCallable<DeleteWorkerPoolRequest, WorkerPool, WorkerPool> deleteWorkerPoolOperationCallable; private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable; private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable; private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final HttpJsonOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; private static final PathTemplate CREATE_WORKER_POOL_0_PATH_TEMPLATE = PathTemplate.create("projects/*/locations/{location=*}"); private static final PathTemplate GET_WORKER_POOL_0_PATH_TEMPLATE = PathTemplate.create("projects/*/locations/{location=*}/**"); private static final PathTemplate LIST_WORKER_POOLS_0_PATH_TEMPLATE = PathTemplate.create("projects/*/locations/{location=*}"); private static final PathTemplate UPDATE_WORKER_POOL_0_PATH_TEMPLATE = PathTemplate.create("projects/*/locations/{location=*}/**"); private static final PathTemplate DELETE_WORKER_POOL_0_PATH_TEMPLATE = PathTemplate.create("projects/*/locations/{location=*}/**"); public static final HttpJsonWorkerPoolsStub create(WorkerPoolsStubSettings settings) throws IOException { return new HttpJsonWorkerPoolsStub(settings, ClientContext.create(settings)); } public static final HttpJsonWorkerPoolsStub create(ClientContext clientContext) throws IOException { return new HttpJsonWorkerPoolsStub( WorkerPoolsStubSettings.newHttpJsonBuilder().build(), clientContext); } public static final HttpJsonWorkerPoolsStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonWorkerPoolsStub( WorkerPoolsStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonWorkerPoolsStub, 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 HttpJsonWorkerPoolsStub(WorkerPoolsStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonWorkerPoolsCallableFactory()); } /** * Constructs an instance of HttpJsonWorkerPoolsStub, 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 HttpJsonWorkerPoolsStub( WorkerPoolsStubSettings 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.DeleteOperation", HttpRule.newBuilder() .setDelete("/v2/{name=projects/*/locations/*/operations/*}") .build()) .put( "google.longrunning.Operations.GetOperation", HttpRule.newBuilder() .setGet("/v2/{name=projects/*/locations/*/operations/*}") .build()) .put( "google.longrunning.Operations.ListOperations", HttpRule.newBuilder() .setGet("/v2/{name=projects/*/locations/*}/operations") .build()) .put( "google.longrunning.Operations.WaitOperation", HttpRule.newBuilder() .setPost("/v2/{name=projects/*/locations/*/operations/*}:wait") .build()) .build()); HttpJsonCallSettings<CreateWorkerPoolRequest, Operation> createWorkerPoolTransportSettings = HttpJsonCallSettings.<CreateWorkerPoolRequest, Operation>newBuilder() .setMethodDescriptor(createWorkerPoolMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add(request.getParent(), "location", CREATE_WORKER_POOL_0_PATH_TEMPLATE); return builder.build(); }) .build(); HttpJsonCallSettings<GetWorkerPoolRequest, WorkerPool> getWorkerPoolTransportSettings = HttpJsonCallSettings.<GetWorkerPoolRequest, WorkerPool>newBuilder() .setMethodDescriptor(getWorkerPoolMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add(request.getName(), "location", GET_WORKER_POOL_0_PATH_TEMPLATE); return builder.build(); }) .build(); HttpJsonCallSettings<ListWorkerPoolsRequest, ListWorkerPoolsResponse> listWorkerPoolsTransportSettings = HttpJsonCallSettings.<ListWorkerPoolsRequest, ListWorkerPoolsResponse>newBuilder() .setMethodDescriptor(listWorkerPoolsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add( request.getParent(), "location", LIST_WORKER_POOLS_0_PATH_TEMPLATE); return builder.build(); }) .build(); HttpJsonCallSettings<UpdateWorkerPoolRequest, Operation> updateWorkerPoolTransportSettings = HttpJsonCallSettings.<UpdateWorkerPoolRequest, Operation>newBuilder() .setMethodDescriptor(updateWorkerPoolMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); if (request.getWorkerPool() != null) { builder.add( request.getWorkerPool().getName(), "location", UPDATE_WORKER_POOL_0_PATH_TEMPLATE); } return builder.build(); }) .build(); HttpJsonCallSettings<DeleteWorkerPoolRequest, Operation> deleteWorkerPoolTransportSettings = HttpJsonCallSettings.<DeleteWorkerPoolRequest, Operation>newBuilder() .setMethodDescriptor(deleteWorkerPoolMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add(request.getName(), "location", DELETE_WORKER_POOL_0_PATH_TEMPLATE); return builder.build(); }) .build(); HttpJsonCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings = HttpJsonCallSettings.<GetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(getIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings = HttpJsonCallSettings.<SetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(setIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsTransportSettings = HttpJsonCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.createWorkerPoolCallable = callableFactory.createUnaryCallable( createWorkerPoolTransportSettings, settings.createWorkerPoolSettings(), clientContext); this.createWorkerPoolOperationCallable = callableFactory.createOperationCallable( createWorkerPoolTransportSettings, settings.createWorkerPoolOperationSettings(), clientContext, httpJsonOperationsStub); this.getWorkerPoolCallable = callableFactory.createUnaryCallable( getWorkerPoolTransportSettings, settings.getWorkerPoolSettings(), clientContext); this.listWorkerPoolsCallable = callableFactory.createUnaryCallable( listWorkerPoolsTransportSettings, settings.listWorkerPoolsSettings(), clientContext); this.listWorkerPoolsPagedCallable = callableFactory.createPagedCallable( listWorkerPoolsTransportSettings, settings.listWorkerPoolsSettings(), clientContext); this.updateWorkerPoolCallable = callableFactory.createUnaryCallable( updateWorkerPoolTransportSettings, settings.updateWorkerPoolSettings(), clientContext); this.updateWorkerPoolOperationCallable = callableFactory.createOperationCallable( updateWorkerPoolTransportSettings, settings.updateWorkerPoolOperationSettings(), clientContext, httpJsonOperationsStub); this.deleteWorkerPoolCallable = callableFactory.createUnaryCallable( deleteWorkerPoolTransportSettings, settings.deleteWorkerPoolSettings(), clientContext); this.deleteWorkerPoolOperationCallable = callableFactory.createOperationCallable( deleteWorkerPoolTransportSettings, settings.deleteWorkerPoolOperationSettings(), clientContext, httpJsonOperationsStub); this.getIamPolicyCallable = callableFactory.createUnaryCallable( getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); this.setIamPolicyCallable = callableFactory.createUnaryCallable( setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); 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(createWorkerPoolMethodDescriptor); methodDescriptors.add(getWorkerPoolMethodDescriptor); methodDescriptors.add(listWorkerPoolsMethodDescriptor); methodDescriptors.add(updateWorkerPoolMethodDescriptor); methodDescriptors.add(deleteWorkerPoolMethodDescriptor); methodDescriptors.add(getIamPolicyMethodDescriptor); methodDescriptors.add(setIamPolicyMethodDescriptor); methodDescriptors.add(testIamPermissionsMethodDescriptor); return methodDescriptors; } public HttpJsonOperationsStub getHttpJsonOperationsStub() { return httpJsonOperationsStub; } @Override public UnaryCallable<CreateWorkerPoolRequest, Operation> createWorkerPoolCallable() { return createWorkerPoolCallable; } @Override public OperationCallable<CreateWorkerPoolRequest, WorkerPool, WorkerPool> createWorkerPoolOperationCallable() { return createWorkerPoolOperationCallable; } @Override public UnaryCallable<GetWorkerPoolRequest, WorkerPool> getWorkerPoolCallable() { return getWorkerPoolCallable; } @Override public UnaryCallable<ListWorkerPoolsRequest, ListWorkerPoolsResponse> listWorkerPoolsCallable() { return listWorkerPoolsCallable; } @Override public UnaryCallable<ListWorkerPoolsRequest, ListWorkerPoolsPagedResponse> listWorkerPoolsPagedCallable() { return listWorkerPoolsPagedCallable; } @Override public UnaryCallable<UpdateWorkerPoolRequest, Operation> updateWorkerPoolCallable() { return updateWorkerPoolCallable; } @Override public OperationCallable<UpdateWorkerPoolRequest, WorkerPool, WorkerPool> updateWorkerPoolOperationCallable() { return updateWorkerPoolOperationCallable; } @Override public UnaryCallable<DeleteWorkerPoolRequest, Operation> deleteWorkerPoolCallable() { return deleteWorkerPoolCallable; } @Override public OperationCallable<DeleteWorkerPoolRequest, WorkerPool, WorkerPool> deleteWorkerPoolOperationCallable() { return deleteWorkerPoolOperationCallable; } @Override public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return getIamPolicyCallable; } @Override public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return setIamPolicyCallable; } @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); } }
oracle/graal
37,070
truffle/src/com.oracle.truffle.api.test/src/com/oracle/truffle/api/test/profiles/PrimitiveValueProfileTest.java
/* * Copyright (c) 2014, 2022, 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.profiles; import static com.oracle.truffle.api.test.ReflectionUtils.invoke; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import java.util.Objects; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import com.oracle.truffle.api.profiles.PrimitiveValueProfile; import com.oracle.truffle.api.test.ReflectionUtils; import com.oracle.truffle.tck.tests.TruffleTestAssumptions; @RunWith(Theories.class) @SuppressWarnings("deprecation") public class PrimitiveValueProfileTest { @DataPoint public static final String O1 = new String(); @DataPoint public static final String O2 = O1; @DataPoint public static final Object O3 = new Object(); @DataPoint public static final Object O4 = null; @DataPoint public static final byte B1 = Byte.MIN_VALUE; @DataPoint public static final byte B2 = 0; @DataPoint public static final byte B3 = 14; @DataPoint public static final byte B4 = Byte.MAX_VALUE; @DataPoint public static final short S1 = Short.MIN_VALUE; @DataPoint public static final short S2 = 0; @DataPoint public static final short S3 = 14; @DataPoint public static final short S4 = Short.MAX_VALUE; @DataPoint public static final int I1 = Integer.MIN_VALUE; @DataPoint public static final int I2 = 0; @DataPoint public static final int I3 = 14; @DataPoint public static final int I4 = Integer.MAX_VALUE; @DataPoint public static final long L1 = Long.MIN_VALUE; @DataPoint public static final long L2 = 0; @DataPoint public static final long L3 = 14; @DataPoint public static final long L4 = Long.MAX_VALUE; @DataPoint public static final float F1 = Float.MIN_VALUE; @DataPoint public static final float F2 = -0.0f; @DataPoint public static final float F3 = +0.0f; @DataPoint public static final float F4 = 14.5f; @DataPoint public static final float F5 = Float.MAX_VALUE; @DataPoint public static final double D1 = Double.MIN_VALUE; @DataPoint public static final double D2 = -0.0; @DataPoint public static final double D3 = +0.0; @DataPoint public static final double D4 = 14.5; @DataPoint public static final double D5 = Double.MAX_VALUE; @DataPoint public static final boolean T1 = false; @DataPoint public static final boolean T2 = true; @DataPoint public static final char C1 = Character.MIN_VALUE; @DataPoint public static final char C2 = 0; @DataPoint public static final char C3 = 14; @DataPoint public static final char C4 = Character.MAX_VALUE; private static final float FLOAT_DELTA = 0.00001f; private static final double DOUBLE_DELTA = 0.00001; @BeforeClass public static void runWithWeakEncapsulationOnly() { TruffleTestAssumptions.assumeWeakEncapsulation(); } private PrimitiveValueProfile profile; @Before public void create() { profile = ReflectionUtils.newInstance(PrimitiveValueProfile.class); } private static boolean isGeneric(PrimitiveValueProfile profile) { return (boolean) invoke(profile, "isGeneric"); } private static boolean isUninitialized(PrimitiveValueProfile profile) { return (boolean) invoke(profile, "isUninitialized"); } private static Object getCachedValue(PrimitiveValueProfile profile) { return invoke(profile, "getCachedValue"); } @Test public void testInitial() { assertThat(isGeneric(profile), is(false)); assertThat(isUninitialized(profile), is(true)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneObject(Object value) { Object result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } private static boolean primitiveEquals(Object value0, Object value1) { return Objects.equals(value0, value1); } @Theory public void testProfileTwoObject(Object value0, Object value1) { Object result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertThat(result0, is(value0)); assertThat(result1, is(value1)); if (primitiveEquals(value0, value1)) { assertThat(getCachedValue(profile), is(value0)); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneByte(byte value) { byte result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoByte(byte value0, byte value1) { byte result0 = profile.profile(value0); byte result1 = profile.profile(value1); assertEquals(result0, value0); assertEquals(result1, value1); if (value0 == value1) { assertTrue(getCachedValue(profile) instanceof Byte); assertEquals((byte) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeByte(byte value0, byte value1, byte value2) { byte result0 = profile.profile(value0); byte result1 = profile.profile(value1); byte result2 = profile.profile(value2); assertEquals(result0, value0); assertEquals(result1, value1); assertEquals(result2, value2); if (value0 == value1 && value1 == value2) { assertTrue(getCachedValue(profile) instanceof Byte); assertEquals((byte) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneShort(short value) { short result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoShort(short value0, short value1) { short result0 = profile.profile(value0); short result1 = profile.profile(value1); assertEquals(result0, value0); assertEquals(result1, value1); if (value0 == value1) { assertTrue(getCachedValue(profile) instanceof Short); assertEquals((short) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeShort(short value0, short value1, short value2) { short result0 = profile.profile(value0); short result1 = profile.profile(value1); short result2 = profile.profile(value2); assertEquals(result0, value0); assertEquals(result1, value1); assertEquals(result2, value2); if (value0 == value1 && value1 == value2) { assertTrue(getCachedValue(profile) instanceof Short); assertEquals((short) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneInteger(int value) { int result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoInteger(int value0, int value1) { int result0 = profile.profile(value0); int result1 = profile.profile(value1); assertEquals(result0, value0); assertEquals(result1, value1); if (value0 == value1) { assertTrue(getCachedValue(profile) instanceof Integer); assertEquals((int) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeInteger(int value0, int value1, int value2) { int result0 = profile.profile(value0); int result1 = profile.profile(value1); int result2 = profile.profile(value2); assertEquals(result0, value0); assertEquals(result1, value1); assertEquals(result2, value2); if (value0 == value1 && value1 == value2) { assertTrue(getCachedValue(profile) instanceof Integer); assertEquals((int) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneLong(long value) { long result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoLong(long value0, long value1) { long result0 = profile.profile(value0); long result1 = profile.profile(value1); assertEquals(result0, value0); assertEquals(result1, value1); if (value0 == value1) { assertTrue(getCachedValue(profile) instanceof Long); assertEquals((long) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeLong(long value0, long value1, long value2) { long result0 = profile.profile(value0); long result1 = profile.profile(value1); long result2 = profile.profile(value2); assertEquals(result0, value0); assertEquals(result1, value1); assertEquals(result2, value2); if (value0 == value1 && value1 == value2) { assertTrue(getCachedValue(profile) instanceof Long); assertEquals((long) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneFloat(float value) { float result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoFloat(float value0, float value1) { float result0 = profile.profile(value0); float result1 = profile.profile(value1); assertEquals(result0, value0, FLOAT_DELTA); assertEquals(result1, value1, FLOAT_DELTA); if (exactCompare(value0, value1)) { assertTrue(getCachedValue(profile) instanceof Float); assertEquals((float) getCachedValue(profile), value0, FLOAT_DELTA); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeFloat(float value0, float value1, float value2) { float result0 = profile.profile(value0); float result1 = profile.profile(value1); float result2 = profile.profile(value2); assertEquals(result0, value0, FLOAT_DELTA); assertEquals(result1, value1, FLOAT_DELTA); assertEquals(result2, value2, FLOAT_DELTA); if (exactCompare(value0, value1) && exactCompare(value1, value2)) { assertTrue(getCachedValue(profile) instanceof Float); assertEquals((float) getCachedValue(profile), value0, FLOAT_DELTA); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneDouble(double value) { double result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoDouble(double value0, double value1) { double result0 = profile.profile(value0); double result1 = profile.profile(value1); assertEquals(result0, value0, DOUBLE_DELTA); assertEquals(result1, value1, DOUBLE_DELTA); if (exactCompare(value0, value1)) { assertTrue(getCachedValue(profile) instanceof Double); assertEquals((double) getCachedValue(profile), value0, DOUBLE_DELTA); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeDouble(double value0, double value1, double value2) { double result0 = profile.profile(value0); double result1 = profile.profile(value1); double result2 = profile.profile(value2); assertEquals(result0, value0, DOUBLE_DELTA); assertEquals(result1, value1, DOUBLE_DELTA); assertEquals(result2, value2, DOUBLE_DELTA); if (exactCompare(value0, value1) && exactCompare(value1, value2)) { assertTrue(getCachedValue(profile) instanceof Double); assertEquals((double) getCachedValue(profile), value0, DOUBLE_DELTA); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneBoolean(boolean value) { boolean result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoBoolean(boolean value0, boolean value1) { boolean result0 = profile.profile(value0); boolean result1 = profile.profile(value1); assertEquals(result0, value0); assertEquals(result1, value1); if (value0 == value1) { assertTrue(getCachedValue(profile) instanceof Boolean); assertEquals((boolean) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeBoolean(boolean value0, boolean value1, boolean value2) { boolean result0 = profile.profile(value0); boolean result1 = profile.profile(value1); boolean result2 = profile.profile(value2); assertEquals(result0, value0); assertEquals(result1, value1); assertEquals(result2, value2); if (value0 == value1 && value1 == value2) { assertTrue(getCachedValue(profile) instanceof Boolean); assertEquals((boolean) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileOneChar(char value) { char result = profile.profile(value); assertThat(result, is(value)); assertEquals(getCachedValue(profile), value); assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileTwoChar(char value0, char value1) { char result0 = profile.profile(value0); char result1 = profile.profile(value1); assertEquals(result0, value0); assertEquals(result1, value1); if (value0 == value1) { assertTrue(getCachedValue(profile) instanceof Character); assertEquals((char) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testProfileThreeChar(char value0, char value1, char value2) { char result0 = profile.profile(value0); char result1 = profile.profile(value1); char result2 = profile.profile(value2); assertEquals(result0, value0); assertEquals(result1, value1); assertEquals(result2, value2); if (value0 == value1 && value1 == value2) { assertTrue(getCachedValue(profile) instanceof Character); assertEquals((char) getCachedValue(profile), value0); assertThat(isGeneric(profile), is(false)); } else { assertThat(isGeneric(profile), is(true)); } assertThat(isUninitialized(profile), is(false)); profile.toString(); // test that it is not crashing } @Theory public void testWithBoxedBoxedByte(byte value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Byte); assertEquals((byte) result0, value); assertTrue(result1 instanceof Byte); assertEquals((byte) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedByte(byte value) { byte result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertEquals(result0, value); assertTrue(result1 instanceof Byte); assertEquals((byte) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedByte(byte value) { Object result0 = profile.profile((Object) value); byte result1 = profile.profile(value); assertTrue(result0 instanceof Byte); assertEquals((byte) result0, value); assertEquals(result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedShort(short value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Short); assertEquals((short) result0, value); assertTrue(result1 instanceof Short); assertEquals((short) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedShort(short value) { short result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertEquals(result0, value); assertTrue(result1 instanceof Short); assertEquals((short) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedShort(short value) { Object result0 = profile.profile((Object) value); short result1 = profile.profile(value); assertTrue(result0 instanceof Short); assertEquals((short) result0, value); assertEquals(result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedInt(int value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Integer); assertEquals((int) result0, value); assertTrue(result1 instanceof Integer); assertEquals((int) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedInt(int value) { int result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertEquals(result0, value); assertTrue(result1 instanceof Integer); assertEquals((int) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedInt(int value) { Object result0 = profile.profile((Object) value); int result1 = profile.profile(value); assertTrue(result0 instanceof Integer); assertEquals((int) result0, value); assertEquals(result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedLong(long value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Long); assertEquals((long) result0, value); assertTrue(result1 instanceof Long); assertEquals((long) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedLong(long value) { long result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertEquals(result0, value); assertTrue(result1 instanceof Long); assertEquals((long) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedLong(long value) { Object result0 = profile.profile((Object) value); long result1 = profile.profile(value); assertTrue(result0 instanceof Long); assertEquals((long) result0, value); assertEquals(result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedFloat(float value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Float); assertTrue(exactCompare((float) result0, value)); assertTrue(result1 instanceof Float); assertTrue(exactCompare((float) result1, value)); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedFloat(float value) { float result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertTrue(exactCompare(result0, value)); assertTrue(result1 instanceof Float); assertTrue(exactCompare((float) result1, value)); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedFloat(float value) { Object result0 = profile.profile((Object) value); float result1 = profile.profile(value); assertTrue(result0 instanceof Float); assertTrue(exactCompare((float) result0, value)); assertTrue(exactCompare(result1, value)); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedDouble(double value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Double); assertTrue(exactCompare((double) result0, value)); assertTrue(result1 instanceof Double); assertTrue(exactCompare((double) result1, value)); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedDouble(double value) { double result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertTrue(exactCompare(result0, value)); assertTrue(result1 instanceof Double); assertTrue(exactCompare((double) result1, value)); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedDouble(double value) { Object result0 = profile.profile((Object) value); double result1 = profile.profile(value); assertTrue(result0 instanceof Double); assertTrue(exactCompare((double) result0, value)); assertTrue(exactCompare(result1, value)); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedBoolean(boolean value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Boolean); assertEquals((boolean) result0, value); assertTrue(result1 instanceof Boolean); assertEquals((boolean) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedBoolean(boolean value) { boolean result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertEquals(result0, value); assertTrue(result1 instanceof Boolean); assertEquals((boolean) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedBoolean(boolean value) { Object result0 = profile.profile((Object) value); boolean result1 = profile.profile(value); assertTrue(result0 instanceof Boolean); assertEquals((boolean) result0, value); assertEquals(result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedBoxedChar(char value) { Object result0 = profile.profile((Object) value); Object result1 = profile.profile((Object) value); assertTrue(result0 instanceof Character); assertEquals((char) result0, value); assertTrue(result1 instanceof Character); assertEquals((char) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithUnboxedBoxedChar(char value) { char result0 = profile.profile(value); Object result1 = profile.profile((Object) value); assertEquals(result0, value); assertTrue(result1 instanceof Character); assertEquals((char) result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithBoxedUnboxedCharacter(char value) { Object result0 = profile.profile((Object) value); char result1 = profile.profile(value); assertTrue(result0 instanceof Character); assertEquals((char) result0, value); assertEquals(result1, value); assertFalse(isUninitialized(profile)); assertFalse(isGeneric(profile)); } @Theory public void testWithByteThenObject(byte value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); byte result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertEquals(result0, value0); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithShortThenObject(short value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); short result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertEquals(result0, value0); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithIntThenObject(int value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); int result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertEquals(result0, value0); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithLongThenObject(long value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); long result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertEquals(result0, value0); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithFloatThenObject(float value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); float result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertTrue(exactCompare(result0, value0)); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithDoubleThenObject(double value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); double result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertTrue(exactCompare(result0, value0)); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithBooleanThenObject(boolean value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); boolean result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertEquals(result0, value0); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Theory public void testWithCharThenObject(char value0, Object value1) { assumeThat(value0, is(not(equalTo(value1)))); char result0 = profile.profile(value0); Object result1 = profile.profile(value1); assertEquals(result0, value0); assertSame(result1, value1); assertFalse(isUninitialized(profile)); assertTrue(isGeneric(profile)); } @Test public void testNegativeZeroFloat() { profile.profile(-0.0f); profile.profile(+0.0f); assertThat(isGeneric(profile), is(true)); } @Test public void testNegativeZeroDouble() { profile.profile(-0.0); profile.profile(+0.0); assertThat(isGeneric(profile), is(true)); } @Test public void testDisabled() { PrimitiveValueProfile p = PrimitiveValueProfile.getUncached(); assertThat(p.profile(O1), is(O1)); assertThat(p.profile(B1), is(B1)); assertThat(p.profile(S1), is(S1)); assertThat(p.profile(I1), is(I1)); assertThat(p.profile(L1), is(L1)); assertThat(p.profile(F1), is(F1)); assertThat(p.profile(D1), is(D1)); assertThat(p.profile(T1), is(T1)); assertThat(p.profile(C1), is(C1)); p.toString(); // test that it is not crashing } static boolean exactCompare(float a, float b) { /* * -0.0 == 0.0, but you can tell the difference through other means, so we need to * differentiate. */ return Float.floatToRawIntBits(a) == Float.floatToRawIntBits(b); } static boolean exactCompare(double a, double b) { /* * -0.0 == 0.0, but you can tell the difference through other means, so we need to * differentiate. */ return Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b); } }
apache/rya
37,025
extras/indexing/src/main/java/org/apache/rya/indexing/accumulo/freetext/AccumuloFreeTextIndexer.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.rya.indexing.accumulo.freetext; import static java.util.Objects.requireNonNull; import static org.apache.rya.indexing.accumulo.freetext.query.ASTNodeUtils.getNodeIterator; import java.io.IOException; import java.nio.charset.CharacterCodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.IteratorSetting; import org.apache.accumulo.core.client.MultiTableBatchWriter; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.admin.TableOperations; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.file.keyfunctor.ColumnFamilyFunctor; import org.apache.accumulo.core.iterators.user.IntersectingIterator; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import org.apache.rya.accumulo.experimental.AbstractAccumuloIndexer; import org.apache.rya.api.RdfCloudTripleStoreConfiguration; import org.apache.rya.api.domain.RyaStatement; import org.apache.rya.api.resolver.RyaToRdfConversions; import org.apache.rya.indexing.FreeTextIndexer; import org.apache.rya.indexing.Md5Hash; import org.apache.rya.indexing.StatementConstraints; import org.apache.rya.indexing.StatementSerializer; import org.apache.rya.indexing.accumulo.ConfigUtils; import org.apache.rya.indexing.accumulo.freetext.iterators.BooleanTreeIterator; import org.apache.rya.indexing.accumulo.freetext.query.ASTExpression; import org.apache.rya.indexing.accumulo.freetext.query.ASTNodeUtils; import org.apache.rya.indexing.accumulo.freetext.query.ASTSimpleNode; import org.apache.rya.indexing.accumulo.freetext.query.ASTTerm; import org.apache.rya.indexing.accumulo.freetext.query.ParseException; import org.apache.rya.indexing.accumulo.freetext.query.QueryParser; import org.apache.rya.indexing.accumulo.freetext.query.QueryParserTreeConstants; import org.apache.rya.indexing.accumulo.freetext.query.SimpleNode; import org.apache.rya.indexing.accumulo.freetext.query.TokenMgrError; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.query.QueryEvaluationException; import com.google.common.base.Charsets; import com.google.common.collect.Lists; /** * The {@link AccumuloFreeTextIndexer} stores and queries "free text" data from statements into tables in Accumulo. Specifically, this class * stores data into two different Accumulo Tables. This is the <b>document table</b> (default name: triplestore_text) and the <b>terms * table</b> (default name: triplestore_terms). * <p> * The document table stores the document (i.e. a triple statement), document properties, and the terms within the document. This is the * main table used for processing a text search by using document partitioned indexing. See {@link IntersectingIterator}. * <p> * For each document, the document table will store the following information: * <P> * * <pre> * Row (partition) | Column Family | Column Qualifier | Value * ================+================+==================+========== * shardID | d\x00 | documentHash | Document * shardID | s\x00Subject | documentHash | (empty) * shardID | p\x00Predicate | documentHash | (empty) * shardID | o\x00Object | documentHash | (empty) * shardID | c\x00Context | documentHash | (empty) * shardID | t\x00token | documentHash | (empty) * </pre> * <p> * Note: documentHash is a sha256 Hash of the Document's Content * <p> * The terms table is used for expanding wildcard search terms. For each token in the document table, the table will store the following * information: * * <pre> * Row (partition) | CF/CQ/Value * ==================+============= * l\x00token | (empty) * r\x00Reversetoken | (empty) * </pre> * <p> * There are two prefixes in the table, "token list" (keys with an "l" prefix) and "reverse token list" (keys with a "r" prefix). This table * is uses the "token list" to expand foo* into terms like food, foot, and football. This table uses the "reverse token list" to expand *ar * into car, bar, and far. * <p> * Example: Given these three statements as inputs: * * <pre> * <uri:paul> rdfs:label "paul smith"@en <uri:graph1> * <uri:steve> rdfs:label "steven anthony miller"@en <uri:graph1> * <uri:steve> rdfs:label "steve miller"@en <uri:graph1> * </pre> * <p> * Here's what the tables would look like: (Note: the hashes aren't real, the rows are not sorted, and the partition ids will vary.) * <p> * Triplestore_text * * <pre> * Row (partition) | Column Family | Column Qualifier | Value * ================+=================================+==================+========== * 000000 | d\x00 | 08b3d233a | uri:graph1x00uri:paul\x00rdfs:label\x00"paul smith"@en * 000000 | s\x00uri:paul | 08b3d233a | (empty) * 000000 | p\x00rdfs:label | 08b3d233a | (empty) * 000000 | o\x00"paul smith"@en | 08b3d233a | (empty) * 000000 | c\x00uri:graph1 | 08b3d233a | (empty) * 000000 | t\x00paul | 08b3d233a | (empty) * 000000 | t\x00smith | 08b3d233a | (empty) * * 000000 | d\x00 | 3a575534b | uri:graph1x00uri:steve\x00rdfs:label\x00"steven anthony miller"@en * 000000 | s\x00uri:steve | 3a575534b | (empty) * 000000 | p\x00rdfs:label | 3a575534b | (empty) * 000000 | o\x00"steven anthony miller"@en | 3a575534b | (empty) * 000000 | c\x00uri:graph1 | 3a575534b | (empty) * 000000 | t\x00steven | 3a575534b | (empty) * 000000 | t\x00anthony | 3a575534b | (empty) * 000000 | t\x00miller | 3a575534b | (empty) * * 000001 | d\x00 | 7bf670d06 | uri:graph1x00uri:steve\x00rdfs:label\x00"steve miller"@en * 000001 | s\x00uri:steve | 7bf670d06 | (empty) * 000001 | p\x00rdfs:label | 7bf670d06 | (empty) * 000001 | o\x00"steve miller"@en | 7bf670d06 | (empty) * 000001 | c\x00uri:graph1 | 7bf670d06 | (empty) * 000001 | t\x00steve | 7bf670d06 | (empty) * 000001 | t\x00miller | 7bf670d06 | (empty) * </pre> * <p> * triplestore_terms * <p> * * <pre> * Row (partition) | CF/CQ/Value * ==================+============= * l\x00paul | (empty) * l\x00smith | (empty) * l\x00steven | (empty) * l\x00anthony | (empty) * l\x00miller | (empty) * l\x00steve | (empty) * r\x00luap | (empty) * r\x00htims | (empty) * r\x00nevets | (empty) * r\x00ynohtna | (empty) * r\x00rellim | (empty) * r\x00evets | (empty) * * <pre> */ public class AccumuloFreeTextIndexer extends AbstractAccumuloIndexer implements FreeTextIndexer { private static final String TABLE_SUFFIX_TERM = "freetext_term"; private static final String TABLE_SUFFFIX_DOC = "freetext"; private static final Logger logger = Logger.getLogger(AccumuloFreeTextIndexer.class); private static final boolean IS_TERM_TABLE_TOKEN_DELETION_ENABLED = true; private static final byte[] EMPTY_BYTES = new byte[] {}; private static final Text EMPTY_TEXT = new Text(EMPTY_BYTES); private static final Value EMPTY_VALUE = new Value(EMPTY_BYTES); private Tokenizer tokenizer; private BatchWriter docTableBw; private BatchWriter termTableBw; private MultiTableBatchWriter mtbw; private int queryTermLimit; private int docTableNumPartitions; private Set<IRI> validPredicates; private Configuration conf; private boolean isInit = false; /** * Called by setConf to initialize query only. * Use this alone if usage does not require writing. * For a writeable (store and delete) version of this, * call setconf() and then setMultiTableBatchWriter(), then call init() * that is what the DAO does. * @throws AccumuloException * @throws AccumuloSecurityException * @throws TableNotFoundException * @throws TableExistsException */ private void initInternal() throws AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { final String doctable = getFreeTextDocTablename(conf); final String termtable = getFreeTextTermTablename(conf); docTableNumPartitions = ConfigUtils.getFreeTextDocNumPartitions(conf); final int termTableNumPartitions = ConfigUtils.getFreeTextTermNumPartitions(conf); final TableOperations tableOps = ConfigUtils.getConnector(conf).tableOperations(); // Create term table partitions final boolean createdTermTable = ConfigUtils.createTableIfNotExists(conf, termtable); if (createdTermTable && !ConfigUtils.useMockInstance(conf) && termTableNumPartitions > 0) { final TreeSet<Text> splits = new TreeSet<Text>(); // split on the "Term List" and "Reverse Term list" boundary splits.add(new Text(ColumnPrefixes.getRevTermListColFam(""))); // Symmetrically split the "Term List" and "Reverse Term list" final int numSubpartitions = ((termTableNumPartitions - 1) / 2); if (numSubpartitions > 0) { final int step = (26 / numSubpartitions); for (int i = 0; i < numSubpartitions; i++) { final String nextChar = String.valueOf((char) ('a' + (step * i))); splits.add(new Text(ColumnPrefixes.getTermListColFam(nextChar))); splits.add(new Text(ColumnPrefixes.getRevTermListColFam(nextChar))); } } tableOps.addSplits(termtable, splits); } // Create document (text) table partitions final boolean createdDocTable = ConfigUtils.createTableIfNotExists(conf, doctable); if (createdDocTable && !ConfigUtils.useMockInstance(conf)) { final TreeSet<Text> splits = new TreeSet<Text>(); for (int i = 0; i < docTableNumPartitions; i++) { splits.add(genPartition(i, docTableNumPartitions)); } tableOps.addSplits(doctable, splits); // Add a tablet level Bloom filter for the Column Family. // This will allow us to quickly determine if a term is contained in a tablet. tableOps.setProperty(doctable, "table.bloom.key.functor", ColumnFamilyFunctor.class.getCanonicalName()); tableOps.setProperty(doctable, "table.bloom.enabled", Boolean.TRUE.toString()); } // Set mtbw by calling setMultiTableBatchWriter(). The DAO does this and manages flushing. // If you create it here, tests work, but a real Accumulo may lose writes due to unmanaged flushing. if (mtbw != null) { docTableBw = mtbw.getBatchWriter(doctable); termTableBw = mtbw.getBatchWriter(termtable); } tokenizer = ConfigUtils.getFreeTextTokenizer(conf); validPredicates = ConfigUtils.getFreeTextPredicates(conf); queryTermLimit = ConfigUtils.getFreeTextTermLimit(conf); } /** * setConf sets the configuration and then initializes for query only. * Use this alone if usage does not require writing. * For a writeable (store and delete) version of this, * call this and then setMultiTableBatchWriter(), then call init() * that is what the DAO does. */ @Override public void setConf(final Configuration conf) { this.conf = conf; if (!isInit) { try { initInternal(); isInit = true; } catch (AccumuloException | AccumuloSecurityException | TableNotFoundException | TableExistsException e) { logger.warn("Unable to initialize index. Throwing Runtime Exception. ", e); throw new RuntimeException(e); } } } @Override public Configuration getConf() { return conf; } private void storeStatement(final Statement statement) throws IOException { Objects.requireNonNull(mtbw, "Freetext indexer attempting to store, but setMultiTableBatchWriter() was not set."); // if the predicate list is empty, accept all predicates. // Otherwise, make sure the predicate is on the "valid" list final boolean isValidPredicate = validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate()); if (isValidPredicate && (statement.getObject() instanceof Literal)) { // Get the tokens final String text = statement.getObject().stringValue().toLowerCase(); final SortedSet<String> tokens = tokenizer.tokenize(text); if (!tokens.isEmpty()) { // Get Document Data final String docContent = StatementSerializer.writeStatement(statement); final String docId = Md5Hash.md5Base64(docContent); // Setup partition final Text partition = genPartition(docContent.hashCode(), docTableNumPartitions); final Mutation docTableMut = new Mutation(partition); final List<Mutation> termTableMutations = new ArrayList<Mutation>(); final Text docIdText = new Text(docId); // Store the Document Data docTableMut.put(ColumnPrefixes.DOCS_CF_PREFIX, docIdText, new Value(docContent.getBytes(Charsets.UTF_8))); // index the statement parts docTableMut.put(ColumnPrefixes.getSubjColFam(statement), docIdText, EMPTY_VALUE); docTableMut.put(ColumnPrefixes.getPredColFam(statement), docIdText, EMPTY_VALUE); docTableMut.put(ColumnPrefixes.getObjColFam(statement), docIdText, EMPTY_VALUE); docTableMut.put(ColumnPrefixes.getContextColFam(statement), docIdText, EMPTY_VALUE); // index the statement terms for (final String token : tokens) { // tie the token to the document docTableMut.put(ColumnPrefixes.getTermColFam(token), docIdText, EMPTY_VALUE); // store the term in the term table (useful for wildcard searches) termTableMutations.add(createEmptyPutMutation(ColumnPrefixes.getTermListColFam(token))); termTableMutations.add(createEmptyPutMutation(ColumnPrefixes.getRevTermListColFam(token))); } // write the mutations try { docTableBw.addMutation(docTableMut); termTableBw.addMutations(termTableMutations); } catch (final MutationsRejectedException e) { logger.error("error adding mutation", e); throw new IOException(e); } } } } @Override public void storeStatement(final RyaStatement statement) throws IOException { storeStatement(RyaToRdfConversions.convertStatement(statement)); } private static Mutation createEmptyPutMutation(final Text row) { final Mutation m = new Mutation(row); m.put(EMPTY_TEXT, EMPTY_TEXT, EMPTY_VALUE); return m; } private static Mutation createEmptyPutDeleteMutation(final Text row) { final Mutation m = new Mutation(row); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); return m; } private static Text genPartition(final int partition, final int numParitions) { final int length = Integer.toString(numParitions).length(); return new Text(String.format("%0" + length + "d", Math.abs(partition % numParitions))); } @Override public Set<IRI> getIndexablePredicates() { return validPredicates; } /** {@inheritDoc} */ @Override public void flush() throws IOException { try { mtbw.flush(); } catch (final MutationsRejectedException e) { logger.error("error flushing the batch writer", e); throw new IOException(e); } } /** {@inheritDoc} */ @Override public void close() throws IOException { try { if (mtbw!=null) mtbw.close(); } catch (final MutationsRejectedException e) { logger.error("error closing the batch writer", e); throw new IOException(e); } } private Set<String> unrollWildcard(final String string, final boolean reverse) throws IOException { final Scanner termTableScan = getScanner(getFreeTextTermTablename(conf)); final Set<String> unrolledTerms = new HashSet<String>(); Text queryTerm; if (reverse) { final String t = StringUtils.removeStart(string, "*").toLowerCase(); queryTerm = ColumnPrefixes.getRevTermListColFam(t); } else { final String t = StringUtils.removeEnd(string, "*").toLowerCase(); queryTerm = ColumnPrefixes.getTermListColFam(t); } // perform query and read results termTableScan.setRange(Range.prefix(queryTerm)); for (final Entry<Key, Value> e : termTableScan) { final String term = ColumnPrefixes.removePrefix(e.getKey().getRow()).toString(); if (reverse) { unrolledTerms.add(StringUtils.reverse(term)); } else { unrolledTerms.add(term); } } if (unrolledTerms.isEmpty()) { // put in a placeholder term that will never be in the index. unrolledTerms.add("\1\1\1"); } return unrolledTerms; } private void unrollWildcards(final SimpleNode node) throws IOException { if (node instanceof ASTExpression || node instanceof ASTSimpleNode) { for (final SimpleNode n : getNodeIterator(node)) { unrollWildcards(n); } } else if (node instanceof ASTTerm) { final ASTTerm term = (ASTTerm) node; final boolean isWildTerm = term.getType().equals(ASTTerm.WILDTERM); final boolean isPreWildTerm = term.getType().equals(ASTTerm.PREFIXTERM); if (isWildTerm || isPreWildTerm) { final Set<String> unrolledTerms = unrollWildcard(term.getTerm(), isPreWildTerm); // create a new expression final ASTExpression newExpression = new ASTExpression(QueryParserTreeConstants.JJTEXPRESSION); newExpression.setType(ASTExpression.OR); newExpression.setNotFlag(term.isNotFlag()); for (final String unrolledTerm : unrolledTerms) { final ASTTerm t = new ASTTerm(QueryParserTreeConstants.JJTTERM); t.setNotFlag(false); t.setTerm(unrolledTerm); t.setType(ASTTerm.TERM); ASTNodeUtils.pushChild(newExpression, t); } // replace "term" node with "expression" node in "term" node parent final SimpleNode parent = (SimpleNode) term.jjtGetParent(); final int index = ASTNodeUtils.getChildIndex(parent, term); Validate.isTrue(index >= 0, "child not found in parent"); parent.jjtAddChild(newExpression, index); } } else { throw new IllegalArgumentException("Node is of unknown type: " + node.getClass().getName()); } } private Scanner getScanner(final String tablename) throws IOException { try { return ConfigUtils.createScanner(tablename, conf); } catch (AccumuloException | AccumuloSecurityException | TableNotFoundException e) { logger.error("Error connecting to " + tablename); throw new IOException(e); } } /** {@inheritDoc} */ @Override public CloseableIteration<Statement, QueryEvaluationException> queryText(final String query, final StatementConstraints contraints) throws IOException { final Scanner docTableScan = getScanner(getFreeTextDocTablename(conf)); // test the query to see if it's parses correctly. SimpleNode root = parseQuery(query); // unroll any wildcard nodes before it goes to the server unrollWildcards(root); final String unrolledQuery = ASTNodeUtils.serializeExpression(root); // Add S P O C constraints to query final StringBuilder constrainedQuery = new StringBuilder("(" + unrolledQuery + ")"); if (contraints.hasSubject()) { constrainedQuery.append(" AND "); constrainedQuery.append(ColumnPrefixes.getSubjColFam(contraints.getSubject().toString()).toString()); } if (contraints.hasContext()) { constrainedQuery.append(" AND "); constrainedQuery.append(ColumnPrefixes.getContextColFam(contraints.getContext().toString()).toString()); } if (contraints.hasPredicates()) { constrainedQuery.append(" AND ("); final List<String> predicates = new ArrayList<String>(); for (final IRI u : contraints.getPredicates()) { predicates.add(ColumnPrefixes.getPredColFam(u.stringValue()).toString()); } constrainedQuery.append(StringUtils.join(predicates, " OR ")); constrainedQuery.append(")"); } // Verify that the query is a reasonable size root = parseQuery(constrainedQuery.toString()); final int termCount = ASTNodeUtils.termCount(root); if (termCount > queryTermLimit) { throw new IOException("Query contains too many terms. Term limit: " + queryTermLimit + ". Term Count: " + termCount); } // perform query docTableScan.clearScanIterators(); docTableScan.clearColumns(); final int iteratorPriority = 20; final String iteratorName = "booleanTree"; final IteratorSetting ii = new IteratorSetting(iteratorPriority, iteratorName, BooleanTreeIterator.class); BooleanTreeIterator.setQuery(ii, constrainedQuery.toString()); docTableScan.addScanIterator(ii); docTableScan.setRange(new Range()); return getIteratorWrapper(docTableScan); } private static CloseableIteration<Statement, QueryEvaluationException> getIteratorWrapper(final Scanner s) { final Iterator<Entry<Key, Value>> i = s.iterator(); return new CloseableIteration<Statement, QueryEvaluationException>() { @Override public boolean hasNext() { return i.hasNext(); } @Override public Statement next() throws QueryEvaluationException { final Entry<Key, Value> entry = i.next(); final Value v = entry.getValue(); try { final String dataString = Text.decode(v.get(), 0, v.getSize()); final Statement s = StatementSerializer.readStatement(dataString); return s; } catch (final CharacterCodingException e) { logger.error("Error decoding value", e); throw new QueryEvaluationException(e); } catch (final IOException e) { logger.error("Error deserializing statement", e); throw new QueryEvaluationException(e); } } @Override public void remove() { throw new UnsupportedOperationException("Remove not implemented"); } @Override public void close() throws QueryEvaluationException { if (s != null) { s.close(); } } }; } /** * Simple adapter that parses the query using {@link QueryParser}. Note: any checked exceptions thrown by {@link QueryParser} are * re-thrown as {@link IOException}s. * * @param query * @return * @throws IOException */ private static SimpleNode parseQuery(final String query) throws IOException { SimpleNode root = null; try { root = QueryParser.parse(query); } catch (final ParseException e) { logger.error("Parser Exception on Client Side. Query: " + query, e); throw new IOException(e); } catch (final TokenMgrError e) { logger.error("Token Manager Exception on Client Side. Query: " + query, e); throw new IOException(e); } return root; } /** * Get Free Text Document index table's name * Use the two table version of this below. This one is required by base class. */ @Override public String getTableName() { return getFreeTextDocTablename(conf); } /** * Make the Accumulo table names used by this indexer for a specific instance of Rya. * * @param conf - The Rya configuration that specifies which instance of Rya * the table names will be built for. (not null) * @return The Accumulo table names used by this indexer for a specific instance of Rya. */ public static List<String> getTableNames(final Configuration conf) { requireNonNull(conf); return Collections.unmodifiableList( makeTableNames(ConfigUtils.getTablePrefix(conf) ) ); } /** * Get the Document index's table name. * * @param conf - The Rya configuration that specifies which instance of Rya * the table names will be built for. (not null) * @return The Free Text Document index's Accumulo table name for the Rya instance. */ public static String getFreeTextDocTablename(final Configuration conf) { requireNonNull(conf); return makeFreeTextDocTablename( ConfigUtils.getTablePrefix(conf) ); } @Override public void setMultiTableBatchWriter(MultiTableBatchWriter writer) throws IOException { mtbw = writer; } /** * Get the Term index's table name. * * @param conf - The Rya configuration that specifies which instance of Rya * the table names will be built for. (not null) * @return The Free Text Term index's Accumulo table name for the Rya instance. */ public static String getFreeTextTermTablename(final Configuration conf) { requireNonNull(conf); return makeFreeTextTermTablename( ConfigUtils.getTablePrefix(conf) ); } /** * Make the Accumulo table names used by this indexer for a specific instance of Rya. * * @param ryaInstanceName - The name of the Rya instance the table names are for. (not null) * @return The Accumulo table names used by this indexer for a specific instance of Rya. */ public static List<String> makeTableNames(final String ryaInstanceName) { requireNonNull(ryaInstanceName); return Lists.newArrayList( makeFreeTextDocTablename(ryaInstanceName), makeFreeTextTermTablename(ryaInstanceName)); } /** * Make the Document index's table name. * * @param ryaInstanceName - The name of the Rya instance the table names are for. (not null) * @return The Free Text Document index's Accumulo table name for the Rya instance. */ public static String makeFreeTextDocTablename(final String ryaInstanceName) { requireNonNull(ryaInstanceName); return ryaInstanceName + TABLE_SUFFFIX_DOC; } /** * Make the Term index's table name. * * @param ryaInstanceName - The name of the Rya instance the table names are for. (not null) * @return The Free Text Term index's Accumulo table name for the Rya instance. */ public static String makeFreeTextTermTablename(final String ryaInstanceName) { requireNonNull(ryaInstanceName); return ryaInstanceName + TABLE_SUFFIX_TERM; } private void deleteStatement(final Statement statement) throws IOException { Objects.requireNonNull(mtbw, "Freetext indexer attempting to delete, but setMultiTableBatchWriter() was not set."); // if the predicate list is empty, accept all predicates. // Otherwise, make sure the predicate is on the "valid" list final boolean isValidPredicate = validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate()); if (isValidPredicate && (statement.getObject() instanceof Literal)) { // Get the tokens final String text = statement.getObject().stringValue().toLowerCase(); final SortedSet<String> tokens = tokenizer.tokenize(text); if (!tokens.isEmpty()) { // Get Document Data final String docContent = StatementSerializer.writeStatement(statement); final String docId = Md5Hash.md5Base64(docContent); // Setup partition final Text partition = genPartition(docContent.hashCode(), docTableNumPartitions); final Mutation docTableMut = new Mutation(partition); final List<Mutation> termTableMutations = new ArrayList<Mutation>(); final Text docIdText = new Text(docId); // Delete the Document Data docTableMut.putDelete(ColumnPrefixes.DOCS_CF_PREFIX, docIdText); // Delete the statement parts in index docTableMut.putDelete(ColumnPrefixes.getSubjColFam(statement), docIdText); docTableMut.putDelete(ColumnPrefixes.getPredColFam(statement), docIdText); docTableMut.putDelete(ColumnPrefixes.getObjColFam(statement), docIdText); docTableMut.putDelete(ColumnPrefixes.getContextColFam(statement), docIdText); // Delete the statement terms in index for (final String token : tokens) { if (IS_TERM_TABLE_TOKEN_DELETION_ENABLED) { final int rowId = Integer.parseInt(partition.toString()); final boolean doesTermExistInOtherDocs = doesTermExistInOtherDocs(token, rowId, docIdText); // Only delete the term from the term table if it doesn't appear in other docs if (!doesTermExistInOtherDocs) { // Delete the term in the term table termTableMutations.add(createEmptyPutDeleteMutation(ColumnPrefixes.getTermListColFam(token))); termTableMutations.add(createEmptyPutDeleteMutation(ColumnPrefixes.getRevTermListColFam(token))); } } // Un-tie the token to the document docTableMut.putDelete(ColumnPrefixes.getTermColFam(token), docIdText); } // write the mutations try { docTableBw.addMutation(docTableMut); termTableBw.addMutations(termTableMutations); } catch (final MutationsRejectedException e) { logger.error("error adding mutation", e); throw new IOException(e); } } } } @Override public void deleteStatement(final RyaStatement statement) throws IOException { deleteStatement(RyaToRdfConversions.convertStatement(statement)); } /** * Checks to see if the provided term appears in other documents. * @param term the term to search for. * @param currentDocId the current document ID that the search term exists in. * @return {@code true} if the term was found in other documents. {@code false} otherwise. */ private boolean doesTermExistInOtherDocs(final String term, final int currentDocId, final Text docIdText) { try { final String freeTextDocTableName = getFreeTextDocTablename(conf); final Scanner scanner = getScanner(freeTextDocTableName); final String t = StringUtils.removeEnd(term, "*").toLowerCase(); final Text queryTerm = ColumnPrefixes.getTermColFam(t); // perform query and read results scanner.fetchColumnFamily(queryTerm); for (final Entry<Key, Value> entry : scanner) { final Key key = entry.getKey(); final Text row = key.getRow(); final int rowId = Integer.parseInt(row.toString()); // We only want to check other documents from the one we're deleting if (rowId != currentDocId) { final Text columnFamily = key.getColumnFamily(); final String columnFamilyValue = columnFamily.toString(); // Check that the value has the term prefix if (columnFamilyValue.startsWith(ColumnPrefixes.TERM_CF_PREFIX.toString())) { final Text text = ColumnPrefixes.removePrefix(columnFamily); final String value = text.toString(); if (value.equals(term)) { return true; } } } } } catch (final IOException e) { logger.error("Error searching for the existance of the term in other documents", e); } return false; } /** * called by the DAO after setting the mtbw. * The rest of the initilization is done by setConf() */ @Override public void init() { Objects.requireNonNull(mtbw, "Freetext indexer failed to initialize temporal index, setMultiTableBatchWriter() was not set."); Objects.requireNonNull(conf, "Freetext indexer failed to initialize temporal index, setConf() was not set."); try { docTableBw = mtbw.getBatchWriter(getFreeTextDocTablename(conf)); termTableBw = mtbw.getBatchWriter(getFreeTextTermTablename(conf)); } catch (AccumuloException | AccumuloSecurityException | TableNotFoundException e) { logger.error("Unable to initialize index. Throwing Runtime Exception. ", e); throw new RuntimeException(e); } } @Override public void setConnector(final Connector connector) { // TODO Auto-generated method stub } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void purge(final RdfCloudTripleStoreConfiguration configuration) { // TODO Auto-generated method stub } @Override public void dropAndDestroy() { // TODO Auto-generated method stub } }
apache/hbase
37,001
hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/TPut.java
/** * Autogenerated by Thrift Compiler (0.14.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hbase.thrift2.generated; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) /** * Used to perform Put operations for a single row. * * Add column values to this object and they'll be added. * You can provide a default timestamp if the column values * don't have one. If you don't provide a default timestamp * the current time is inserted. * * You can specify how this Put should be written to the write-ahead Log (WAL) * by changing the durability. If you don't provide durability, it defaults to * column family's default setting for durability. */ @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.14.1)", date = "2025-08-16") public class TPut implements org.apache.thrift.TBase<TPut, TPut._Fields>, java.io.Serializable, Cloneable, Comparable<TPut> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TPut"); private static final org.apache.thrift.protocol.TField ROW_FIELD_DESC = new org.apache.thrift.protocol.TField("row", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField COLUMN_VALUES_FIELD_DESC = new org.apache.thrift.protocol.TField("columnValues", org.apache.thrift.protocol.TType.LIST, (short)2); private static final org.apache.thrift.protocol.TField TIMESTAMP_FIELD_DESC = new org.apache.thrift.protocol.TField("timestamp", org.apache.thrift.protocol.TType.I64, (short)3); private static final org.apache.thrift.protocol.TField ATTRIBUTES_FIELD_DESC = new org.apache.thrift.protocol.TField("attributes", org.apache.thrift.protocol.TType.MAP, (short)5); private static final org.apache.thrift.protocol.TField DURABILITY_FIELD_DESC = new org.apache.thrift.protocol.TField("durability", org.apache.thrift.protocol.TType.I32, (short)6); private static final org.apache.thrift.protocol.TField CELL_VISIBILITY_FIELD_DESC = new org.apache.thrift.protocol.TField("cellVisibility", org.apache.thrift.protocol.TType.STRUCT, (short)7); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new TPutStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new TPutTupleSchemeFactory(); public @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row; // required public @org.apache.thrift.annotation.Nullable java.util.List<TColumnValue> columnValues; // required public long timestamp; // optional public @org.apache.thrift.annotation.Nullable java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> attributes; // optional /** * * @see TDurability */ public @org.apache.thrift.annotation.Nullable TDurability durability; // optional public @org.apache.thrift.annotation.Nullable TCellVisibility cellVisibility; // 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 { ROW((short)1, "row"), COLUMN_VALUES((short)2, "columnValues"), TIMESTAMP((short)3, "timestamp"), ATTRIBUTES((short)5, "attributes"), /** * * @see TDurability */ DURABILITY((short)6, "durability"), CELL_VISIBILITY((short)7, "cellVisibility"); 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: // ROW return ROW; case 2: // COLUMN_VALUES return COLUMN_VALUES; case 3: // TIMESTAMP return TIMESTAMP; case 5: // ATTRIBUTES return ATTRIBUTES; case 6: // DURABILITY return DURABILITY; case 7: // CELL_VISIBILITY return CELL_VISIBILITY; 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 __TIMESTAMP_ISSET_ID = 0; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.TIMESTAMP,_Fields.ATTRIBUTES,_Fields.DURABILITY,_Fields.CELL_VISIBILITY}; 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.ROW, new org.apache.thrift.meta_data.FieldMetaData("row", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true))); tmpMap.put(_Fields.COLUMN_VALUES, new org.apache.thrift.meta_data.FieldMetaData("columnValues", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TColumnValue.class)))); tmpMap.put(_Fields.TIMESTAMP, new org.apache.thrift.meta_data.FieldMetaData("timestamp", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.ATTRIBUTES, new org.apache.thrift.meta_data.FieldMetaData("attributes", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true), new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)))); tmpMap.put(_Fields.DURABILITY, new org.apache.thrift.meta_data.FieldMetaData("durability", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, TDurability.class))); tmpMap.put(_Fields.CELL_VISIBILITY, new org.apache.thrift.meta_data.FieldMetaData("cellVisibility", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TCellVisibility.class))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TPut.class, metaDataMap); } public TPut() { } public TPut( java.nio.ByteBuffer row, java.util.List<TColumnValue> columnValues) { this(); this.row = org.apache.thrift.TBaseHelper.copyBinary(row); this.columnValues = columnValues; } /** * Performs a deep copy on <i>other</i>. */ public TPut(TPut other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetRow()) { this.row = org.apache.thrift.TBaseHelper.copyBinary(other.row); } if (other.isSetColumnValues()) { java.util.List<TColumnValue> __this__columnValues = new java.util.ArrayList<TColumnValue>(other.columnValues.size()); for (TColumnValue other_element : other.columnValues) { __this__columnValues.add(new TColumnValue(other_element)); } this.columnValues = __this__columnValues; } this.timestamp = other.timestamp; if (other.isSetAttributes()) { java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> __this__attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(other.attributes); this.attributes = __this__attributes; } if (other.isSetDurability()) { this.durability = other.durability; } if (other.isSetCellVisibility()) { this.cellVisibility = new TCellVisibility(other.cellVisibility); } } public TPut deepCopy() { return new TPut(this); } @Override public void clear() { this.row = null; this.columnValues = null; setTimestampIsSet(false); this.timestamp = 0; this.attributes = null; this.durability = null; this.cellVisibility = null; } public byte[] getRow() { setRow(org.apache.thrift.TBaseHelper.rightSize(row)); return row == null ? null : row.array(); } public java.nio.ByteBuffer bufferForRow() { return org.apache.thrift.TBaseHelper.copyBinary(row); } public TPut setRow(byte[] row) { this.row = row == null ? (java.nio.ByteBuffer)null : java.nio.ByteBuffer.wrap(row.clone()); return this; } public TPut setRow(@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row) { this.row = org.apache.thrift.TBaseHelper.copyBinary(row); return this; } public void unsetRow() { this.row = null; } /** Returns true if field row is set (has been assigned a value) and false otherwise */ public boolean isSetRow() { return this.row != null; } public void setRowIsSet(boolean value) { if (!value) { this.row = null; } } public int getColumnValuesSize() { return (this.columnValues == null) ? 0 : this.columnValues.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<TColumnValue> getColumnValuesIterator() { return (this.columnValues == null) ? null : this.columnValues.iterator(); } public void addToColumnValues(TColumnValue elem) { if (this.columnValues == null) { this.columnValues = new java.util.ArrayList<TColumnValue>(); } this.columnValues.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<TColumnValue> getColumnValues() { return this.columnValues; } public TPut setColumnValues(@org.apache.thrift.annotation.Nullable java.util.List<TColumnValue> columnValues) { this.columnValues = columnValues; return this; } public void unsetColumnValues() { this.columnValues = null; } /** Returns true if field columnValues is set (has been assigned a value) and false otherwise */ public boolean isSetColumnValues() { return this.columnValues != null; } public void setColumnValuesIsSet(boolean value) { if (!value) { this.columnValues = null; } } public long getTimestamp() { return this.timestamp; } public TPut setTimestamp(long timestamp) { this.timestamp = timestamp; setTimestampIsSet(true); return this; } public void unsetTimestamp() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __TIMESTAMP_ISSET_ID); } /** Returns true if field timestamp is set (has been assigned a value) and false otherwise */ public boolean isSetTimestamp() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __TIMESTAMP_ISSET_ID); } public void setTimestampIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __TIMESTAMP_ISSET_ID, value); } public int getAttributesSize() { return (this.attributes == null) ? 0 : this.attributes.size(); } public void putToAttributes(java.nio.ByteBuffer key, java.nio.ByteBuffer val) { if (this.attributes == null) { this.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(); } this.attributes.put(key, val); } @org.apache.thrift.annotation.Nullable public java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> getAttributes() { return this.attributes; } public TPut setAttributes(@org.apache.thrift.annotation.Nullable java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer> attributes) { this.attributes = attributes; return this; } public void unsetAttributes() { this.attributes = null; } /** Returns true if field attributes is set (has been assigned a value) and false otherwise */ public boolean isSetAttributes() { return this.attributes != null; } public void setAttributesIsSet(boolean value) { if (!value) { this.attributes = null; } } /** * * @see TDurability */ @org.apache.thrift.annotation.Nullable public TDurability getDurability() { return this.durability; } /** * * @see TDurability */ public TPut setDurability(@org.apache.thrift.annotation.Nullable TDurability durability) { this.durability = durability; return this; } public void unsetDurability() { this.durability = null; } /** Returns true if field durability is set (has been assigned a value) and false otherwise */ public boolean isSetDurability() { return this.durability != null; } public void setDurabilityIsSet(boolean value) { if (!value) { this.durability = null; } } @org.apache.thrift.annotation.Nullable public TCellVisibility getCellVisibility() { return this.cellVisibility; } public TPut setCellVisibility(@org.apache.thrift.annotation.Nullable TCellVisibility cellVisibility) { this.cellVisibility = cellVisibility; return this; } public void unsetCellVisibility() { this.cellVisibility = null; } /** Returns true if field cellVisibility is set (has been assigned a value) and false otherwise */ public boolean isSetCellVisibility() { return this.cellVisibility != null; } public void setCellVisibilityIsSet(boolean value) { if (!value) { this.cellVisibility = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case ROW: if (value == null) { unsetRow(); } else { if (value instanceof byte[]) { setRow((byte[])value); } else { setRow((java.nio.ByteBuffer)value); } } break; case COLUMN_VALUES: if (value == null) { unsetColumnValues(); } else { setColumnValues((java.util.List<TColumnValue>)value); } break; case TIMESTAMP: if (value == null) { unsetTimestamp(); } else { setTimestamp((java.lang.Long)value); } break; case ATTRIBUTES: if (value == null) { unsetAttributes(); } else { setAttributes((java.util.Map<java.nio.ByteBuffer,java.nio.ByteBuffer>)value); } break; case DURABILITY: if (value == null) { unsetDurability(); } else { setDurability((TDurability)value); } break; case CELL_VISIBILITY: if (value == null) { unsetCellVisibility(); } else { setCellVisibility((TCellVisibility)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case ROW: return getRow(); case COLUMN_VALUES: return getColumnValues(); case TIMESTAMP: return getTimestamp(); case ATTRIBUTES: return getAttributes(); case DURABILITY: return getDurability(); case CELL_VISIBILITY: return getCellVisibility(); } 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 ROW: return isSetRow(); case COLUMN_VALUES: return isSetColumnValues(); case TIMESTAMP: return isSetTimestamp(); case ATTRIBUTES: return isSetAttributes(); case DURABILITY: return isSetDurability(); case CELL_VISIBILITY: return isSetCellVisibility(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof TPut) return this.equals((TPut)that); return false; } public boolean equals(TPut that) { if (that == null) return false; if (this == that) return true; boolean this_present_row = true && this.isSetRow(); boolean that_present_row = true && that.isSetRow(); if (this_present_row || that_present_row) { if (!(this_present_row && that_present_row)) return false; if (!this.row.equals(that.row)) return false; } boolean this_present_columnValues = true && this.isSetColumnValues(); boolean that_present_columnValues = true && that.isSetColumnValues(); if (this_present_columnValues || that_present_columnValues) { if (!(this_present_columnValues && that_present_columnValues)) return false; if (!this.columnValues.equals(that.columnValues)) return false; } boolean this_present_timestamp = true && this.isSetTimestamp(); boolean that_present_timestamp = true && that.isSetTimestamp(); if (this_present_timestamp || that_present_timestamp) { if (!(this_present_timestamp && that_present_timestamp)) return false; if (this.timestamp != that.timestamp) return false; } boolean this_present_attributes = true && this.isSetAttributes(); boolean that_present_attributes = true && that.isSetAttributes(); if (this_present_attributes || that_present_attributes) { if (!(this_present_attributes && that_present_attributes)) return false; if (!this.attributes.equals(that.attributes)) return false; } boolean this_present_durability = true && this.isSetDurability(); boolean that_present_durability = true && that.isSetDurability(); if (this_present_durability || that_present_durability) { if (!(this_present_durability && that_present_durability)) return false; if (!this.durability.equals(that.durability)) return false; } boolean this_present_cellVisibility = true && this.isSetCellVisibility(); boolean that_present_cellVisibility = true && that.isSetCellVisibility(); if (this_present_cellVisibility || that_present_cellVisibility) { if (!(this_present_cellVisibility && that_present_cellVisibility)) return false; if (!this.cellVisibility.equals(that.cellVisibility)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetRow()) ? 131071 : 524287); if (isSetRow()) hashCode = hashCode * 8191 + row.hashCode(); hashCode = hashCode * 8191 + ((isSetColumnValues()) ? 131071 : 524287); if (isSetColumnValues()) hashCode = hashCode * 8191 + columnValues.hashCode(); hashCode = hashCode * 8191 + ((isSetTimestamp()) ? 131071 : 524287); if (isSetTimestamp()) hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(timestamp); hashCode = hashCode * 8191 + ((isSetAttributes()) ? 131071 : 524287); if (isSetAttributes()) hashCode = hashCode * 8191 + attributes.hashCode(); hashCode = hashCode * 8191 + ((isSetDurability()) ? 131071 : 524287); if (isSetDurability()) hashCode = hashCode * 8191 + durability.getValue(); hashCode = hashCode * 8191 + ((isSetCellVisibility()) ? 131071 : 524287); if (isSetCellVisibility()) hashCode = hashCode * 8191 + cellVisibility.hashCode(); return hashCode; } @Override public int compareTo(TPut other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetRow(), other.isSetRow()); if (lastComparison != 0) { return lastComparison; } if (isSetRow()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.row, other.row); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetColumnValues(), other.isSetColumnValues()); if (lastComparison != 0) { return lastComparison; } if (isSetColumnValues()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.columnValues, other.columnValues); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetTimestamp(), other.isSetTimestamp()); if (lastComparison != 0) { return lastComparison; } if (isSetTimestamp()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.timestamp, other.timestamp); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetAttributes(), other.isSetAttributes()); if (lastComparison != 0) { return lastComparison; } if (isSetAttributes()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.attributes, other.attributes); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetDurability(), other.isSetDurability()); if (lastComparison != 0) { return lastComparison; } if (isSetDurability()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.durability, other.durability); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetCellVisibility(), other.isSetCellVisibility()); if (lastComparison != 0) { return lastComparison; } if (isSetCellVisibility()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cellVisibility, other.cellVisibility); 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("TPut("); boolean first = true; sb.append("row:"); if (this.row == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.row, sb); } first = false; if (!first) sb.append(", "); sb.append("columnValues:"); if (this.columnValues == null) { sb.append("null"); } else { sb.append(this.columnValues); } first = false; if (isSetTimestamp()) { if (!first) sb.append(", "); sb.append("timestamp:"); sb.append(this.timestamp); first = false; } if (isSetAttributes()) { if (!first) sb.append(", "); sb.append("attributes:"); if (this.attributes == null) { sb.append("null"); } else { sb.append(this.attributes); } first = false; } if (isSetDurability()) { if (!first) sb.append(", "); sb.append("durability:"); if (this.durability == null) { sb.append("null"); } else { sb.append(this.durability); } first = false; } if (isSetCellVisibility()) { if (!first) sb.append(", "); sb.append("cellVisibility:"); if (this.cellVisibility == null) { sb.append("null"); } else { sb.append(this.cellVisibility); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (row == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'row' was not present! Struct: " + toString()); } if (columnValues == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'columnValues' was not present! Struct: " + toString()); } // check for sub-struct validity if (cellVisibility != null) { cellVisibility.validate(); } } 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 TPutStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TPutStandardScheme getScheme() { return new TPutStandardScheme(); } } private static class TPutStandardScheme extends org.apache.thrift.scheme.StandardScheme<TPut> { public void read(org.apache.thrift.protocol.TProtocol iprot, TPut 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: // ROW if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.row = iprot.readBinary(); struct.setRowIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // COLUMN_VALUES if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list34 = iprot.readListBegin(); struct.columnValues = new java.util.ArrayList<TColumnValue>(_list34.size); @org.apache.thrift.annotation.Nullable TColumnValue _elem35; for (int _i36 = 0; _i36 < _list34.size; ++_i36) { _elem35 = new TColumnValue(); _elem35.read(iprot); struct.columnValues.add(_elem35); } iprot.readListEnd(); } struct.setColumnValuesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TIMESTAMP if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.timestamp = iprot.readI64(); struct.setTimestampIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // ATTRIBUTES if (schemeField.type == org.apache.thrift.protocol.TType.MAP) { { org.apache.thrift.protocol.TMap _map37 = iprot.readMapBegin(); struct.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(2*_map37.size); @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _key38; @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _val39; for (int _i40 = 0; _i40 < _map37.size; ++_i40) { _key38 = iprot.readBinary(); _val39 = iprot.readBinary(); struct.attributes.put(_key38, _val39); } iprot.readMapEnd(); } struct.setAttributesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // DURABILITY if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.durability = org.apache.hadoop.hbase.thrift2.generated.TDurability.findByValue(iprot.readI32()); struct.setDurabilityIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // CELL_VISIBILITY if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.cellVisibility = new TCellVisibility(); struct.cellVisibility.read(iprot); struct.setCellVisibilityIsSet(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(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, TPut struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.row != null) { oprot.writeFieldBegin(ROW_FIELD_DESC); oprot.writeBinary(struct.row); oprot.writeFieldEnd(); } if (struct.columnValues != null) { oprot.writeFieldBegin(COLUMN_VALUES_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.columnValues.size())); for (TColumnValue _iter41 : struct.columnValues) { _iter41.write(oprot); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } if (struct.isSetTimestamp()) { oprot.writeFieldBegin(TIMESTAMP_FIELD_DESC); oprot.writeI64(struct.timestamp); oprot.writeFieldEnd(); } if (struct.attributes != null) { if (struct.isSetAttributes()) { oprot.writeFieldBegin(ATTRIBUTES_FIELD_DESC); { oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING, struct.attributes.size())); for (java.util.Map.Entry<java.nio.ByteBuffer, java.nio.ByteBuffer> _iter42 : struct.attributes.entrySet()) { oprot.writeBinary(_iter42.getKey()); oprot.writeBinary(_iter42.getValue()); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.durability != null) { if (struct.isSetDurability()) { oprot.writeFieldBegin(DURABILITY_FIELD_DESC); oprot.writeI32(struct.durability.getValue()); oprot.writeFieldEnd(); } } if (struct.cellVisibility != null) { if (struct.isSetCellVisibility()) { oprot.writeFieldBegin(CELL_VISIBILITY_FIELD_DESC); struct.cellVisibility.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class TPutTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public TPutTupleScheme getScheme() { return new TPutTupleScheme(); } } private static class TPutTupleScheme extends org.apache.thrift.scheme.TupleScheme<TPut> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, TPut struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; oprot.writeBinary(struct.row); { oprot.writeI32(struct.columnValues.size()); for (TColumnValue _iter43 : struct.columnValues) { _iter43.write(oprot); } } java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetTimestamp()) { optionals.set(0); } if (struct.isSetAttributes()) { optionals.set(1); } if (struct.isSetDurability()) { optionals.set(2); } if (struct.isSetCellVisibility()) { optionals.set(3); } oprot.writeBitSet(optionals, 4); if (struct.isSetTimestamp()) { oprot.writeI64(struct.timestamp); } if (struct.isSetAttributes()) { { oprot.writeI32(struct.attributes.size()); for (java.util.Map.Entry<java.nio.ByteBuffer, java.nio.ByteBuffer> _iter44 : struct.attributes.entrySet()) { oprot.writeBinary(_iter44.getKey()); oprot.writeBinary(_iter44.getValue()); } } } if (struct.isSetDurability()) { oprot.writeI32(struct.durability.getValue()); } if (struct.isSetCellVisibility()) { struct.cellVisibility.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, TPut struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; struct.row = iprot.readBinary(); struct.setRowIsSet(true); { org.apache.thrift.protocol.TList _list45 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRUCT); struct.columnValues = new java.util.ArrayList<TColumnValue>(_list45.size); @org.apache.thrift.annotation.Nullable TColumnValue _elem46; for (int _i47 = 0; _i47 < _list45.size; ++_i47) { _elem46 = new TColumnValue(); _elem46.read(iprot); struct.columnValues.add(_elem46); } } struct.setColumnValuesIsSet(true); java.util.BitSet incoming = iprot.readBitSet(4); if (incoming.get(0)) { struct.timestamp = iprot.readI64(); struct.setTimestampIsSet(true); } if (incoming.get(1)) { { org.apache.thrift.protocol.TMap _map48 = iprot.readMapBegin(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING); struct.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(2*_map48.size); @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _key49; @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _val50; for (int _i51 = 0; _i51 < _map48.size; ++_i51) { _key49 = iprot.readBinary(); _val50 = iprot.readBinary(); struct.attributes.put(_key49, _val50); } } struct.setAttributesIsSet(true); } if (incoming.get(2)) { struct.durability = org.apache.hadoop.hbase.thrift2.generated.TDurability.findByValue(iprot.readI32()); struct.setDurabilityIsSet(true); } if (incoming.get(3)) { struct.cellVisibility = new TCellVisibility(); struct.cellVisibility.read(iprot); struct.setCellVisibilityIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
apache/harmony
37,087
classlib/modules/swing/src/main/java/common/javax/swing/plaf/metal/MetalIconFactory.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 Sergey Burlak, Anton Avtamonov, Vadim Bogdanov */ package javax.swing.plaf.metal; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.io.Serializable; import javax.swing.AbstractButton; import javax.swing.Icon; import javax.swing.JSlider; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.plaf.UIResource; import org.apache.harmony.x.swing.Utilities; public class MetalIconFactory implements Serializable { public static class FileIcon16 implements Icon, Serializable { private static final Color FILE_COLOR = new Color(240, 240, 255); public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); int[] envelopeXs = new int[] { x + 2, x + 7, x + 14, x + 14, x + 2, x + 2 }; int[] envelopeYs = new int[] { y + 7, y + 2, y + 2, y + 16, y + 16, y + 7 }; g.setColor(FILE_COLOR); g.fillPolygon(envelopeXs, envelopeYs, 6); g.setColor(Color.GRAY); g.drawPolygon(envelopeXs, envelopeYs, 6); int[] cornerXs = new int[] { x + 2, x + 7, x + 7, x + 2 }; int[] cornerYs = new int[] { y + 7, y + 2, y + 7, y + 7 }; g.setColor(Color.LIGHT_GRAY); g.fillPolygon(cornerXs, cornerYs, 4); g.setColor(Color.GRAY); g.drawPolygon(cornerXs, cornerYs, 4); g.setColor(oldColor); } public int getShift() { return 0; } public int getIconWidth() { return 16; } public int getIconHeight() { return 16; } public int getAdditionalHeight() { return 0; } } public static class FolderIcon16 implements Icon, Serializable { public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); int[] folderXs = new int[] { x + 2, x + 7, x + 8, x + 14, x + 14, x + 2, x + 2 }; int[] folderYs = new int[] { y + 3, y + 3, y + 5, y + 5, y + 13, y + 13, y + 3 }; g.setColor(Color.YELLOW); g.fillPolygon(folderXs, folderYs, 7); g.setColor(Color.GRAY); g.drawPolygon(folderXs, folderYs, 7); int[] cornerXs = new int[] { x + 2, x + 7, x + 8, x + 2, x + 2 }; int[] cornerYs = new int[] { y + 3, y + 3, y + 5, y + 5, y + 3 }; g.setColor(Color.LIGHT_GRAY); g.fillPolygon(cornerXs, cornerYs, 5); g.setColor(Color.GRAY); g.drawPolygon(cornerXs, cornerYs, 5); g.setColor(oldColor); } public int getShift() { return 0; } public int getIconWidth() { return 16; } public int getIconHeight() { return 16; } public int getAdditionalHeight() { return 0; } } public static class PaletteCloseIcon implements Icon, UIResource, Serializable { private static final int size = 8; public int getIconWidth() { return size; } public int getIconHeight() { return size; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { AbstractButton b = (AbstractButton)c; Color saveColor = g.getColor(); Color shadow = MetalLookAndFeel.getControlDarkShadow(); Color highlight = MetalLookAndFeel.getControlHighlight(); Color foreground = b.getModel().isArmed() ? shadow : highlight; Color background = !b.getModel().isArmed() ? shadow : highlight; g.setColor(foreground); g.drawPolyline(new int[] {0, 1, size / 2 - 1, size / 2, size - 2, size - 1}, new int[] {0, 0, size / 2 - 2, size / 2 - 2, 0, 0}, 6); g.drawLine(0, size - 2, size / 2 - 2, size / 2); g.drawLine(size / 2 + 1, size / 2, size - 1, size - 2); g.setColor(background); g.drawPolyline(new int[] {0, 1, size / 2 - 1, size / 2, size - 2, size - 1}, new int[] {size - 1, size - 1, size / 2 + 1, size / 2 + 1, size - 1, size - 1}, 6); g.drawLine(0, 1, size / 2 - 2, size / 2 - 1); g.drawLine(size / 2 + 1, size / 2 - 1, size - 1, 1); g.setColor(saveColor); } } public static class TreeControlIcon implements Icon, Serializable { protected boolean isLight; public TreeControlIcon(final boolean isCollapsed) { this.isLight = isCollapsed; } public void paintMe(final Component c, final Graphics g, final int x, final int y) { JTree tree = (JTree)c; g.setColor(tree.getBackground()); g.fillRect(x + getIconWidth() / 4, y + getIconHeight() / 4 + 1, getIconWidth() / 2 - 1, getIconHeight() / 2 - 1); g.setColor(tree.getForeground()); g.drawRect(x + getIconWidth() / 4, y + getIconHeight() / 4 + 1, getIconWidth() / 2 - 1, getIconHeight() / 2 - 1); g.drawLine(x + getIconWidth() / 2 - 3, y + getIconWidth() / 2, x + getIconWidth() / 2 + 1, y + getIconWidth() / 2); if (isLight) { g.drawLine(x + getIconWidth() / 2 - 1, y + getIconWidth() / 2 - 2, x + getIconWidth() / 2 - 1, y + getIconWidth() / 2 + 2); } } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { paintMe(c, g, x, y); } public int getIconWidth() { return 18; } public int getIconHeight() { return 18; } } public static class TreeFolderIcon extends MetalIconFactory.FolderIcon16 { public int getShift() { return -1; } public int getAdditionalHeight() { return 2; } public int getIconHeight() { return 18; } } public static class TreeLeafIcon extends MetalIconFactory.FileIcon16 { public int getShift() { return 2; } public int getAdditionalHeight() { return 4; } public int getIconHeight() { return 20; } } private static class InternalFrameAltMaximizeIcon implements Icon, UIResource { private int size; public InternalFrameAltMaximizeIcon(final int size) { this.size = size; } public int getIconHeight() { return size; } public int getIconWidth() { return size; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { AbstractButton b = (AbstractButton)c; Color saveColor = g.getColor(); Color shadow = MetalLookAndFeel.getControlDarkShadow(); Color highlight = MetalLookAndFeel.getControlHighlight(); Utilities.draw3DRect(g, x, y + 5, size - 6, size - 6, shadow, highlight, !b.getModel().isArmed()); Utilities.draw3DRect(g, x + 1, y + 6, size - 8, size - 8, shadow, highlight, b.getModel().isArmed()); Utilities.draw3DRect(g, x + 5, y, size - 6, size - 6, shadow, highlight, !b.getModel().isArmed()); Utilities.draw3DRect(g, x + 6, y + 1, size - 8, size - 8, shadow, highlight, b.getModel().isArmed()); g.setColor(saveColor); } } private static class InternalFrameMinimizeIcon implements Icon, UIResource { private int size; public InternalFrameMinimizeIcon(final int size) { this.size = size; } public int getIconHeight() { return size; } public int getIconWidth() { return size; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { AbstractButton b = (AbstractButton)c; Color shadow = MetalLookAndFeel.getControlDarkShadow(); Color highlight = MetalLookAndFeel.getControlHighlight(); Utilities.draw3DRect(g, x, y + size - 6, size - 1, 5, shadow, highlight, !b.getModel().isArmed()); } } private static class InternalFrameCloseIcon implements Icon, UIResource { private final int size; public InternalFrameCloseIcon(final int size) { this.size = size & -2; } public int getIconHeight() { return size; } public int getIconWidth() { return size; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { AbstractButton b = (AbstractButton)c; Color saveColor = g.getColor(); Color shadow = MetalLookAndFeel.getControlDarkShadow(); Color highlight = MetalLookAndFeel.getControlHighlight(); Color foreground = b.getModel().isArmed() ? shadow : highlight; Color background = !b.getModel().isArmed() ? shadow : highlight; g.setColor(foreground); g.drawPolyline(new int[]{0, 2, size / 2 - 1, size / 2, size - 3, size - 2}, new int[] {2, 0, size / 2 - 3, size / 2 - 3, 0, 1}, 6); g.drawLine(0, size - 3, size / 2 - 3, size / 2); g.drawLine(size / 2 + 2, size / 2, size - 2, size - 4); g.setColor(background); g.drawPolyline(new int[]{1, 2, size / 2 - 1, size / 2, size - 3, size - 1}, new int[] {size - 2, size - 1, size / 2 + 2, size / 2 + 2, size - 1, size - 3}, 6); g.drawLine(1, 3, size / 2 - 3, size / 2 - 1); g.drawLine(size / 2 + 2, size / 2 - 1, size - 1, 2); g.setColor(saveColor); } } private static class InternalFrameMaximizeIcon implements Icon, UIResource { private int size; public InternalFrameMaximizeIcon(final int size) { this.size = size; } public int getIconHeight() { return size; } public int getIconWidth() { return size; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { AbstractButton b = (AbstractButton)c; Color shadow = MetalLookAndFeel.getControlDarkShadow(); Color highlight = MetalLookAndFeel.getControlHighlight(); Utilities.draw3DRect(g, x, y, size - 1, size - 1, shadow, highlight, !b.getModel().isArmed()); Utilities.draw3DRect(g, x + 1, y + 1, size - 3, size - 3, shadow, highlight, b.getModel().isArmed()); } } private static class TreeHardDriveIcon implements Icon, UIResource { public int getIconHeight() { return 16; } public int getIconWidth() { return 16; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); g.setColor(Color.LIGHT_GRAY); g.fillOval(x + 2, y + 8, 12, 6); g.setColor(Color.DARK_GRAY); g.drawOval(x + 2, y + 8, 12, 6); g.setColor(Color.LIGHT_GRAY); g.fillOval(x + 2, y + 5, 12, 6); g.setColor(Color.DARK_GRAY); g.drawOval(x + 2, y + 5, 12, 6); g.setColor(Color.LIGHT_GRAY); g.fillOval(x + 2, y + 2, 12, 6); g.setColor(Color.DARK_GRAY); g.drawOval(x + 2, y + 2, 12, 6); g.setColor(oldColor); } } private static class TreeFloppyDriveIcon implements Icon, UIResource { private static final Color FLOPPY_COLOR = new Color(200, 200, 255); public int getIconHeight() { return 16; } public int getIconWidth() { return 16; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); int[] floppyXs = new int[] { x + 2, x + 3, x + 13, x + 14, x + 14, x + 13, x + 3, x + 2, x + 2 }; int[] floppyYs = new int[] { y + 2, y + 1, y + 1, y + 2, y + 12, y + 13, y + 13, y + 13, y + 2 }; g.setColor(FLOPPY_COLOR); g.fillPolygon(floppyXs, floppyYs, 9); g.setColor(Color.GRAY); g.drawPolygon(floppyXs, floppyYs, 9); int[] labelXs = new int[] { x + 4, x + 12, x + 12, x + 4, x + 4 }; int[] labelYs = new int[] { y + 1, y + 1, y + 8, y + 8, y + 1 }; g.setColor(Color.WHITE); g.fillPolygon(labelXs, labelYs, 5); g.setColor(Color.GRAY); g.drawPolygon(labelXs, labelYs, 5); int[] bootXs = new int[] { x + 5, x + 12, x + 12, x + 5, x + 5 }; int[] bootYs = new int[] { y + 10, y + 10, y + 13, y + 13, y + 10 }; g.setColor(Color.BLUE); g.fillPolygon(bootXs, bootYs, 5); g.setColor(oldColor); } } private static class TreeComputerIcon implements Icon, UIResource { private static final Color SCREEN_COLOR = new Color(176, 221, 244); public int getIconHeight() { return 16; } public int getIconWidth() { return 16; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); g.setColor(SCREEN_COLOR); g.fillRect(x + 2, y + 2, 12, 8); g.setColor(Color.DARK_GRAY); g.drawRect(x + 2, y + 2, 11, 8); g.setColor(Color.CYAN); g.drawRect(x + 4, y + 5, 2, 1); g.setColor(Color.DARK_GRAY); g.fillRect(x + 7, y + 10, 2, 2); g.fillRect(x + 2, y + 12, 12, 2); g.setColor(oldColor); } } private static class InternalFrameDefaultMenuIcon implements Icon, UIResource { public int getIconHeight() { return 16; } public int getIconWidth() { return 16; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color highlight = MetalLookAndFeel.getControlHighlight(); Color shadow = MetalLookAndFeel.getControlDarkShadow(); Utilities.draw3DRect(g, x, y, 16, 16, shadow, highlight, true); Utilities.draw3DRect(g, x + 1, y + 1, 14, 14, shadow, highlight, false); Color oldColor = g.getColor(); g.setColor(MetalLookAndFeel.getControlHighlight()); g.fillRect(x + 2, y + 2, 12, 12); g.setColor(oldColor); } } private static class HorizontalSliderThumbIcon implements Icon, UIResource { public int getIconHeight() { return 16; } public int getIconWidth() { return 15; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { int bottom = y + getIconHeight() - 1; int right = x + getIconWidth() - 1; g.fillPolygon(new int[] { x, right, right, x + getIconWidth() / 2, x }, new int[] { y, y, bottom - getIconHeight() / 2, bottom, bottom - getIconHeight() / 2 }, 5); Color shadow = Color.gray; Color highlight = Color.white; g.setColor(highlight); g.drawLine(x, y, right, y); g.drawLine(right, y, right, bottom - getIconHeight() / 2 + 1); g.drawLine(right, bottom - getIconHeight() / 2 + 1, x + getIconWidth() / 2, bottom); g.setColor(shadow); g.drawLine(x, y, x, bottom - getIconHeight() / 2 + 1); g.drawLine(x, bottom - getIconHeight() / 2 + 1, x + getIconWidth() / 2, bottom); } } private static class VerticalSliderThumbIcon implements Icon, UIResource { public int getIconHeight() { return 15; } public int getIconWidth() { return 16; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { JSlider slider = (JSlider)c; int bottom = y + getIconHeight() - 1; int right = x + getIconWidth() - 1; if (slider.getComponentOrientation().isLeftToRight()) { g.fillPolygon(new int[] { x, x + getIconWidth() / 2, right, x + getIconWidth() / 2, x }, new int[] { y, y, bottom - getIconHeight() / 2, bottom, bottom }, 5); Color shadow = Color.gray; Color highlight = Color.white; g.setColor(highlight); g.drawLine(x, y, x + getIconWidth() / 2, y); g.drawLine(x + getIconWidth() / 2, y, right, bottom - getIconHeight() / 2); g.setColor(shadow); g.drawLine(x, y, x, bottom); g.drawLine(x, bottom, x + getIconWidth() / 2, bottom); g.drawLine(x + getIconWidth() / 2, bottom, right, bottom - getIconHeight() / 2); } else { g.fillPolygon(new int[] { x, x + getIconWidth() / 2, right, right, x + getIconWidth() / 2, x }, new int[] { bottom - getIconHeight() / 2, y, y, bottom, bottom, bottom - getIconHeight() / 2 }, 5); Color shadow = Color.gray; Color highlight = Color.white; g.setColor(highlight); g.drawLine(x + getIconWidth() / 2 - 1, bottom, right, bottom); g.drawLine(right, bottom, right, y); g.setColor(shadow); g.drawLine(right, y, x + getIconWidth() / 2 - 1, y); g.drawLine(x + getIconWidth() / 2 - 1, y, x, bottom - getIconHeight() / 2); g.drawLine(x, bottom - getIconHeight() / 2, x + getIconWidth() / 2 - 1, bottom); } } } private static class FileChooserUpFolderIcon implements Icon, UIResource { public int getIconHeight() { return 18; } public int getIconWidth() { return 18; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); int[] folderXs = new int[] { x + 2, x + 9, x + 10, x + 16, x + 16, x + 2, x + 2 }; int[] folderYs = new int[] { y + 3, y + 3, y + 5, y + 5, y + 13, y + 13, y + 3 }; g.setColor(Color.YELLOW); g.fillPolygon(folderXs, folderYs, 7); g.setColor(Color.GRAY); g.drawPolygon(folderXs, folderYs, 7); int[] cornerXs = new int[] { x + 2, x + 9, x + 10, x + 2, x + 2 }; int[] cornerYs = new int[] { y + 3, y + 3, y + 5, y + 5, y + 3 }; g.setColor(Color.LIGHT_GRAY); g.fillPolygon(cornerXs, cornerYs, 5); g.setColor(Color.GRAY); g.drawPolygon(cornerXs, cornerYs, 5); g.setColor(Color.GREEN.darker()); int[] arrowXs = new int[] { x + 9, x + 13, x + 17, x + 9 }; int[] arrowYs = new int[] { y + 6, y + 2, y + 6, y + 6 }; g.fillPolygon(arrowXs, arrowYs, 4); g.drawPolygon(arrowXs, arrowYs, 4); g.drawLine(x + 12, y + 6, x + 12, y + 11); g.drawLine(x + 13, y + 6, x + 13, y + 11); g.drawLine(x + 14, y + 6, x + 14, y + 11); g.setColor(oldColor); } } private static class FileChooserNewFolderIcon implements Icon, UIResource { private static final Color STAR_COLOR = new Color(191, 62, 6); public int getIconHeight() { return 18; } public int getIconWidth() { return 18; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); int[] folderXs = new int[] { x + 2, x + 9, x + 10, x + 16, x + 16, x + 2, x + 2 }; int[] folderYs = new int[] { y + 3, y + 3, y + 5, y + 5, y + 13, y + 13, y + 3 }; g.setColor(Color.YELLOW); g.fillPolygon(folderXs, folderYs, 7); g.setColor(Color.GRAY); g.drawPolygon(folderXs, folderYs, 7); int[] cornerXs = new int[] { x + 2, x + 9, x + 10, x + 2, x + 2 }; int[] cornerYs = new int[] { y + 3, y + 3, y + 5, y + 5, y + 3 }; g.setColor(Color.LIGHT_GRAY); g.fillPolygon(cornerXs, cornerYs, 5); g.setColor(Color.GRAY); g.drawPolygon(cornerXs, cornerYs, 5); g.setColor(STAR_COLOR); g.drawLine(x, y + 12, x + 6, y + 12); g.drawLine(x + 3, y + 9, x + 3, y + 15); g.drawLine(x + 1, y + 10, x + 5, y + 14); g.drawLine(x + 1, y + 14, x + 5, y + 10); g.setColor(oldColor); } } private static class FileChooserListViewIcon implements Icon, UIResource { private static final Color ICON_COLOR = new Color(50, 100, 250); public int getIconHeight() { return 18; } public int getIconWidth() { return 18; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); drawItem(g, x + 1, y + 4); drawItem(g, x + 10, y + 4); drawItem(g, x + 1, y + 10); drawItem(g, x + 10, y + 10); g.setColor(oldColor); } private void drawItem(final Graphics g, final int x, final int y) { g.setColor(Color.LIGHT_GRAY); g.fillRect(x, y, 3, 3); g.setColor(ICON_COLOR); g.drawRect(x, y, 3, 3); g.setColor(Color.BLACK); g.drawLine(x + 5, y + 1, x + 7, y + 1); g.setColor(Color.GRAY); g.drawLine(x + 6, y + 2, x + 8, y + 2); } } private static class FileChooserHomeFolderIcon implements Icon, UIResource { private static final Color ROOF_COLOR = new Color(191, 62, 6); public int getIconHeight() { return 18; } public int getIconWidth() { return 18; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); int[] roofXs = new int[] { x + 1, x + 9, x + 17, x + 2 }; int[] roofYs = new int[] { y + 9, y + 1, y + 9, y + 9 }; g.setColor(ROOF_COLOR); g.fillPolygon(roofXs, roofYs, 4); g.setColor(Color.DARK_GRAY); g.drawPolygon(roofXs, roofYs, 4); g.setColor(Color.YELLOW); g.fillRect(x + 3, y + 8, 12, 8); g.setColor(Color.DARK_GRAY); g.drawRect(x + 3, y + 8, 12, 8); g.setColor(Color.DARK_GRAY); g.fillRect(x + 5, y + 11, 3, 5); g.setColor(Color.DARK_GRAY); g.fillRect(x + 10, y + 11, 3, 3); g.setColor(oldColor); } } private static class FileChooserDetailViewIcon implements Icon, UIResource { private static final Color ICON_COLOR = new Color(50, 100, 250); public int getIconHeight() { return 18; } public int getIconWidth() { return 18; } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color oldColor = g.getColor(); drawItem(g, x + 1, y + 4); drawItem(g, x + 1, y + 10); g.setColor(oldColor); } private void drawItem(final Graphics g, final int x, final int y) { g.setColor(Color.LIGHT_GRAY); g.fillRect(x, y, 3, 3); g.setColor(ICON_COLOR); g.drawRect(x, y, 3, 3); g.setColor(Color.BLACK); g.drawLine(x + 5, y + 1, x + 7, y + 1); g.drawLine(x + 9, y + 1, x + 11, y + 1); g.drawLine(x + 13, y + 1, x + 15, y + 1); g.setColor(Color.GRAY); g.drawLine(x + 6, y + 2, x + 8, y + 2); g.drawLine(x + 10, y + 2, x + 12, y + 2); g.drawLine(x + 14, y + 2, x + 16, y + 2); } } private static class RadioButtonIcon implements Icon, UIResource { private static final int SIZE = 13; public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color selectionColor = c.isEnabled() ? c.getForeground() : MetalLookAndFeel.getControlDisabled(); drawRadioButtonIcon(g, (AbstractButton)c, selectionColor, MetalLookAndFeel.getControlDisabled(), c.getBackground(), x, y, SIZE, SIZE); } public int getIconWidth() { return SIZE; } public int getIconHeight() { return SIZE; } } private static class RadioButtonMenuItemIcon implements Icon, UIResource { private static final int SIZE = 10; public void paintIcon(final Component c, final Graphics g, final int x, final int y) { AbstractButton ab = (AbstractButton)c; Color selectionColor = c.isEnabled() ? ab.isSelected() ? MetalLookAndFeel.getMenuSelectedForeground() : c.getForeground() : MetalLookAndFeel.getMenuDisabledForeground(); Color backgroundColor = ab.getModel().isArmed() ? MetalLookAndFeel.getMenuSelectedBackground() : c.getBackground(); drawRadioButtonIcon(g, ab, selectionColor, MetalLookAndFeel.getMenuDisabledForeground(), backgroundColor, x, y, SIZE, SIZE); } public int getIconWidth() { return SIZE; } public int getIconHeight() { return SIZE; } } private static class CheckBoxIcon implements Icon, UIResource { private static final int SIZE = 13; public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color selectionColor = c.isEnabled() ? c.getForeground() : MetalLookAndFeel.getControlDisabled(); drawCheckBoxIcon(g, (AbstractButton)c, selectionColor, MetalLookAndFeel.getControlDisabled(), x, y, SIZE, SIZE); } public int getIconWidth() { return SIZE; } public int getIconHeight() { return SIZE; } } private static class CheckBoxMenuItemIcon implements Icon, UIResource { private static final int SIZE = 10; public void paintIcon(final Component c, final Graphics g, final int x, final int y) { Color selectionColor = c.isEnabled() ? ((AbstractButton)c).isSelected() ? MetalLookAndFeel.getMenuSelectedForeground() : c.getForeground() : MetalLookAndFeel.getMenuDisabledForeground(); drawCheckBoxIcon(g, (AbstractButton)c, selectionColor, MetalLookAndFeel.getMenuDisabledForeground(), x, y, SIZE, SIZE); } public int getIconWidth() { return SIZE; } public int getIconHeight() { return SIZE; } } private static class MenuArrowIcon implements Icon, UIResource { public void paintIcon(final Component c, final Graphics g, final int x, final int y) { final boolean leftToRight = c.getComponentOrientation().isLeftToRight(); final int direction = leftToRight ? SwingConstants.EAST : SwingConstants.WEST; final Color color = c.isEnabled() ? c.getForeground() : c.getBackground().darker(); Utilities.fillArrow(g, x, y + 1, direction, 8, true, color); } public int getIconWidth() { return 4; } public int getIconHeight() { return 8; } } private static class MenuItemArrowIcon implements Icon, UIResource { public void paintIcon(final Component c, final Graphics g, final int x, final int y) { } public int getIconWidth() { return 4; } public int getIconHeight() { return 8; } } public static final boolean DARK = false; public static final boolean LIGHT = true; private static Icon treeHardDriveIcon; private static Icon treeFloppyDriveIcon; private static Icon treeComputerIcon; private static Icon radioButtonMenuItemIcon; private static Icon radioButtonIcon; private static Icon menuItemArrowIcon; private static Icon menuArrowIcon; private static Icon internalFrameDefaultMenuIcon; private static Icon fileChooserUpFolderIcon; private static Icon fileChooserNewFolderIcon; private static Icon fileChooserListViewIcon; private static Icon fileChooserHomeFolderIcon; private static Icon fileChooserDetailViewIcon; private static Icon checkBoxMenuItemIcon; private static Icon checkBoxIcon; private static Icon verticalSliderThumbIcon; private static Icon horizontalSliderThumbIcon; public static Icon getTreeControlIcon(final boolean isLight) { return new TreeControlIcon(isLight); } public static Icon getInternalFrameMinimizeIcon(final int size) { return new InternalFrameMinimizeIcon(size); } public static Icon getInternalFrameMaximizeIcon(final int size) { return new InternalFrameMaximizeIcon(size); } public static Icon getInternalFrameCloseIcon(final int size) { return new InternalFrameCloseIcon(size); } public static Icon getInternalFrameAltMaximizeIcon(final int size) { return new InternalFrameAltMaximizeIcon(size); } public static Icon getVerticalSliderThumbIcon() { if (verticalSliderThumbIcon == null) { verticalSliderThumbIcon = new VerticalSliderThumbIcon(); } return verticalSliderThumbIcon; } public static Icon getTreeLeafIcon() { return new TreeLeafIcon(); } public static Icon getTreeHardDriveIcon() { if (treeHardDriveIcon == null) { treeHardDriveIcon = new TreeHardDriveIcon(); } return treeHardDriveIcon; } public static Icon getTreeFolderIcon() { return new TreeFolderIcon(); } public static Icon getTreeFloppyDriveIcon() { if (treeFloppyDriveIcon == null) { treeFloppyDriveIcon = new TreeFloppyDriveIcon(); } return treeFloppyDriveIcon; } public static Icon getTreeComputerIcon() { if (treeComputerIcon == null) { treeComputerIcon = new TreeComputerIcon(); } return treeComputerIcon; } public static Icon getRadioButtonMenuItemIcon() { if (radioButtonMenuItemIcon == null) { radioButtonMenuItemIcon = new RadioButtonMenuItemIcon(); } return radioButtonMenuItemIcon; } public static Icon getRadioButtonIcon() { if (radioButtonIcon == null) { radioButtonIcon = new RadioButtonIcon(); } return radioButtonIcon; } public static Icon getMenuItemCheckIcon() { return null; } public static Icon getMenuItemArrowIcon() { if (menuItemArrowIcon == null) { menuItemArrowIcon = new MenuItemArrowIcon(); } return menuItemArrowIcon; } public static Icon getMenuArrowIcon() { if (menuArrowIcon == null) { menuArrowIcon = new MenuArrowIcon(); } return menuArrowIcon; } public static Icon getInternalFrameDefaultMenuIcon() { if (internalFrameDefaultMenuIcon == null) { internalFrameDefaultMenuIcon = new InternalFrameDefaultMenuIcon(); } return internalFrameDefaultMenuIcon; } public static Icon getHorizontalSliderThumbIcon() { if (horizontalSliderThumbIcon == null) { horizontalSliderThumbIcon = new HorizontalSliderThumbIcon(); } return horizontalSliderThumbIcon; } public static Icon getFileChooserUpFolderIcon() { if (fileChooserUpFolderIcon == null) { fileChooserUpFolderIcon = new FileChooserUpFolderIcon(); } return fileChooserUpFolderIcon; } public static Icon getFileChooserNewFolderIcon() { if (fileChooserNewFolderIcon == null) { fileChooserNewFolderIcon = new FileChooserNewFolderIcon(); } return fileChooserNewFolderIcon; } public static Icon getFileChooserListViewIcon() { if (fileChooserListViewIcon == null) { fileChooserListViewIcon = new FileChooserListViewIcon(); } return fileChooserListViewIcon; } public static Icon getFileChooserHomeFolderIcon() { if (fileChooserHomeFolderIcon == null) { fileChooserHomeFolderIcon = new FileChooserHomeFolderIcon(); } return fileChooserHomeFolderIcon; } public static Icon getFileChooserDetailViewIcon() { if (fileChooserDetailViewIcon == null) { fileChooserDetailViewIcon = new FileChooserDetailViewIcon(); } return fileChooserDetailViewIcon; } public static Icon getCheckBoxMenuItemIcon() { if (checkBoxMenuItemIcon == null) { checkBoxMenuItemIcon = new CheckBoxMenuItemIcon(); } return checkBoxMenuItemIcon; } public static Icon getCheckBoxIcon() { if (checkBoxIcon == null) { checkBoxIcon = new CheckBoxIcon(); } return checkBoxIcon; } private static void drawRadioButtonIcon(final Graphics g, final AbstractButton rb, final Color selectionColor, final Color disableColor, final Color backgroundColor, final int x, final int y, final int w, final int h) { Color oldColor = g.getColor(); if (rb.isEnabled()) { if (rb.getModel().isArmed()) { g.setColor(MetalLookAndFeel.getControlShadow()); g.fillRoundRect(x, y + 1, w - 1, h - 1, w - 1, h - 1); } g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawRoundRect(x + 1, y + 2, w - 2, h - 2, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRoundRect(x, y + 1, w - 2, h - 2, w - 2, h - 2); } else { g.setColor(disableColor); g.drawRoundRect(x, y + 1, w - 2, h - 2, w - 2, h - 2); } if (rb.isSelected()) { g.setColor(rb.isEnabled() ? selectionColor : disableColor); g.fillRoundRect(x + w / 4, y + w / 4 + 1, w / 2, h / 2, w / 4, h / 4); } g.setColor(oldColor); } private static void drawCheckBoxIcon(final Graphics g, final AbstractButton cb, final Color selectionColor, final Color disableColor, final int x, final int y, final int w, final int h) { Color oldColor = g.getColor(); if (cb.isEnabled()) { g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawRect(x + 1, y + 2, w - 2, h - 2); } if (cb.getModel().isArmed()) { g.setColor(MetalLookAndFeel.getControlShadow()); g.fillRect(x, y + 1, w - 2, h - 2); } g.setColor(cb.isEnabled() ? MetalLookAndFeel.getControlDarkShadow() : disableColor); g.drawRect(x, y + 1, w - 2, h - 2); if (cb.isSelected()) { g.setColor(cb.isEnabled() ? selectionColor : disableColor); g.drawLine(x + 3, y + h / 2, x + 3, y + h - 2); g.drawLine(x + 4, y + h / 2, x + 4, y + h - 2); int lineLength = h - h / 2 - 2; g.drawLine(x + 4, y + h - 3, x + 4 + lineLength, y + h - 3 - lineLength); } g.setColor(oldColor); } }
apache/hertzbeat
37,161
hertzbeat-warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/history/tsdb/vm/VictoriaMetricsClusterDataStorage.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.hertzbeat.warehouse.store.history.tsdb.vm; import com.fasterxml.jackson.databind.JsonNode; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.time.ZonedDateTime; import java.time.temporal.TemporalAmount; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.common.collect.Maps; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.math.NumberUtils; import org.apache.hertzbeat.common.constants.CommonConstants; import org.apache.hertzbeat.common.constants.MetricDataConstants; import org.apache.hertzbeat.common.constants.NetworkConstants; import org.apache.hertzbeat.common.constants.SignConstants; import org.apache.hertzbeat.common.entity.arrow.RowWrapper; import org.apache.hertzbeat.common.entity.dto.Value; import org.apache.hertzbeat.common.entity.message.CollectRep; import org.apache.hertzbeat.common.timer.HashedWheelTimer; import org.apache.hertzbeat.common.timer.Timeout; import org.apache.hertzbeat.common.timer.TimerTask; import org.apache.hertzbeat.common.util.Base64Util; import org.apache.hertzbeat.common.util.CommonUtil; import org.apache.hertzbeat.common.util.JsonUtil; import org.apache.hertzbeat.common.util.TimePeriodUtil; import org.apache.hertzbeat.warehouse.store.history.tsdb.AbstractHistoryDataStorage; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Primary; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import static org.apache.hertzbeat.common.constants.ConfigConstants.FunctionModuleConstants.STATUS; /** * VictoriaMetrics data storage */ @Primary @Component @ConditionalOnProperty(prefix = "warehouse.store.victoria-metrics.cluster", name = "enabled", havingValue = "true") @Slf4j public class VictoriaMetricsClusterDataStorage extends AbstractHistoryDataStorage { private static final String VM_INSERT_BASE_PATH = "/insert/%s/%s"; private static final String VM_SELECT_BASE_PATH = "/select/%s/%s"; private static final String IMPORT_PATH = "prometheus/api/v1/import"; private static final String EXPORT_PATH = "prometheus/api/v1/export"; private static final String STATUS_PATH = "prometheus/api/v1/status/tsdb"; private static final String STATUS_SUCCESS = "success"; private static final String QUERY_RANGE_PATH = "prometheus/api/v1/query_range"; private static final String LABEL_KEY_NAME = "__name__"; private static final String LABEL_KEY_JOB = "job"; private static final String LABEL_KEY_INSTANCE = "instance"; private static final String LABEL_KEY_HOST = "host"; private static final String SPILT = "_"; private static final String MONITOR_METRICS_KEY = "__metrics__"; private static final String MONITOR_METRIC_KEY = "__metric__"; private static final long MAX_WAIT_MS = 500L; private static final int MAX_RETRIES = 3; private final VictoriaMetricsClusterProperties vmClusterProps; private final VictoriaMetricsInsertProperties vmInsertProps; private final VictoriaMetricsSelectProperties vmSelectProps; private final RestTemplate restTemplate; private final BlockingQueue<VictoriaMetricsDataStorage.VictoriaMetricsContent> metricsBufferQueue; private HashedWheelTimer metricsFlushTimer = null; private MetricsFlushTask metricsFlushtask = null; private boolean isBatchImportEnabled = false; public VictoriaMetricsClusterDataStorage(VictoriaMetricsClusterProperties vmClusterProps, RestTemplate restTemplate) { if (vmClusterProps == null) { log.error("init error, please config Warehouse victoriaMetrics cluster props in application.yml"); throw new IllegalArgumentException("please config Warehouse victoriaMetrics cluster props"); } this.restTemplate = restTemplate; this.vmClusterProps = vmClusterProps; this.vmInsertProps = vmClusterProps.insert(); this.vmSelectProps = vmClusterProps.select(); serverAvailable = checkVictoriaMetricsDatasourceAvailable(); metricsBufferQueue = new LinkedBlockingQueue<>(vmInsertProps.bufferSize()); isBatchImportEnabled = vmInsertProps.flushInterval() != 0 && vmInsertProps.bufferSize() != 0; if (isBatchImportEnabled){ initializeFlushTimer(); } } private void initializeFlushTimer() { this.metricsFlushTimer = new HashedWheelTimer(r -> { Thread thread = new Thread(r, "victoria-metrics-flush-timer"); thread.setDaemon(true); return thread; }, 1, TimeUnit.SECONDS, 512); metricsFlushtask = new MetricsFlushTask(); this.metricsFlushTimer.newTimeout(metricsFlushtask, 0, TimeUnit.SECONDS); } private boolean checkVictoriaMetricsDatasourceAvailable() { // check server status try { String selectNodeStatusUrl = vmClusterProps.select().url() + VM_SELECT_BASE_PATH.formatted(vmClusterProps.accountID(), STATUS_PATH); HttpHeaders headers = new HttpHeaders(); if (StringUtils.hasText(vmInsertProps.username()) && StringUtils.hasText(vmInsertProps.password())) { String authStr = vmInsertProps.username() + ":" + vmInsertProps.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } HttpEntity<Void> requestEntity = new HttpEntity<>(headers); ResponseEntity<String> responseEntity = restTemplate.exchange( selectNodeStatusUrl, HttpMethod.GET, requestEntity, String.class ); String result = responseEntity.getBody(); JsonNode jsonNode = JsonUtil.fromJson(result); if (jsonNode != null && STATUS_SUCCESS.equalsIgnoreCase(jsonNode.get(STATUS).asText())) { return true; } log.error("check victoria metrics cluster server status not success: {}.", result); } catch (Exception e) { log.error("check victoria metrics cluster server status error: {}.", e.getMessage()); } return false; } @Override public void saveData(CollectRep.MetricsData metricsData) { if (!isServerAvailable()) { serverAvailable = checkVictoriaMetricsDatasourceAvailable(); } if (!isServerAvailable() || metricsData.getCode() != CollectRep.Code.SUCCESS) { return; } if (metricsData.getValues().isEmpty()) { log.info("[warehouse victoria-metrics] flush metrics data {} {} {} is null, ignore.", metricsData.getId(), metricsData.getApp(), metricsData.getMetrics()); return; } Map<String, String> defaultLabels = Maps.newHashMapWithExpectedSize(8); defaultLabels.put(MONITOR_METRICS_KEY, metricsData.getMetrics()); boolean isPrometheusAuto; if (metricsData.getApp().startsWith(CommonConstants.PROMETHEUS_APP_PREFIX)) { isPrometheusAuto = true; defaultLabels.remove(MONITOR_METRICS_KEY); defaultLabels.put(LABEL_KEY_JOB, metricsData.getApp() .substring(CommonConstants.PROMETHEUS_APP_PREFIX.length())); } else { isPrometheusAuto = false; defaultLabels.put(LABEL_KEY_JOB, metricsData.getApp()); } defaultLabels.put(LABEL_KEY_INSTANCE, String.valueOf(metricsData.getId())); try { List<CollectRep.Field> fieldList = metricsData.getFields(); Long[] timestamp = new Long[]{metricsData.getTime()}; Map<String, Double> fieldsValue = Maps.newHashMapWithExpectedSize(fieldList.size()); Map<String, String> labels = Maps.newHashMapWithExpectedSize(fieldList.size()); List<VictoriaMetricsDataStorage.VictoriaMetricsContent> contentList = new LinkedList<>(); RowWrapper rowWrapper = metricsData.readRow(); while (rowWrapper.hasNextRow()) { rowWrapper = rowWrapper.nextRow(); fieldsValue.clear(); labels.clear(); rowWrapper.cellStream().forEach(cell -> { String value = cell.getValue(); Byte type = cell.getMetadataAsByte(MetricDataConstants.TYPE); Boolean label = cell.getMetadataAsBoolean(MetricDataConstants.LABEL); if (type == CommonConstants.TYPE_NUMBER && !label) { // number metrics data if (!CommonConstants.NULL_VALUE.equals(value)) { fieldsValue.put(cell.getField().getName(), CommonUtil.parseStrDouble(value)); } } // label if (label && !CommonConstants.NULL_VALUE.equals(value)) { labels.put(cell.getField().getName(), value); } for (Map.Entry<String, Double> entry : fieldsValue.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { try { labels.putAll(defaultLabels); String labelName = isPrometheusAuto ? metricsData.getMetrics() : metricsData.getMetrics() + SPILT + entry.getKey(); labels.put(LABEL_KEY_NAME, labelName); if (!isPrometheusAuto) { labels.put(MONITOR_METRIC_KEY, entry.getKey()); } labels.put(LABEL_KEY_HOST, metricsData.getInstanceHost()); // add customized labels as identifier var customizedLabels = metricsData.getLabels(); if (!ObjectUtils.isEmpty(customizedLabels)) { labels.putAll(customizedLabels); } VictoriaMetricsDataStorage.VictoriaMetricsContent content = VictoriaMetricsDataStorage.VictoriaMetricsContent.builder() .metric(new HashMap<>(labels)) .values(new Double[]{entry.getValue()}) .timestamps(timestamp) .build(); contentList.add(content); } catch (Exception e) { log.error("combine metrics data error: {}.", e.getMessage(), e); } } } }); } if (contentList.isEmpty()) { log.info("[warehouse victoria-metrics] flush metrics data {} is empty, ignore.", metricsData.getId()); return; } if (!isBatchImportEnabled){ doSaveData(contentList); return; } sendVictoriaMetrics(contentList); } catch (Exception e) { log.error("flush metrics data to victoria-metrics error: {}.", e.getMessage(), e); } } @Override public void destroy() { if (metricsFlushTimer != null && !metricsFlushTimer.isStop()) { metricsFlushTimer.stop(); } } @Override public Map<String, List<Value>> getHistoryMetricData(Long monitorId, String app, String metrics, String metric, String label, String history) { String labelName = metrics + SPILT + metric; if (CommonConstants.PROMETHEUS.equals(app)) { labelName = metrics; } String timeSeriesSelector = Stream.of( LABEL_KEY_NAME + "=\"" + labelName + "\"", LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"", CommonConstants.PROMETHEUS.equals(app) ? null : MONITOR_METRIC_KEY + "=\"" + metric + "\"" ).filter(Objects::nonNull).collect(Collectors.joining(",")); Map<String, List<Value>> instanceValuesMap = new HashMap<>(8); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(List.of(MediaType.APPLICATION_JSON)); if (StringUtils.hasText(vmSelectProps.username()) && StringUtils.hasText(vmSelectProps.password())) { String authStr = vmSelectProps.username() + ":" + vmSelectProps.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } HttpEntity<Void> httpEntity = new HttpEntity<>(headers); Instant end = Instant.now(); Duration duration = Duration.ofHours(Long.parseLong(history.replace("h", ""))); Instant start = end.minus(duration); String exportUrl = vmClusterProps.select().url() + VM_SELECT_BASE_PATH.formatted(vmClusterProps.accountID(), EXPORT_PATH); URI uri = UriComponentsBuilder.fromUriString(exportUrl) .queryParam("match", URLEncoder.encode("{" + timeSeriesSelector + "}", StandardCharsets.UTF_8)) .queryParam("start", String.valueOf(start.getEpochSecond())) .queryParam("end", String.valueOf(end.getEpochSecond())) .build(true).toUri(); ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.debug("query metrics data from victoria-metrics success. {}", uri); if (StringUtils.hasText(responseEntity.getBody())) { String[] contentJsonArr = responseEntity.getBody().split("\n"); List<VictoriaMetricsContent> contents = Arrays.stream(contentJsonArr) .map(item -> JsonUtil.fromJson(item, VictoriaMetricsContent.class)).toList(); for (VictoriaMetricsContent content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && content.getTimestamps() != null) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (content.getValues().length != content.getTimestamps().length) { log.error("content.getValues().length != content.getTimestamps().length"); continue; } Double[] values = content.getValues(); Long[] timestamps = content.getTimestamps(); for (int index = 0; index < content.getValues().length; index++) { String strValue = BigDecimal.valueOf(values[index]).setScale(4, RoundingMode.HALF_UP) .stripTrailingZeros().toPlainString(); // read timestamp here is ms unit valueList.add(new Value(strValue, timestamps[index])); } } } } } else { log.error("query metrics data from victoria-metrics failed. {}", responseEntity); } } catch (Exception e) { log.error("query metrics data from victoria-metrics error. {}.", e.getMessage(), e); } return instanceValuesMap; } @Override public Map<String, List<Value>> getHistoryIntervalMetricData(Long monitorId, String app, String metrics, String metric, String label, String history) { if (!serverAvailable) { log.error(""" \t---------------VictoriaMetrics Init Failed--------------- \t--------------Please Config VictoriaMetrics-------------- \t----------Can Not Use Metric History Now---------- """); return Collections.emptyMap(); } long endTime = ZonedDateTime.now().toEpochSecond(); long startTime; try { if (NumberUtils.isParsable(history)) { startTime = NumberUtils.toLong(history); startTime = (ZonedDateTime.now().toEpochSecond() - startTime); } else { TemporalAmount temporalAmount = TimePeriodUtil.parseTokenTime(history); ZonedDateTime dateTime = ZonedDateTime.now().minus(temporalAmount); startTime = dateTime.toEpochSecond(); } } catch (Exception e) { log.error("history time error: {}. use default: 6h", e.getMessage()); ZonedDateTime dateTime = ZonedDateTime.now().minus(Duration.ofHours(6)); startTime = dateTime.toEpochSecond(); } String labelName = metrics + SPILT + metric; if (CommonConstants.PROMETHEUS.equals(app)) { labelName = metrics; } String timeSeriesSelector = Stream.of( LABEL_KEY_NAME + "=\"" + labelName + "\"", LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"", CommonConstants.PROMETHEUS.equals(app) ? null : MONITOR_METRIC_KEY + "=\"" + metric + "\"" ).filter(Objects::nonNull).collect(Collectors.joining(",")); Map<String, List<Value>> instanceValuesMap = new HashMap<>(8); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(List.of(MediaType.APPLICATION_JSON)); if (StringUtils.hasText(vmSelectProps.username()) && StringUtils.hasText(vmSelectProps.password())) { String authStr = vmSelectProps.username() + ":" + vmSelectProps.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } HttpEntity<Void> httpEntity = new HttpEntity<>(headers); String rangeUrl = VM_SELECT_BASE_PATH.formatted(vmClusterProps.accountID(), QUERY_RANGE_PATH); URI uri = UriComponentsBuilder.fromUriString(rangeUrl) .queryParam("query", URLEncoder.encode("{" + timeSeriesSelector + "}", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true) .toUri(); ResponseEntity<PromQlQueryContent> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.debug("query metrics data from victoria-metrics success. {}", uri); if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData() .getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); for (Object[] valueArr : content.getValues()) { long timestamp = Long.parseLong(String.valueOf(valueArr[0])); String value = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); // read timestamp here is s unit valueList.add(new Value(value, timestamp * 1000)); } } } } } else { log.error("query metrics data from victoria-metrics failed. {}", responseEntity); } // max uri = UriComponentsBuilder.fromUriString(rangeUrl) .queryParam("query", URLEncoder.encode("max_over_time({" + timeSeriesSelector + "})", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true) .toUri(); responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData() .getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (valueList.size() == content.getValues().size()) { for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) { Value value = valueList.get(timestampIndex); Object[] valueArr = content.getValues().get(timestampIndex); String maxValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); value.setMax(maxValue); } } } } } } // min uri = UriComponentsBuilder.fromUriString(rangeUrl) .queryParam("query", URLEncoder.encode("min_over_time({" + timeSeriesSelector + "})", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true) .toUri(); responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData() .getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (valueList.size() == content.getValues().size()) { for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) { Value value = valueList.get(timestampIndex); Object[] valueArr = content.getValues().get(timestampIndex); String minValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); value.setMin(minValue); } } } } } } // avg uri = UriComponentsBuilder.fromUriString(rangeUrl) .queryParam("query", URLEncoder.encode("avg_over_time({" + timeSeriesSelector + "})", StandardCharsets.UTF_8)) .queryParam("step", "4h") .queryParam("start", startTime) .queryParam("end", endTime) .build(true) .toUri(); responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, PromQlQueryContent.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null && responseEntity.getBody().getData().getResult() != null) { List<PromQlQueryContent.ContentData.Content> contents = responseEntity.getBody().getData() .getResult(); for (PromQlQueryContent.ContentData.Content content : contents) { Map<String, String> labels = content.getMetric(); labels.remove(LABEL_KEY_NAME); labels.remove(LABEL_KEY_JOB); labels.remove(LABEL_KEY_INSTANCE); labels.remove(MONITOR_METRICS_KEY); labels.remove(MONITOR_METRIC_KEY); String labelStr = JsonUtil.toJson(labels); if (content.getValues() != null && !content.getValues().isEmpty()) { List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>()); if (valueList.size() == content.getValues().size()) { for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) { Value value = valueList.get(timestampIndex); Object[] valueArr = content.getValues().get(timestampIndex); String avgValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); value.setMean(avgValue); } } } } } } } catch (Exception e) { log.error("query metrics data from victoria-metrics error. {}.", e.getMessage(), e); } return instanceValuesMap; } /** * Save metric data to victoria-metric via HTTP call */ public void doSaveData(List<VictoriaMetricsDataStorage.VictoriaMetricsContent> contentList){ try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); if (StringUtils.hasText(vmInsertProps.username()) && StringUtils.hasText(vmInsertProps.password())) { String authStr = vmInsertProps.username() + ":" + vmInsertProps.password(); String encodedAuth = Base64Util.encode(authStr); headers.add(HttpHeaders.AUTHORIZATION, NetworkConstants.BASIC + SignConstants.BLANK + encodedAuth); } StringBuilder stringBuilder = new StringBuilder(); for (VictoriaMetricsDataStorage.VictoriaMetricsContent content : contentList) { stringBuilder.append(JsonUtil.toJson(content)).append("\n"); } HttpEntity<String> httpEntity = new HttpEntity<>(stringBuilder.toString(), headers); String importUrl = vmClusterProps.insert().url() + VM_INSERT_BASE_PATH.formatted(vmClusterProps.accountID(), IMPORT_PATH); ResponseEntity<String> responseEntity = restTemplate.postForEntity(importUrl, httpEntity, String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.debug("insert metrics data to victoria-metrics success."); } else { log.error("insert metrics data to victoria-metrics failed. {}", responseEntity.getBody()); } } catch (Exception e){ log.error("flush metrics data to victoria-metrics error: {}.", e.getMessage(), e); } } /** * add victoriaMetricsContent to buffer * @param contentList victoriaMetricsContent List */ private void sendVictoriaMetrics(List<VictoriaMetricsDataStorage.VictoriaMetricsContent> contentList) { for (VictoriaMetricsDataStorage.VictoriaMetricsContent content : contentList) { boolean offered = false; int retryCount = 0; while (!offered && retryCount < MAX_RETRIES) { try { // Attempt to add to the queue for a limited time offered = metricsBufferQueue.offer(content, MAX_WAIT_MS, TimeUnit.MILLISECONDS); if (!offered) { // If the queue is still full, trigger an immediate refresh to free up space if (retryCount == 0) { log.debug("victoria metrics buffer queue is full, triggering immediate flush"); triggerImmediateFlush(); } retryCount++; // The short sleep allows the queue to clear out if (retryCount < MAX_RETRIES) { Thread.sleep(100L * retryCount); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("[Victoria Metrics] Interrupted while offering metrics to buffer queue", e); break; } } // When the maximum number of retries is reached, if it still cannot be added to the queue, the data is saved directly if (!offered) { log.warn("[Victoria Metrics] Failed to add metrics to buffer after {} retries, saving directly", MAX_RETRIES); try { doSaveData(contentList); } catch (Exception e) { log.error("[Victoria Metrics] Failed to save metrics directly: {}", e.getMessage(), e); } } // Refresh in advance to avoid waiting if (metricsBufferQueue.size() >= vmInsertProps.bufferSize() * 0.8) { triggerImmediateFlush(); } } } private void triggerImmediateFlush() { metricsFlushTimer.newTimeout(metricsFlushtask, 0, TimeUnit.MILLISECONDS); } /** * Regularly refresh the buffer queue to the vm */ private class MetricsFlushTask implements TimerTask { @Override public void run(Timeout timeout) { try { List<VictoriaMetricsDataStorage.VictoriaMetricsContent> batch = new ArrayList<>(vmInsertProps.bufferSize()); metricsBufferQueue.drainTo(batch, vmInsertProps.bufferSize()); if (!batch.isEmpty()) { doSaveData(batch); log.debug("[Victoria Metrics] Flushed {} metrics items", batch.size()); } if (metricsFlushTimer != null && !metricsFlushTimer.isStop()) { metricsFlushTimer.newTimeout(this, vmInsertProps.flushInterval(), TimeUnit.SECONDS); } } catch (Exception e) { log.error("[VictoriaMetrics] flush task error: {}", e.getMessage(), e); } } } /** * victoria metrics content */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public static final class VictoriaMetricsContent { /** * metric contains metric name plus labels for a particular time series */ private Map<String, String> metric; /** * values contains raw sample values for the given time series */ private Double[] values; /** * timestamps contains raw sample UNIX timestamps in milliseconds for the given time series * every timestamp is associated with the value at the corresponding position */ private Long[] timestamps; } }
apache/lucene
36,726
lucene/core/src/test/org/apache/lucene/index/TestDirectoryReaderReopen.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.lucene.index; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.apache.lucene.document.Document; import org.apache.lucene.document.DocumentStoredFieldVisitor; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.ByteBuffersDirectory; import org.apache.lucene.store.Directory; import org.apache.lucene.tests.analysis.MockAnalyzer; import org.apache.lucene.tests.store.MockDirectoryWrapper; import org.apache.lucene.tests.store.MockDirectoryWrapper.FakeIOException; import org.apache.lucene.tests.util.LuceneTestCase; import org.apache.lucene.tests.util.TestUtil; import org.apache.lucene.util.IOUtils; public class TestDirectoryReaderReopen extends LuceneTestCase { public void testReopen() throws Exception { final Directory dir1 = newDirectory(); createIndex(random(), dir1, false); performDefaultTests( new TestReopen() { @Override protected void modifyIndex(int i) throws IOException { TestDirectoryReaderReopen.modifyIndex(i, dir1); } @Override protected DirectoryReader openReader() throws IOException { return DirectoryReader.open(dir1); } }); dir1.close(); final Directory dir2 = newDirectory(); createIndex(random(), dir2, true); performDefaultTests( new TestReopen() { @Override protected void modifyIndex(int i) throws IOException { TestDirectoryReaderReopen.modifyIndex(i, dir2); } @Override protected DirectoryReader openReader() throws IOException { return DirectoryReader.open(dir2); } }); dir2.close(); } // LUCENE-1228: IndexWriter.commit() does not update the index version // populate an index in iterations. // at the end of every iteration, commit the index and reopen/recreate the reader. // in each iteration verify the work of previous iteration. // try this once with reopen once recreate, on both RAMDir and FSDir. public void testCommitReopen() throws IOException { Directory dir = newDirectory(); doTestReopenWithCommit(random(), dir, true); dir.close(); } public void testCommitRecreate() throws IOException { Directory dir = newDirectory(); doTestReopenWithCommit(random(), dir, false); dir.close(); } private void doTestReopenWithCommit(Random random, Directory dir, boolean withReopen) throws IOException { IndexWriter iwriter = new IndexWriter( dir, newIndexWriterConfig(new MockAnalyzer(random)) .setOpenMode(OpenMode.CREATE) .setMergeScheduler(new SerialMergeScheduler()) .setMergePolicy(newLogMergePolicy())); iwriter.commit(); DirectoryReader reader = DirectoryReader.open(dir); try { int M = 3; FieldType customType = new FieldType(TextField.TYPE_STORED); customType.setTokenized(false); FieldType customType2 = new FieldType(TextField.TYPE_STORED); customType2.setTokenized(false); customType2.setOmitNorms(true); FieldType customType3 = new FieldType(); customType3.setStored(true); for (int i = 0; i < 4; i++) { for (int j = 0; j < M; j++) { Document doc = new Document(); doc.add(newField("id", i + "_" + j, customType)); doc.add(newField("id2", i + "_" + j, customType2)); doc.add(newField("id3", i + "_" + j, customType3)); iwriter.addDocument(doc); if (i > 0) { int k = i - 1; int n = j + k * M; final DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor(); reader.storedFields().document(n, visitor); Document prevItereationDoc = visitor.getDocument(); assertNotNull(prevItereationDoc); String id = prevItereationDoc.get("id"); assertEquals(k + "_" + j, id); } } iwriter.commit(); if (withReopen) { // reopen DirectoryReader r2 = DirectoryReader.openIfChanged(reader); if (r2 != null) { reader.close(); reader = r2; } } else { // recreate reader.close(); reader = DirectoryReader.open(dir); } } } finally { iwriter.close(); reader.close(); } } private void performDefaultTests(TestReopen test) throws Exception { DirectoryReader index1 = test.openReader(); DirectoryReader index2 = test.openReader(); TestDirectoryReader.assertIndexEquals(index1, index2); // verify that reopen() does not return a new reader instance // in case the index has no changes ReaderCouple couple = refreshReader(index2, false); assertTrue(couple.refreshedReader == index2); couple = refreshReader(index2, test, 0, true); index1.close(); index1 = couple.newReader; DirectoryReader index2_refreshed = couple.refreshedReader; index2.close(); // test if refreshed reader and newly opened reader return equal results TestDirectoryReader.assertIndexEquals(index1, index2_refreshed); index2_refreshed.close(); assertReaderClosed(index2, true); assertReaderClosed(index2_refreshed, true); index2 = test.openReader(); for (int i = 1; i < 4; i++) { index1.close(); couple = refreshReader(index2, test, i, true); // refresh DirectoryReader index2.close(); index2 = couple.refreshedReader; index1 = couple.newReader; TestDirectoryReader.assertIndexEquals(index1, index2); } index1.close(); index2.close(); assertReaderClosed(index1, true); assertReaderClosed(index2, true); } public void testThreadSafety() throws Exception { final Directory dir = newDirectory(); // NOTE: this also controls the number of threads! final int n = TestUtil.nextInt(random(), 20, 40); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random()))); for (int i = 0; i < n; i++) { writer.addDocument(createDocument(i, 3)); } writer.forceMerge(1); writer.close(); final TestReopen test = new TestReopen() { @Override protected void modifyIndex(int i) throws IOException { IndexWriter modifier = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))); modifier.addDocument(createDocument(n + i, 6)); modifier.close(); } @Override protected DirectoryReader openReader() throws IOException { return DirectoryReader.open(dir); } }; final List<ReaderCouple> readers = Collections.synchronizedList(new ArrayList<ReaderCouple>()); DirectoryReader firstReader = DirectoryReader.open(dir); DirectoryReader reader = firstReader; ReaderThread[] threads = new ReaderThread[n]; final Set<DirectoryReader> readersToClose = Collections.synchronizedSet(new HashSet<DirectoryReader>()); for (int i = 0; i < n; i++) { if (i % 2 == 0) { DirectoryReader refreshed = DirectoryReader.openIfChanged(reader); if (refreshed != null) { readersToClose.add(reader); reader = refreshed; } } final DirectoryReader r = reader; final int index = i; ReaderThreadTask task; if (i < 4 || (i >= 10 && i < 14) || i > 18) { task = new ReaderThreadTask() { @Override public void run() throws Exception { Random rnd = LuceneTestCase.random(); while (!stopped) { if (index % 2 == 0) { // refresh reader synchronized ReaderCouple c = (refreshReader(r, test, index, true)); readersToClose.add(c.newReader); readersToClose.add(c.refreshedReader); readers.add(c); // prevent too many readers break; } else { // not synchronized DirectoryReader refreshed = DirectoryReader.openIfChanged(r); if (refreshed == null) { refreshed = r; } IndexSearcher searcher = newSearcher(refreshed); ScoreDoc[] hits = searcher.search( new TermQuery( new Term("field1", "a" + rnd.nextInt(refreshed.maxDoc()))), 1000) .scoreDocs; if (hits.length > 0) { searcher.storedFields().document(hits[0].doc); } if (refreshed != r) { refreshed.close(); } } synchronized (this) { wait(TestUtil.nextInt(random(), 1, 100)); } } } }; } else { task = new ReaderThreadTask() { @Override public void run() throws Exception { Random rnd = LuceneTestCase.random(); while (!stopped) { int numReaders = readers.size(); if (numReaders > 0) { ReaderCouple c = readers.get(rnd.nextInt(numReaders)); TestDirectoryReader.assertIndexEquals(c.newReader, c.refreshedReader); } synchronized (this) { wait(TestUtil.nextInt(random(), 1, 100)); } } } }; } threads[i] = new ReaderThread(task); threads[i].start(); } synchronized (this) { wait(1000); } for (int i = 0; i < n; i++) { if (threads[i] != null) { threads[i].stopThread(); } } for (int i = 0; i < n; i++) { if (threads[i] != null) { threads[i].join(); if (threads[i].error != null) { String msg = "Error occurred in thread " + threads[i].getName() + ":\n" + threads[i].error.getMessage(); fail(msg); } } } for (final DirectoryReader readerToClose : readersToClose) { readerToClose.close(); } firstReader.close(); reader.close(); for (final DirectoryReader readerToClose : readersToClose) { assertReaderClosed(readerToClose, true); } assertReaderClosed(reader, true); assertReaderClosed(firstReader, true); dir.close(); } private static class ReaderCouple { ReaderCouple(DirectoryReader r1, DirectoryReader r2) { newReader = r1; refreshedReader = r2; } DirectoryReader newReader; DirectoryReader refreshedReader; } abstract static class ReaderThreadTask { protected volatile boolean stopped; public void stop() { this.stopped = true; } public abstract void run() throws Exception; } private static class ReaderThread extends Thread { ReaderThreadTask task; Throwable error; ReaderThread(ReaderThreadTask task) { this.task = task; } public void stopThread() { this.task.stop(); } @Override public void run() { try { this.task.run(); } catch (Throwable r) { r.printStackTrace(System.out); this.error = r; } } } private Object createReaderMutex = new Object(); private ReaderCouple refreshReader(DirectoryReader reader, boolean hasChanges) throws IOException { return refreshReader(reader, null, -1, hasChanges); } ReaderCouple refreshReader( DirectoryReader reader, TestReopen test, int modify, boolean hasChanges) throws IOException { synchronized (createReaderMutex) { DirectoryReader r = null; if (test != null) { test.modifyIndex(modify); r = test.openReader(); } DirectoryReader refreshed = null; try { refreshed = DirectoryReader.openIfChanged(reader); if (refreshed == null) { refreshed = reader; } } finally { if (refreshed == null && r != null) { // Hit exception -- close opened reader r.close(); } } if (hasChanges) { if (refreshed == reader) { fail("No new DirectoryReader instance created during refresh."); } } else { if (refreshed != reader) { fail( "New DirectoryReader instance created during refresh even though index had no changes."); } } return new ReaderCouple(r, refreshed); } } public static void createIndex(Random random, Directory dir, boolean multiSegment) throws IOException { MergePolicy mp; if (multiSegment) { mp = NoMergePolicy.INSTANCE; } else { mp = new LogDocMergePolicy(); } IndexWriter w = new IndexWriter( dir, LuceneTestCase.newIndexWriterConfig(random, new MockAnalyzer(random)) .setMergePolicy(mp)); for (int i = 0; i < 100; i++) { w.addDocument(createDocument(i, 4)); if (multiSegment && (i % 10) == 0) { w.commit(); } } if (!multiSegment) { w.forceMerge(1); } w.close(); DirectoryReader r = DirectoryReader.open(dir); if (multiSegment) { assertTrue(r.leaves().size() > 1); } else { assertTrue(r.leaves().size() == 1); } r.close(); } public static Document createDocument(int n, int numFields) { StringBuilder sb = new StringBuilder(); Document doc = new Document(); sb.append("a"); sb.append(n); FieldType customType2 = new FieldType(TextField.TYPE_STORED); customType2.setTokenized(false); customType2.setOmitNorms(true); FieldType customType3 = new FieldType(); customType3.setStored(true); doc.add(new TextField("field1", sb.toString(), Field.Store.YES)); doc.add(new Field("fielda", sb.toString(), customType2)); doc.add(new Field("fieldb", sb.toString(), customType3)); sb.append(" b"); sb.append(n); for (int i = 1; i < numFields; i++) { doc.add(new TextField("field" + (i + 1), sb.toString(), Field.Store.YES)); } return doc; } static void modifyIndex(int i, Directory dir) throws IOException { switch (i) { case 0: { if (VERBOSE) { System.out.println("TEST: modify index"); } IndexWriter w = new IndexWriter( dir, new IndexWriterConfig(new MockAnalyzer(random())) .setMergePolicy(NoMergePolicy.INSTANCE)); w.deleteDocuments(new Term("field2", "a11")); w.deleteDocuments(new Term("field2", "b30")); w.close(); break; } case 1: { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))); w.forceMerge(1); w.close(); break; } case 2: { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))); w.addDocument(createDocument(101, 4)); w.forceMerge(1); w.addDocument(createDocument(102, 4)); w.addDocument(createDocument(103, 4)); w.close(); break; } case 3: { IndexWriter w = new IndexWriter( dir, new IndexWriterConfig(new MockAnalyzer(random())) .setMergePolicy(NoMergePolicy.INSTANCE)); w.addDocument(createDocument(101, 4)); w.close(); break; } } } static void assertReaderClosed(IndexReader reader, boolean checkSubReaders) { assertEquals(0, reader.getRefCount()); if (checkSubReaders && reader instanceof CompositeReader) { // we cannot use reader context here, as reader is // already closed and calling getTopReaderContext() throws AlreadyClosed! List<? extends IndexReader> subReaders = ((CompositeReader) reader).getSequentialSubReaders(); for (final IndexReader r : subReaders) { assertReaderClosed(r, checkSubReaders); } } } abstract static class TestReopen { protected abstract DirectoryReader openReader() throws IOException; protected abstract void modifyIndex(int i) throws IOException; } static class KeepAllCommits extends IndexDeletionPolicy { @Override public void onInit(List<? extends IndexCommit> commits) {} @Override public void onCommit(List<? extends IndexCommit> commits) {} } public void testReopenOnCommit() throws Throwable { Directory dir = newDirectory(); IndexWriter writer = new IndexWriter( dir, newIndexWriterConfig(new MockAnalyzer(random())) .setIndexDeletionPolicy(new KeepAllCommits()) .setMaxBufferedDocs(-1) .setMergePolicy(newLogMergePolicy(10))); for (int i = 0; i < 4; i++) { Document doc = new Document(); doc.add(newStringField("id", "" + i, Field.Store.NO)); writer.addDocument(doc); Map<String, String> data = new HashMap<>(); data.put("index", i + ""); writer.setLiveCommitData(data.entrySet()); writer.commit(); } for (int i = 0; i < 4; i++) { writer.deleteDocuments(new Term("id", "" + i)); Map<String, String> data = new HashMap<>(); data.put("index", (4 + i) + ""); writer.setLiveCommitData(data.entrySet()); writer.commit(); } writer.close(); DirectoryReader r = DirectoryReader.open(dir); assertEquals(0, r.numDocs()); Collection<IndexCommit> commits = DirectoryReader.listCommits(dir); for (final IndexCommit commit : commits) { DirectoryReader r2 = DirectoryReader.openIfChanged(r, commit); assertNotNull(r2); assertTrue(r2 != r); final Map<String, String> s = commit.getUserData(); final int v; if (s.size() == 0) { // First commit created by IW v = -1; } else { v = Integer.parseInt(s.get("index")); } if (v < 4) { assertEquals(1 + v, r2.numDocs()); } else { assertEquals(7 - v, r2.numDocs()); } r.close(); r = r2; } r.close(); dir.close(); } public void testOpenIfChangedNRTToCommit() throws Exception { Directory dir = newDirectory(); // Can't use RIW because it randomly commits: IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random()))); Document doc = new Document(); doc.add(newStringField("field", "value", Field.Store.NO)); w.addDocument(doc); w.commit(); List<IndexCommit> commits = DirectoryReader.listCommits(dir); assertEquals(1, commits.size()); w.addDocument(doc); DirectoryReader r = DirectoryReader.open(w); assertEquals(2, r.numDocs()); IndexReader r2 = DirectoryReader.openIfChanged(r, commits.get(0)); assertNotNull(r2); r.close(); assertEquals(1, r2.numDocs()); w.close(); r2.close(); dir.close(); } public void testOverDecRefDuringReopen() throws Exception { MockDirectoryWrapper dir = newMockDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(NoMergePolicy.INSTANCE); iwc.setCodec(TestUtil.getDefaultCodec()); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(newStringField("id", "id", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("id", "id2", Field.Store.NO)); w.addDocument(doc); w.commit(); // Open reader w/ one segment w/ 2 docs: DirectoryReader r = DirectoryReader.open(dir); // Delete 1 doc from the segment: // System.out.println("TEST: now delete"); w.deleteDocuments(new Term("id", "id")); // System.out.println("TEST: now commit"); w.commit(); // Fail when reopen tries to open the live docs file: dir.failOn( new MockDirectoryWrapper.Failure() { boolean failed; @Override public void eval(MockDirectoryWrapper dir) throws IOException { if (failed) { return; } // System.out.println("failOn: "); // new Throwable().printStackTrace(System.out); if (callStackContainsAnyOf("readLiveDocs")) { if (VERBOSE) { System.out.println("TEST: now fail; exc:"); new Throwable().printStackTrace(System.out); } failed = true; throw new FakeIOException(); } } }); // Now reopen: // System.out.println("TEST: now reopen"); expectThrows( FakeIOException.class, () -> { DirectoryReader.openIfChanged(r); }); IndexSearcher s = newSearcher(r); assertEquals(1, s.count(new TermQuery(new Term("id", "id")))); r.close(); w.close(); dir.close(); } public void testNPEAfterInvalidReindex1() throws Exception { Directory dir = new ByteBuffersDirectory(); IndexWriter w = new IndexWriter( dir, new IndexWriterConfig(new MockAnalyzer(random())) .setMergePolicy(NoMergePolicy.INSTANCE)); Document doc = new Document(); doc.add(newStringField("id", "id", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("id", "id2", Field.Store.NO)); w.addDocument(doc); w.deleteDocuments(new Term("id", "id")); w.commit(); w.close(); // Open reader w/ one segment w/ 2 docs, 1 deleted: DirectoryReader r = DirectoryReader.open(dir); // Blow away the index: for (String fileName : dir.listAll()) { dir.deleteFile(fileName); } w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))); doc = new Document(); doc.add(newStringField("id", "id", Field.Store.NO)); doc.add(new NumericDocValuesField("ndv", 13)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("id", "id2", Field.Store.NO)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(newStringField("id", "id2", Field.Store.NO)); w.addDocument(doc); w.updateNumericDocValue(new Term("id", "id"), "ndv", 17L); w.commit(); w.close(); expectThrows( IllegalStateException.class, () -> { DirectoryReader.openIfChanged(r); }); r.close(); w.close(); dir.close(); } public void testNPEAfterInvalidReindex2() throws Exception { Directory dir = new ByteBuffersDirectory(); IndexWriter w = new IndexWriter( dir, new IndexWriterConfig(new MockAnalyzer(random())) .setMergePolicy(NoMergePolicy.INSTANCE)); Document doc = new Document(); doc.add(newStringField("id", "id", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("id", "id2", Field.Store.NO)); w.addDocument(doc); w.deleteDocuments(new Term("id", "id")); w.commit(); w.close(); // Open reader w/ one segment w/ 2 docs, 1 deleted: DirectoryReader r = DirectoryReader.open(dir); // Blow away the index: for (String name : dir.listAll()) { dir.deleteFile(name); } w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))); doc = new Document(); doc.add(newStringField("id", "id", Field.Store.NO)); doc.add(new NumericDocValuesField("ndv", 13)); w.addDocument(doc); w.commit(); doc = new Document(); doc.add(newStringField("id", "id2", Field.Store.NO)); w.addDocument(doc); w.commit(); w.close(); expectThrows( IllegalStateException.class, () -> { DirectoryReader.openIfChanged(r); }); r.close(); dir.close(); } /** test reopening backwards from a non-NRT reader (with document deletes) */ public void testNRTMdeletes() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(NoMergePolicy.INSTANCE); SnapshotDeletionPolicy snapshotter = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); iwc.setIndexDeletionPolicy(snapshotter); IndexWriter writer = new IndexWriter(dir, iwc); writer.commit(); // make sure all index metadata is written out Document doc = new Document(); doc.add(new StringField("key", "value1", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(new StringField("key", "value2", Field.Store.YES)); writer.addDocument(doc); writer.commit(); IndexCommit ic1 = snapshotter.snapshot(); doc = new Document(); doc.add(new StringField("key", "value3", Field.Store.YES)); writer.updateDocument(new Term("key", "value1"), doc); writer.commit(); IndexCommit ic2 = snapshotter.snapshot(); DirectoryReader latest = DirectoryReader.open(ic2); assertEquals(2, latest.leaves().size()); // This reader will be used for searching against commit point 1 DirectoryReader oldest = DirectoryReader.openIfChanged(latest, ic1); assertEquals(1, oldest.leaves().size()); // sharing same core assertSame( latest.leaves().get(0).reader().getCoreCacheHelper().getKey(), oldest.leaves().get(0).reader().getCoreCacheHelper().getKey()); latest.close(); oldest.close(); snapshotter.release(ic1); snapshotter.release(ic2); writer.close(); dir.close(); } /** test reopening backwards from an NRT reader (with document deletes) */ public void testNRTMdeletes2() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(NoMergePolicy.INSTANCE); SnapshotDeletionPolicy snapshotter = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); iwc.setIndexDeletionPolicy(snapshotter); IndexWriter writer = new IndexWriter(dir, iwc); writer.commit(); // make sure all index metadata is written out Document doc = new Document(); doc.add(new StringField("key", "value1", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(new StringField("key", "value2", Field.Store.YES)); writer.addDocument(doc); writer.commit(); IndexCommit ic1 = snapshotter.snapshot(); doc = new Document(); doc.add(new StringField("key", "value3", Field.Store.YES)); writer.updateDocument(new Term("key", "value1"), doc); DirectoryReader latest = DirectoryReader.open(writer); assertEquals(2, latest.leaves().size()); // This reader will be used for searching against commit point 1 DirectoryReader oldest = DirectoryReader.openIfChanged(latest, ic1); // This reader should not see the deletion: assertEquals(2, oldest.numDocs()); assertFalse(oldest.hasDeletions()); snapshotter.release(ic1); assertEquals(1, oldest.leaves().size()); // sharing same core assertSame( latest.leaves().get(0).reader().getCoreCacheHelper().getKey(), oldest.leaves().get(0).reader().getCoreCacheHelper().getKey()); latest.close(); oldest.close(); writer.close(); dir.close(); } /** test reopening backwards from a non-NRT reader with DV updates */ public void testNRTMupdates() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SnapshotDeletionPolicy snapshotter = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); iwc.setIndexDeletionPolicy(snapshotter); IndexWriter writer = new IndexWriter(dir, iwc); writer.commit(); // make sure all index metadata is written out Document doc = new Document(); doc.add(new StringField("key", "value1", Field.Store.YES)); doc.add(new NumericDocValuesField("dv", 1)); writer.addDocument(doc); writer.commit(); IndexCommit ic1 = snapshotter.snapshot(); writer.updateNumericDocValue(new Term("key", "value1"), "dv", 2); writer.commit(); IndexCommit ic2 = snapshotter.snapshot(); DirectoryReader latest = DirectoryReader.open(ic2); assertEquals(1, latest.leaves().size()); // This reader will be used for searching against commit point 1 DirectoryReader oldest = DirectoryReader.openIfChanged(latest, ic1); assertEquals(1, oldest.leaves().size()); // sharing same core assertSame( latest.leaves().get(0).reader().getCoreCacheHelper().getKey(), oldest.leaves().get(0).reader().getCoreCacheHelper().getKey()); NumericDocValues values = getOnlyLeafReader(oldest).getNumericDocValues("dv"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); values = getOnlyLeafReader(latest).getNumericDocValues("dv"); assertEquals(0, values.nextDoc()); assertEquals(2, values.longValue()); latest.close(); oldest.close(); snapshotter.release(ic1); snapshotter.release(ic2); writer.close(); dir.close(); } /** test reopening backwards from an NRT reader with DV updates */ public void testNRTMupdates2() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random())); SnapshotDeletionPolicy snapshotter = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy()); iwc.setIndexDeletionPolicy(snapshotter); IndexWriter writer = new IndexWriter(dir, iwc); writer.commit(); // make sure all index metadata is written out Document doc = new Document(); doc.add(new StringField("key", "value1", Field.Store.YES)); doc.add(new NumericDocValuesField("dv", 1)); writer.addDocument(doc); writer.commit(); IndexCommit ic1 = snapshotter.snapshot(); writer.updateNumericDocValue(new Term("key", "value1"), "dv", 2); DirectoryReader latest = DirectoryReader.open(writer); assertEquals(1, latest.leaves().size()); // This reader will be used for searching against commit point 1 DirectoryReader oldest = DirectoryReader.openIfChanged(latest, ic1); assertEquals(1, oldest.leaves().size()); // sharing same core assertSame( latest.leaves().get(0).reader().getCoreCacheHelper().getKey(), oldest.leaves().get(0).reader().getCoreCacheHelper().getKey()); NumericDocValues values = getOnlyLeafReader(oldest).getNumericDocValues("dv"); assertEquals(0, values.nextDoc()); assertEquals(1, values.longValue()); values = getOnlyLeafReader(latest).getNumericDocValues("dv"); assertEquals(0, values.nextDoc()); assertEquals(2, values.longValue()); latest.close(); oldest.close(); snapshotter.release(ic1); writer.close(); dir.close(); } // LUCENE-5931: we make a "best effort" to catch this abuse and throw a clear(er) // exception than what would otherwise look like hard to explain index corruption during searching public void testDeleteIndexFilesWhileReaderStillOpen() throws Exception { Directory dir = new ByteBuffersDirectory(); IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))); Document doc = new Document(); doc.add(newStringField("field", "value", Field.Store.NO)); w.addDocument(doc); // Creates single segment index: w.close(); DirectoryReader r = DirectoryReader.open(dir); // Abuse: remove all files while reader is open; one is supposed to use IW.deleteAll, or open a // new IW with OpenMode.CREATE instead: for (String file : dir.listAll()) { dir.deleteFile(file); } w = new IndexWriter( dir, new IndexWriterConfig(new MockAnalyzer(random())) .setMergePolicy(NoMergePolicy.INSTANCE)); doc = new Document(); doc.add(newStringField("field", "value", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("field", "value2", Field.Store.NO)); w.addDocument(doc); // Writes same segment, this time with two documents: w.commit(); w.deleteDocuments(new Term("field", "value2")); w.addDocument(doc); // Writes another segments file, so openIfChanged sees that the index has in fact changed: w.close(); expectThrows( IllegalStateException.class, () -> { DirectoryReader.openIfChanged(r); }); } public void testReuseUnchangedLeafReaderOnDVUpdate() throws IOException { Directory dir = newDirectory(); IndexWriterConfig indexWriterConfig = newIndexWriterConfig(); indexWriterConfig.setMergePolicy(NoMergePolicy.INSTANCE); IndexWriter writer = new IndexWriter(dir, indexWriterConfig); Document doc = new Document(); doc.add(new StringField("id", "1", Field.Store.YES)); doc.add(new StringField("version", "1", Field.Store.YES)); doc.add(new NumericDocValuesField("some_docvalue", 2)); writer.addDocument(doc); doc = new Document(); doc.add(new StringField("id", "2", Field.Store.YES)); doc.add(new StringField("version", "1", Field.Store.YES)); writer.addDocument(doc); writer.commit(); DirectoryReader reader = DirectoryReader.open(dir); assertEquals(2, reader.numDocs()); assertEquals(2, reader.maxDoc()); assertEquals(0, reader.numDeletedDocs()); doc = new Document(); doc.add(new StringField("id", "1", Field.Store.YES)); doc.add(new StringField("version", "2", Field.Store.YES)); writer.updateDocValues(new Term("id", "1"), new NumericDocValuesField("some_docvalue", 1)); writer.commit(); DirectoryReader newReader = DirectoryReader.openIfChanged(reader); assertNotSame(newReader, reader); reader.close(); reader = newReader; assertEquals(2, reader.numDocs()); assertEquals(2, reader.maxDoc()); assertEquals(0, reader.numDeletedDocs()); doc = new Document(); doc.add(new StringField("id", "3", Field.Store.YES)); doc.add(new StringField("version", "3", Field.Store.YES)); writer.updateDocument(new Term("id", "3"), doc); writer.commit(); newReader = DirectoryReader.openIfChanged(reader); assertNotSame(newReader, reader); assertEquals(2, newReader.getSequentialSubReaders().size()); assertEquals(1, reader.getSequentialSubReaders().size()); assertSame(reader.getSequentialSubReaders().get(0), newReader.getSequentialSubReaders().get(0)); reader.close(); reader = newReader; assertEquals(3, reader.numDocs()); assertEquals(3, reader.maxDoc()); assertEquals(0, reader.numDeletedDocs()); IOUtils.close(reader, writer, dir); } }
googleapis/google-cloud-java
36,769
java-orchestration-airflow/proto-google-cloud-orchestration-airflow-v1/src/main/java/com/google/cloud/orchestration/airflow/service/v1/UserWorkloadsConfigMap.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/orchestration/airflow/service/v1/environments.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.orchestration.airflow.service.v1; /** * * * <pre> * User workloads ConfigMap used by Airflow tasks that run with Kubernetes * executor or KubernetesPodOperator. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap} */ public final class UserWorkloadsConfigMap extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap) UserWorkloadsConfigMapOrBuilder { private static final long serialVersionUID = 0L; // Use UserWorkloadsConfigMap.newBuilder() to construct. private UserWorkloadsConfigMap(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UserWorkloadsConfigMap() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UserWorkloadsConfigMap(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_UserWorkloadsConfigMap_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 2: return internalGetData(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_UserWorkloadsConfigMap_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap.class, com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </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 resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </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 DATA_FIELD_NUMBER = 2; private static final class DataDefaultEntryHolder { 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.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_UserWorkloadsConfigMap_DataEntry_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> data_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetData() { if (data_ == null) { return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); } return data_; } public int getDataCount() { return internalGetData().getMap().size(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public boolean containsData(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetData().getMap().containsKey(key); } /** Use {@link #getDataMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getData() { return getDataMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getDataMap() { return internalGetData().getMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public /* nullable */ java.lang.String getDataOrDefault( 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 = internalGetData().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getDataOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetData().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(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetData(), DataDefaultEntryHolder.defaultEntry, 2); getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetData().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> data__ = DataDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, data__); } 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.orchestration.airflow.service.v1.UserWorkloadsConfigMap)) { return super.equals(obj); } com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap other = (com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap) obj; if (!getName().equals(other.getName())) return false; if (!internalGetData().equals(other.internalGetData())) 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 (!internalGetData().getMap().isEmpty()) { hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + internalGetData().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap 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.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap 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.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap 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.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap 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.orchestration.airflow.service.v1.UserWorkloadsConfigMap parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap 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.orchestration.airflow.service.v1.UserWorkloadsConfigMap 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> * User workloads ConfigMap used by Airflow tasks that run with Kubernetes * executor or KubernetesPodOperator. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap) com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMapOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_UserWorkloadsConfigMap_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 2: return internalGetData(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 2: return internalGetMutableData(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_UserWorkloadsConfigMap_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap.class, com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap.Builder .class); } // Construct using // com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; internalGetMutableData().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_UserWorkloadsConfigMap_descriptor; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap getDefaultInstanceForType() { return com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap .getDefaultInstance(); } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap build() { com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap buildPartial() { com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap result = new com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.data_ = internalGetData(); result.data_.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.orchestration.airflow.service.v1.UserWorkloadsConfigMap) { return mergeFrom( (com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap other) { if (other == com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap .getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } internalGetMutableData().mergeFrom(other.internalGetData()); bitField0_ |= 0x00000002; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> data__ = input.readMessage( DataDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableData().getMutableMap().put(data__.getKey(), data__.getValue()); 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.lang.Object name_ = ""; /** * * * <pre> * Identifier. The resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </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 resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </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 resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </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 resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </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 resource name of the ConfigMap, in the form: * "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> data_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetData() { if (data_ == null) { return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); } return data_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableData() { if (data_ == null) { data_ = com.google.protobuf.MapField.newMapField(DataDefaultEntryHolder.defaultEntry); } if (!data_.isMutable()) { data_ = data_.copy(); } bitField0_ |= 0x00000002; onChanged(); return data_; } public int getDataCount() { return internalGetData().getMap().size(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public boolean containsData(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetData().getMap().containsKey(key); } /** Use {@link #getDataMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getData() { return getDataMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getDataMap() { return internalGetData().getMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public /* nullable */ java.lang.String getDataOrDefault( 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 = internalGetData().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ @java.lang.Override public java.lang.String getDataOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetData().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearData() { bitField0_ = (bitField0_ & ~0x00000002); internalGetMutableData().getMutableMap().clear(); return this; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder removeData(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableData().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableData() { bitField0_ |= 0x00000002; return internalGetMutableData().getMutableMap(); } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder putData(java.lang.String key, java.lang.String value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableData().getMutableMap().put(key, value); bitField0_ |= 0x00000002; return this; } /** * * * <pre> * Optional. The "data" field of Kubernetes ConfigMap, organized in key-value * pairs. For details see: * https://kubernetes.io/docs/concepts/configuration/configmap/ * * Example: * * { * "example_key": "example_value", * "another_key": "another_value" * } * </pre> * * <code>map&lt;string, string&gt; data = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ public Builder putAllData(java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableData().getMutableMap().putAll(values); bitField0_ |= 0x00000002; return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap) } // @@protoc_insertion_point(class_scope:google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap) private static final com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap(); } public static com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UserWorkloadsConfigMap> PARSER = new com.google.protobuf.AbstractParser<UserWorkloadsConfigMap>() { @java.lang.Override public UserWorkloadsConfigMap 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<UserWorkloadsConfigMap> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UserWorkloadsConfigMap> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.UserWorkloadsConfigMap getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/sis
36,890
endorsed/src/org.apache.sis.referencing/main/org/apache/sis/referencing/operation/DefaultOperationMethod.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.sis.referencing.operation; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.Objects; import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import org.opengis.util.InternationalString; import org.opengis.metadata.citation.Citation; import org.opengis.referencing.IdentifiedObject; import org.opengis.referencing.operation.Formula; import org.opengis.referencing.operation.Conversion; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.OperationMethod; import org.opengis.referencing.operation.SingleOperation; import org.opengis.parameter.GeneralParameterDescriptor; import org.opengis.parameter.ParameterDescriptorGroup; import org.opengis.parameter.ParameterDescriptor; import org.apache.sis.util.ArgumentChecks; import org.apache.sis.util.Utilities; import org.apache.sis.util.Workaround; import org.apache.sis.util.ComparisonMode; import org.apache.sis.util.SimpleInternationalString; import org.apache.sis.util.resources.Errors; import org.apache.sis.util.resources.Vocabulary; import org.apache.sis.referencing.NamedIdentifier; import org.apache.sis.referencing.IdentifiedObjects; import org.apache.sis.referencing.AbstractIdentifiedObject; import org.apache.sis.referencing.internal.shared.WKTKeywords; import org.apache.sis.referencing.internal.shared.NilReferencingObject; import org.apache.sis.xml.bind.gco.StringAdapter; import org.apache.sis.xml.bind.referencing.CC_OperationMethod; import org.apache.sis.metadata.internal.shared.Identifiers; import org.apache.sis.metadata.internal.shared.ImplementationHelper; import org.apache.sis.parameter.DefaultParameterDescriptorGroup; import org.apache.sis.parameter.Parameterized; import org.apache.sis.io.wkt.Formatter; import org.apache.sis.io.wkt.ElementKind; import org.apache.sis.io.wkt.FormattableObject; // Specific to the main and geoapi-3.1 branches: import jakarta.xml.bind.annotation.XmlSchemaType; import org.opengis.referencing.crs.GeneralDerivedCRS; /** * Describes the algorithm and parameters used to perform a coordinate operation. An {@code OperationMethod} * is a kind of metadata: it does not perform any coordinate operation (e.g. map projection) by itself, but * tells us what is needed in order to perform such operation. * * <p>The most important parts of an {@code OperationMethod} are its {@linkplain #getName() name} and its * {@linkplain #getParameters() group of parameter descriptors}. The parameter descriptors do not contain * any value, but tell us what are the expected parameters, together with their units of measurement.</p> * * <p>In Apache SIS implementation, the {@linkplain #getName() name} is the only mandatory property. * However, it is recommended to provide also {@linkplain #getIdentifiers() identifiers} * (e.g. “EPSG:9804” in the following example) * because names can sometimes be ambiguous or be spelled in different ways.</p> * * <h2>Example</h2> * An operation method named <q>Mercator (variant A)</q> (EPSG:9804) expects the following parameters: * <ul> * <li><q>Latitude of natural origin</q> in degrees. Default value is 0°.</li> * <li><q>Longitude of natural origin</q> in degrees. Default value is 0°.</li> * <li><q>Scale factor at natural origin</q> as a dimensionless number. Default value is 1.</li> * <li><q>False easting</q> in metres. Default value is 0 m.</li> * <li><q>False northing</q> in metres. Default value is 0 m.</li> * </ul> * * <h2>Departure from the ISO 19111 standard</h2> * The following properties are mandatory according ISO 19111, * but may be missing under some conditions in Apache SIS: * <ul> * <li>The {@linkplain #getFormula() formula} if it has not been provided to the * {@linkplain #DefaultOperationMethod(Map, ParameterDescriptorGroup) constructor}, or if it * cannot be {@linkplain #DefaultOperationMethod(MathTransform) inferred from the given math transform}.</li> * <li>The {@linkplain #getParameters() parameters} if the {@link #DefaultOperationMethod(MathTransform)} * constructor cannot infer them.</li> * </ul> * * <h2>Relationship with other classes or interfaces</h2> * {@code OperationMethod} describes parameters without providing any value (except sometimes default values). * When values have been assigned to parameters, the result is a {@link SingleOperation}. * Note that there is different kinds of {@code SingleOperation} depending on the nature and accuracy of the * coordinate operation. See {@link #getOperationType()} for more information. * * <p>The interface performing the actual work of taking coordinates in the * {@linkplain AbstractCoordinateOperation#getSourceCRS() source CRS} and calculating the new coordinates in the * {@linkplain AbstractCoordinateOperation#getTargetCRS() target CRS} is {@link MathTransform}. * In order to allow Apache SIS to instantiate those {@code MathTransform}s from given parameter values, * {@code DefaultOperationMethod} subclasses should implement the * {@link org.apache.sis.referencing.operation.transform.MathTransformProvider} interface.</p> * * <h2>Immutability and thread safety</h2> * This class is immutable and thread-safe if all properties given to the constructor are also immutable and thread-safe. * It is strongly recommended for all subclasses to be thread-safe, especially the * {@link org.apache.sis.referencing.operation.transform.MathTransformProvider} implementations to be used with * {@link org.apache.sis.referencing.operation.transform.DefaultMathTransformFactory}. * * @author Martin Desruisseaux (IRD, Geomatys) * @version 1.5 * * @see DefaultConversion * @see DefaultTransformation * @see org.apache.sis.referencing.operation.transform.MathTransformProvider * * @since 0.5 */ @XmlType(name = "OperationMethodType", propOrder = { "formulaCitation", "formulaDescription", "sourceDimensions", "targetDimensions", "descriptors" }) @XmlRootElement(name = "OperationMethod") public class DefaultOperationMethod extends AbstractIdentifiedObject implements OperationMethod { /* * NOTE FOR JAVADOC WRITER: * The "method" word is ambiguous here, because it can be "Java method" or "coordinate operation method". * In this class, we reserve the "method" word for "coordinate operation method" as much as possible. */ /** * Serial number for inter-operability with different versions. */ private static final long serialVersionUID = 6612049971779439502L; /** * Formula(s) or procedure used by this operation method. This may be a reference to a publication. * Note that the operation method may not be analytic, in which case this attribute references or * contains the procedure, not an analytic formula. * * <p><b>Consider this field as final!</b> * This field is modified only at unmarshalling time by {@link #setFormulaCitation(Citation)} * or {@link #setFormulaDescription(String)}.</p> */ @SuppressWarnings("serial") // Most SIS implementations are serializable. private Formula formula; /** * The set of parameters, or {@code null} if none. * * <p><b>Consider this field as final!</b> * This field is modified only at unmarshalling time by {@link #setDescriptors(GeneralParameterDescriptor[])} * or {@link #afterUnmarshal(Unmarshaller, Object)}.</p> */ @SuppressWarnings("serial") // Most SIS implementations are serializable. private ParameterDescriptorGroup parameters; /** * Constructs an operation method from a set of properties and a descriptor group. The properties map is given * unchanged to the {@linkplain AbstractIdentifiedObject#AbstractIdentifiedObject(Map) super-class constructor}. * In addition to the properties documented in the parent constructor, * the following properties are understood by this constructor: * * <table class="sis"> * <caption>Recognized properties (non exhaustive list)</caption> * <tr> * <th>Property name</th> * <th>Value type</th> * <th>Returned by</th> * </tr><tr> * <td>{@value org.opengis.referencing.operation.OperationMethod#FORMULA_KEY}</td> * <td>{@link Formula}, {@link Citation} or {@link CharSequence}</td> * <td>{@link #getFormula()}</td> * </tr><tr> * <th colspan="3" class="hsep">Defined in parent classes (reminder)</th> * </tr><tr> * <td>{@value org.opengis.referencing.IdentifiedObject#NAME_KEY}</td> * <td>{@link org.opengis.metadata.Identifier} or {@link String}</td> * <td>{@link #getName()}</td> * </tr><tr> * <td>{@value org.opengis.referencing.IdentifiedObject#ALIAS_KEY}</td> * <td>{@link org.opengis.util.GenericName} or {@link CharSequence} (optionally as array)</td> * <td>{@link #getAlias()}</td> * </tr><tr> * <td>{@value org.opengis.referencing.IdentifiedObject#IDENTIFIERS_KEY}</td> * <td>{@link org.opengis.metadata.Identifier} (optionally as array)</td> * <td>{@link #getIdentifiers()}</td> * </tr><tr> * <td>{@value org.opengis.referencing.IdentifiedObject#REMARKS_KEY}</td> * <td>{@link InternationalString} or {@link String}</td> * <td>{@link #getRemarks()}</td> * </tr> * </table> * * @param properties set of properties. Shall contain at least {@code "name"}. * @param parameters description of parameters expected by this operation. * * @since 1.1 */ public DefaultOperationMethod(final Map<String,?> properties, final ParameterDescriptorGroup parameters) { super(properties); ArgumentChecks.ensureNonNull("parameters", parameters); Object value = properties.get(FORMULA_KEY); if (value == null || value instanceof Formula) { formula = (Formula) value; } else if (value instanceof Citation) { formula = new DefaultFormula((Citation) value); } else if (value instanceof CharSequence) { formula = new DefaultFormula((CharSequence) value); } else { throw new IllegalArgumentException(Errors.forProperties(properties) .getString(Errors.Keys.IllegalPropertyValueClass_2, FORMULA_KEY, value.getClass())); } this.parameters = parameters; } /** * Convenience constructor that creates an operation method from a math transform. * The information provided in the newly created object are approximations, and * usually acceptable only as a fallback when no other information are available. * * @param transform the math transform to describe. */ public DefaultOperationMethod(final MathTransform transform) { super(getProperties(transform)); if (transform instanceof Parameterized) { parameters = ((Parameterized) transform).getParameterDescriptors(); } } /** * Work around for RFE #4093999 in Sun's bug database * ("Relax constraint on placement of this()/super() call in constructors"). */ @Workaround(library="JDK", version="1.7") private static Map<String,?> getProperties(final MathTransform transform) { ArgumentChecks.ensureNonNull("transform", transform); if (transform instanceof Parameterized) { final ParameterDescriptorGroup parameters = ((Parameterized) transform).getParameterDescriptors(); if (parameters != null) { return getProperties(parameters, null); } } return Map.of(NAME_KEY, NilReferencingObject.UNNAMED); } /** * Returns the properties to be given to an identified object derived from the specified one. * This method returns the same properties as the supplied argument * (as of <code>{@linkplain IdentifiedObjects#getProperties getProperties}(info)</code>), * except for the following: * * <ul> * <li>The {@linkplain IdentifiedObject#getName() name}'s authority is replaced by the specified one.</li> * <li>All {@linkplain IdentifiedObject#getIdentifiers identifiers} are removed, because the new object * to be created is probably not endorsed by the original authority.</li> * </ul> * * This method returns a mutable map. Consequently, callers can add their own identifiers * directly to this map if they wish. * * @param info the identified object to view as a properties map. * @param authority the new authority for the object to be created, * or {@code null} if it is not going to have any declared authority. * @return the identified object properties in a mutable map. */ private static Map<String,Object> getProperties(final IdentifiedObject info, final Citation authority) { final Map<String,Object> properties = new HashMap<>(IdentifiedObjects.getProperties(info)); properties.put(NAME_KEY, new NamedIdentifier(authority, info.getName().getCode())); properties.remove(IDENTIFIERS_KEY); return properties; } /** * Creates a new operation method with the same values as the specified one. * This copy constructor provides a way to convert an arbitrary implementation into a SIS one * or a user-defined one (as a subclass), usually in order to leverage some implementation-specific API. * * <p>This constructor performs a shallow copy, i.e. the properties are not cloned.</p> * * @param method the operation method to copy. * * @see #castOrCopy(OperationMethod) */ protected DefaultOperationMethod(final OperationMethod method) { super(method); formula = method.getFormula(); parameters = method.getParameters(); } /** * Returns a SIS operation method implementation with the same values as the given arbitrary implementation. * If the given object is {@code null}, then {@code null} is returned. * Otherwise if the given object is already a SIS implementation, then the given object is returned unchanged. * Otherwise a new SIS implementation is created and initialized to the attribute values of the given object. * * @param object the object to get as a SIS implementation, or {@code null} if none. * @return a SIS implementation containing the values of the given object (may be the * given object itself), or {@code null} if the argument was null. */ public static DefaultOperationMethod castOrCopy(final OperationMethod object) { return (object == null) || (object instanceof DefaultOperationMethod) ? (DefaultOperationMethod) object : new DefaultOperationMethod(object); } /** * Returns the GeoAPI interface implemented by this class. * The SIS implementation returns {@code OperationMethod.class}. * * <h4>Note for implementers</h4> * Subclasses usually do not need to override this information since GeoAPI does not define {@code OperationMethod} * sub-interface. Overriding possibility is left mostly for implementers who wish to extend GeoAPI with their * own set of interfaces. * * @return {@code OperationMethod.class} or a user-defined sub-interface. */ @Override public Class<? extends OperationMethod> getInterface() { return OperationMethod.class; } /** * Returns the base interface of the {@code CoordinateOperation} instances that use this method. * The base {@code CoordinateOperation} interface is usually one of the following subtypes: * * <ul class="verbose"> * <li class="verbose">{@link org.opengis.referencing.operation.Conversion} * if the coordinate operation is theoretically of infinite precision, ignoring the limitations of floating * point arithmetic (including rounding errors) and the approximations implied by finite series expansions.</li> * <li>{@link org.opengis.referencing.operation.Transformation} * if the coordinate operation has some errors (typically of a few metres) because of the empirical process by * which the operation parameters were determined. Those errors do not depend on the floating point precision * or the accuracy of the implementation algorithm.</li> * <li>{@link org.opengis.referencing.operation.PointMotionOperation} * if the coordinate operation applies changes due to the motion of points between two coordinate epochs.</li> * </ul> * * In case of doubt, {@code getOperationType()} can conservatively return the base type. * The default implementation returns {@code SingleOperation.class}, * which is the most conservative return value. * * @return interface implemented by all coordinate operations that use this method. * * @see org.apache.sis.referencing.operation.transform.DefaultMathTransformFactory#getAvailableMethods(Class) */ public Class<? extends SingleOperation> getOperationType() { return SingleOperation.class; } /** * Formula(s) or procedure used by this operation method. This may be a reference to a * publication. Note that the operation method may not be analytic, in which case this * attribute references or contains the procedure, not an analytic formula. * * <h4>Departure from the ISO 19111 standard</h4> * This property is mandatory according ISO 19111, but optional in Apache SIS. * * @return the formula used by this method, or {@code null} if unknown. * * @see DefaultFormula * @see org.apache.sis.referencing.operation.transform.MathTransformProvider */ @Override public Formula getFormula() { return formula; } /** * Number of dimensions in the source CRS of this operation method. * May be null if unknown, as in an <i>Affine Transform</i>. * * @return the dimension of source CRS, or {@code null} if unknown. * * @see org.apache.sis.referencing.operation.transform.AbstractMathTransform#getSourceDimensions() * * @deprecated This attribute has been removed from ISO 19111:2019. */ @Override @Deprecated(since="1.1") @XmlElement(name = "sourceDimensions") @XmlSchemaType(name = "positiveInteger") public Integer getSourceDimensions() { return null; } /** * Number of dimensions in the target CRS of this operation method. * May be null if unknown, as in an <i>Affine Transform</i>. * * @return the dimension of target CRS, or {@code null} if unknown. * * @see org.apache.sis.referencing.operation.transform.AbstractMathTransform#getTargetDimensions() * * @deprecated This attribute has been removed from ISO 19111:2019. */ @Override @Deprecated(since="1.1") @XmlElement(name = "targetDimensions") @XmlSchemaType(name = "positiveInteger") public Integer getTargetDimensions() { return null; } /** * Returns the set of parameters. * * <h4>Departure from the ISO 19111 standard</h4> * This property is mandatory according ISO 19111, but may be {@code null} in Apache SIS if the * {@link #DefaultOperationMethod(MathTransform)} constructor has been unable to infer it. * * @return the parameters, or {@code null} if unknown. * * @see DefaultConversion#getParameterDescriptors() * @see DefaultConversion#getParameterValues() */ @Override public ParameterDescriptorGroup getParameters() { return parameters; } /** * Compares this operation method with the specified object for equality. * If the {@code mode} argument value is {@link ComparisonMode#STRICT STRICT} or * {@link ComparisonMode#BY_CONTRACT BY_CONTRACT}, then all available properties * are compared including the {@linkplain #getFormula() formula}. * * @param object the object to compare to {@code this}. * @param mode the strictness level of the comparison. * @return {@code true} if both objects are equal. */ @Override public boolean equals(final Object object, final ComparisonMode mode) { if (object == this) { return true; // Slight optimization. } if (super.equals(object, mode)) { switch (mode) { case STRICT: { // Name and identifiers have been compared by super.equals(object, mode). final var that = (DefaultOperationMethod) object; return Objects.equals(this.formula, that.formula) && Objects.equals(this.parameters, that.parameters); } case BY_CONTRACT: { // Name and identifiers have been compared by super.equals(object, mode). if (!Objects.equals(getFormula(), ((OperationMethod) object).getFormula())) { return false; } break; } default: { /* * Name and identifiers have been ignored by super.equals(object, mode). * Since they are significant for OperationMethod, we compare them here. * * According ISO 19162 (Well Known Text representation of Coordinate Reference Systems), * identifiers shall have precedence over name at least in the case of operation methods * and parameters. */ final var that = (OperationMethod) object; final Boolean match = Identifiers.hasCommonIdentifier(getIdentifiers(), that.getIdentifiers()); if (match != null) { if (!match) { return false; } } else if (!isHeuristicMatchForName(that.getName().getCode()) && !IdentifiedObjects.isHeuristicMatchForName(that, getName().getCode())) { return false; } break; } } final var that = (OperationMethod) object; return Objects.equals(getSourceDimensions(), that.getSourceDimensions()) && Objects.equals(getTargetDimensions(), that.getTargetDimensions()) && Utilities.deepEquals(getParameters(), that.getParameters(), mode); } return false; } /** * Invoked by {@code hashCode()} for computing the hash code when first needed. * See {@link org.apache.sis.referencing.AbstractIdentifiedObject#computeHashCode()} * for more information. * * @return the hash code value. This value may change in any future Apache SIS version. * * @hidden because nothing new to said. */ @Override protected long computeHashCode() { return super.computeHashCode() + Objects.hashCode(parameters); } /** * Formats this operation as a <i>Well Known Text</i> {@code Method[…]} element. * * @return {@code "Method"} (WKT 2) or {@code "Projection"} (WKT 1). */ @Override protected String formatTo(final Formatter formatter) { final boolean isWKT1 = formatter.getConvention().majorVersion() == 1; /* * The next few lines below are basically a copy of the work done by super.formatTo(formatter), * which search for the name to write inside METHOD["name"]. The difference is in the fallback * executed if we do not find a name for the given authority. */ final Citation authority = formatter.getNameAuthority(); String name = IdentifiedObjects.getName(this, authority); ElementKind kind = ElementKind.METHOD; if (name == null) { /* * No name found for the given authority. We may use the primary name as a fallback. * But before doing that, maybe we can find the name that we are looking for in the * hard-coded values in the 'org.apache.sis.referencing.operation.provider' package. * The typical use case is when this DefaultOperationMethod has been instantiated * by the EPSG factory using only the information found in the EPSG database. * * We can find the hard-coded names by looking at the ParameterDescriptorGroup of the * enclosing ProjectedCRS or DerivedCRS. This is because that parameter descriptor was * typically provided by the 'org.apache.sis.referencing.operation.provider' package in * order to create the MathTransform associated with the enclosing CRS. The enclosing * CRS is either the immediate parent in WKT 1, or the parent of the parent in WKT 2. */ final FormattableObject parent = formatter.getEnclosingElement(isWKT1 ? 1 : 2); if (parent instanceof GeneralDerivedCRS) { final Conversion conversion = ((GeneralDerivedCRS) parent).getConversionFromBase(); if (conversion != null) { // Should never be null, but let be safe. final ParameterDescriptorGroup descriptor; if (conversion instanceof Parameterized) { // Usual case in SIS implementation. descriptor = ((Parameterized) conversion).getParameterDescriptors(); } else { descriptor = conversion.getParameterValues().getDescriptor(); } name = IdentifiedObjects.getName(descriptor, authority); } } if (name == null) { name = IdentifiedObjects.getName(this, null); if (name == null) { name = Vocabulary.forLocale(formatter.getLocale()).getString(Vocabulary.Keys.Unnamed); kind = ElementKind.NAME; // Because the "Unnamed" string is not a real OperationMethod name. } } } formatter.append(name, kind); if (isWKT1) { /* * The WKT 1 keyword is "PROJECTION", which imply that the operation method should be of type * org.opengis.referencing.operation.Conversion. So strictly speaking only the first check in * the following 'if' statement is relevant, and we should also check CRS types. * * Unfortunately in many cases we do not know the operation type, because the method that we * invoked - getOperationType() - is not a standard OGC/ISO property, so this information is * usually not provided in XML documents for example. The user could also have instantiated * DirectOperationMethod directly without creating a subclass. Consequently, we also accept to * format the keyword as "PROJECTION" if the operation type *could* be a projection. This is * the second check in the following 'if' statement. * * In other words, the combination of those two checks exclude the following operation types: * Transformation, ConcatenatedOperation, PassThroughOperation, or any user-defined type that * do not extend Conversion. All other operation types are accepted. */ final Class<? extends SingleOperation> type = getOperationType(); if (Conversion.class.isAssignableFrom(type) || type.isAssignableFrom(Conversion.class)) { return WKTKeywords.Projection; } formatter.setInvalidWKT(this, null); } return WKTKeywords.Method; } /* ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ XML support with JAXB ┃ ┃ ┃ ┃ The following methods are invoked by JAXB using reflection (even if ┃ ┃ they are private) or are helpers for other methods invoked by JAXB. ┃ ┃ Those methods can be safely removed if Geographic Markup Language ┃ ┃ (GML) support is not needed. ┃ ┃ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ */ /** * Creates a new object in which every attributes are set to a null value. * <strong>This is not a valid object.</strong> This constructor is strictly * reserved to JAXB, which will assign values to the fields using reflection. */ private DefaultOperationMethod() { super(org.apache.sis.referencing.internal.shared.NilReferencingObject.INSTANCE); } /** * Invoked by JAXB for marshalling a citation to the formula. In principle at most one of * {@code getFormulaCitation()} and {@link #getFormulaDescription()} methods can return a * non-null value. However, SIS accepts both coexist (but this is invalid GML). */ @XmlElement(name = "formulaCitation") private Citation getFormulaCitation() { final Formula formula = getFormula(); // Give to users a chance to override. return (formula != null) ? formula.getCitation() : null; } /** * Invoked by JAXB for marshalling the formula literally. In principle at most one of * {@code getFormulaDescription()} and {@link #getFormulaCitation()} methods can return * a non-null value. However, SIS accepts both to coexist (but this is invalid GML). */ @XmlElement(name = "formula") private String getFormulaDescription() { final Formula formula = getFormula(); // Give to users a chance to override. return (formula != null) ? StringAdapter.toString(formula.getFormula()) : null; } /** * Invoked by JAXB for setting the citation to the formula. */ private void setFormulaCitation(final Citation citation) { if (formula == null || formula.getCitation() == null) { formula = (formula == null) ? new DefaultFormula(citation) : new DefaultFormula(formula.getFormula(), citation); } else { ImplementationHelper.propertyAlreadySet(DefaultOperationMethod.class, "setFormulaCitation", "formulaCitation"); } } /** * Invoked by JAXB for setting the formula description. */ private void setFormulaDescription(final String description) { if (formula == null || formula.getFormula() == null) { formula = (formula == null) ? new DefaultFormula(description) : new DefaultFormula(new SimpleInternationalString(description), formula.getCitation()); } else { ImplementationHelper.propertyAlreadySet(DefaultOperationMethod.class, "setFormulaDescription", "formula"); } } /** * Invoked by JAXB for getting the parameters to marshal. This method usually marshals the sequence of * descriptors without their {@link ParameterDescriptorGroup} wrapper, because GML is defined that way. * The {@code ParameterDescriptorGroup} wrapper is a GeoAPI addition done for allowing usage of its * methods as a convenience (e.g. {@link ParameterDescriptorGroup#descriptor(String)}). * * <p>However, it could happen that the user really wanted to specify a {@code ParameterDescriptorGroup} as * the sole {@code <gml:parameter>} element. We currently have no easy way to distinguish those cases.</p> * * <h4>Tip</h4> * One possible way to distinguish the two cases would be to check that the parameter group does not contain * any property that this method does not have: * * {@snippet lang="java" : * if (IdentifiedObjects.getProperties(this).entrySet().containsAll( * IdentifiedObjects.getProperties(parameters).entrySet())) ... * } * * But we would need to make sure that {@link AbstractSingleOperation#getParameters()} is consistent * with the decision taken by this method. * * <h4>Historical note</h4> * Older, deprecated, names for the parameters were: * <ul> * <li>{@code includesParameter}</li> * <li>{@code generalOperationParameter} - note that this name was used by the EPSG repository</li> * <li>{@code usesParameter}</li> * </ul> * * @see #getParameters() * @see AbstractSingleOperation#getParameters() */ @XmlElement(name = "parameter") private GeneralParameterDescriptor[] getDescriptors() { if (parameters != null) { final List<GeneralParameterDescriptor> descriptors = parameters.descriptors(); if (descriptors != null) { // Paranoiac check (should not be allowed). return CC_OperationMethod.filterImplicit(descriptors.toArray(GeneralParameterDescriptor[]::new)); } } return null; } /** * Invoked by JAXB for setting the unmarshalled parameters. * This method wraps the given descriptors in a {@link DefaultParameterDescriptorGroup}. * * <p>The parameter descriptors created by this method are incomplete since we cannot * provide a non-null value for {@link ParameterDescriptor#getValueClass()}. The value * class will be provided either by replacing this {@code OperationMethod} by one of the * predefined methods, or by unmarshalling the enclosing {@link AbstractSingleOperation}.</p> * * <p><b>Maintenance note:</b> the {@code "setDescriptors"} method name is also hard-coded in * {@link org.apache.sis.xml.bind.referencing.CC_GeneralOperationParameter} for logging purpose.</p> * * @see AbstractSingleOperation#setParameters */ private void setDescriptors(final GeneralParameterDescriptor[] descriptors) { if (parameters == null) { parameters = CC_OperationMethod.group(super.getName(), descriptors); } else { ImplementationHelper.propertyAlreadySet(DefaultOperationMethod.class, "setDescriptors", "parameter"); } } /** * Invoked by {@link AbstractSingleOperation} for completing the parameter descriptor. */ final void updateDescriptors(final GeneralParameterDescriptor[] descriptors) { final ParameterDescriptorGroup previous = parameters; parameters = new DefaultParameterDescriptorGroup(IdentifiedObjects.getProperties(previous), previous.getMinimumOccurs(), previous.getMaximumOccurs(), descriptors); } /** * Invoked by JAXB after unmarshalling. If the {@code <gml:OperationMethod>} element does not contain * any {@code <gml:parameter>}, we assume that this is a valid parameterless operation (as opposed to * an operation with unknown parameters). We need this assumption because, contrarily to GeoAPI model, * the GML schema does not differentiate "no parameters" from "unspecified parameters". */ private void afterUnmarshal(final Unmarshaller unmarshaller, final Object parent) { if (parameters == null) { parameters = CC_OperationMethod.group(super.getName(), new GeneralParameterDescriptor[0]); } } }
apache/sis
37,162
endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.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.sis.image; import java.awt.Image; import java.awt.Shape; import java.awt.Rectangle; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.awt.image.SampleModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.awt.image.WritableRenderedImage; import java.awt.image.RenderedImage; import java.util.Objects; import java.util.Vector; import java.util.function.DoubleUnaryOperator; import static java.lang.Math.multiplyFull; import org.apache.sis.util.Classes; import org.apache.sis.util.Disposable; import org.apache.sis.util.resources.Errors; import org.apache.sis.util.resources.Messages; import org.apache.sis.coverage.SampleDimension; import org.apache.sis.coverage.grid.GridGeometry; // For javadoc import org.apache.sis.image.internal.shared.ImageUtilities; import org.apache.sis.image.internal.shared.TileOpExecutor; import org.apache.sis.image.internal.shared.ColorModelFactory; import org.apache.sis.feature.internal.Resources; import org.apache.sis.pending.jdk.JDK18; /** * Base class of {@link RenderedImage} implementations in Apache SIS. * The "Planar" part in the class name emphasizes that this image is a representation * of two-dimensional data and should not contain an image with three-dimensional effects. * Planar images can be used as data storage for {@link org.apache.sis.coverage.grid.GridCoverage2D}. * * <div class="note"><b>Inspirational source:</b> * this class takes some inspiration from the {@code javax.media.jai.PlanarImage} * class defined in the <cite>Java Advanced Imaging</cite> (<abbr>JAI</abbr>) library. * That excellent library was 20 years in advance on thematic like defining a chain of image operations, * multi-threaded execution, distribution over a computer network, <i>etc.</i> * But unfortunately the <abbr>JAI</abbr> library does not seems to be maintained anymore. * We do not try to reproduce the full set of JAI functionalities here, but we progressively * reproduce some little bits of functionalities as they are needed by Apache SIS.</div> * * <p>This base class does not store any state, * but assumes that numbering of pixel coordinates and tile indices start at zero. * Subclasses need to implement at least the following methods:</p> * <ul> * <li>{@link #getWidth()} — the image width in pixels.</li> * <li>{@link #getHeight()} — the image height in pixels.</li> * <li>{@link #getTileWidth()} — the tile width in pixels.</li> * <li>{@link #getTileHeight()} — the tile height in pixels.</li> * <li>{@link #getTile(int,int)} — the tile at given tile indices.</li> * </ul> * * <p>If pixel coordinates or tile indices do not start at zero, * then subclasses shall also override the following methods:</p> * <ul> * <li>{@link #getMinX()} — the minimum <var>x</var> coordinate (inclusive) of the image.</li> * <li>{@link #getMinY()} — the minimum <var>y</var> coordinate (inclusive) of the image.</li> * <li>{@link #getMinTileX()} — the minimum tile index in the <var>x</var> direction.</li> * <li>{@link #getMinTileY()} — the minimum tile index in the <var>y</var> direction.</li> * </ul> * * Default implementations are provided for {@link #getNumXTiles()}, {@link #getNumYTiles()}, * {@link #getTileGridXOffset()}, {@link #getTileGridYOffset()}, {@link #getData()}, * {@link #getData(Rectangle)} and {@link #copyData(WritableRaster)} * in terms of above methods. * * <h2>Writable images</h2> * Some subclasses may implement the {@link WritableRenderedImage} interface. If this image is writable, * then the {@link WritableRenderedImage#getWritableTile WritableRenderedImage.getWritableTile(…)} and * {@link WritableRenderedImage#releaseWritableTile releaseWritableTile(…)} methods should be invoked in * {@code try ... finally} blocks like below: * * {@snippet lang="java" : * WritableRenderedImage image = ...; * WritableRaster tile = image.getWritableTile(tileX, tileY); * try { * // Do some process on the tile. * } finally { * image.releaseWritableTile(tileX, tileY); * } * } * * This is recommended because implementations may count the number of acquisitions and releases for deciding * when to notify the {@link java.awt.image.TileObserver}s. Some implementations may also acquire and release * synchronization locks in the {@code getWritableTile(…)} and {@code releaseWritableTile(…)} methods. * Apache SIS <a href="https://issues.apache.org/jira/browse/SIS-487">does not yet define a synchronization policy</a> * for {@link WritableRenderedImage}, but such policy may be defined in a future version. * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 1.5 * @since 1.1 */ public abstract class PlanarImage implements RenderedImage { /** * Key for a property identifying the grid dimensions that are represented as a two-dimensional image. * For an image which is the result of {@linkplain org.apache.sis.coverage.grid.GridCoverage#render * rendering a two-dimensional slice} of a multi-dimensional grid coverage, this property maps the * <var>x</var> and <var>y</var> axes of this image to the dimensions of the grid of the source coverage. * * <p>The property value is an {@code int[]} array of length 2. * The value at array index 0 identifies the source grid dimension of the <var>x</var> image axis, which is usually 0. * The value at array index 1 identifies the source grid dimension of the <var>y</var> image axis, which is usually 1.</p> * * @see org.apache.sis.coverage.grid.ImageRenderer#getXYDimensions() * @see org.apache.sis.coverage.grid.GridExtent#getSubspaceDimensions(int) * * @since 1.5 */ public static final String XY_DIMENSIONS_KEY = "org.apache.sis.XYDimensions"; /** * Key for a property defining a conversion from pixel coordinates to "real world" coordinates. * Other information include an envelope in "real world" coordinates and an estimation of pixel resolution. * The value is a {@link GridGeometry} instance with following properties: * * <ul> * <li>The {@linkplain GridGeometry#getDimension() number of grid dimensions} is always 2.</li> * <li>The number of {@linkplain GridGeometry#getCoordinateReferenceSystem() CRS} dimensions is always 2.</li> * <li>The {@linkplain GridGeometry#getExtent() grid extent} is the {@linkplain #getBounds() image bounds}.</li> * <li>The {@linkplain GridGeometry#getGridToCRS grid to CRS} map pixel coordinates "real world" coordinates * (always two-dimensional).</li> * </ul> * * @see org.apache.sis.coverage.grid.ImageRenderer#getImageGeometry(int) */ public static final String GRID_GEOMETRY_KEY = "org.apache.sis.GridGeometry"; /** * Key for a property giving an estimation of positional accuracy, typically in metres or pixel units. * Pixel positions may have limited accuracy when they are computed by * {@linkplain org.opengis.referencing.operation.Transformation coordinate transformations}. * The position may also be inaccurate because of approximation applied for faster rendering. * * <p>Values should be instances of <code>{@link javax.measure.Quantity[]}</code>. The array length * is typically 1 or 2. If accuracy is limited by a coordinate transformation, then the array should contain an * {@linkplain org.apache.sis.referencing.CRS#getLinearAccuracy accuracy expressed in a linear unit} such as meter. * If accuracy is limited by an {@linkplain ImageProcessor#setPositionalAccuracyHints approximation applied during * resampling operation}, then the array should contain an accuracy expressed in * {@linkplain org.apache.sis.measure.Units#PIXEL pixel units}.</p> * * @see ResampledImage#POSITIONAL_CONSISTENCY_KEY * @see org.opengis.referencing.operation.Transformation#getCoordinateOperationAccuracy() */ public static final String POSITIONAL_ACCURACY_KEY = "org.apache.sis.PositionalAccuracy"; /** * Key for a property defining a conversion from pixel values to the units of measurement. * The value should be an array of {@link SampleDimension} instances. * The array length should be the number of bands. * The array may contain null elements if this information is missing in some bands. * * <div class="note"><b>Example:</b> null elements may happen if this image is an * {@linkplain ImageProcessor#aggregateBands(RenderedImage...) aggregation of bands} * of two or more images, and some but not all images define this property.</div> * * @see org.apache.sis.coverage.grid.GridCoverage#getSampleDimensions() * * @since 1.4 */ public static final String SAMPLE_DIMENSIONS_KEY = "org.apache.sis.SampleDimensions"; /** * Key of a property defining the resolutions of sample values in each band. This property is recommended * for images having sample values as floating point numbers. For example if sample values were computed by * <var>value</var> = <var>integer</var> × <var>scale factor</var>, then the resolution is the scale factor. * This information can be used for choosing the number of fraction digits to show when writing sample values * in text format. * * <p><em>Resolution is not accuracy.</em> * There is no guarantee that the data accuracy is as good as the resolution given by this property.</p> * * <p>Values should be instances of {@code double[]}. * The array length should be the number of bands. This property may be computed automatically during * {@linkplain org.apache.sis.coverage.grid.GridCoverage#forConvertedValues(boolean) conversions from * integer values to floating point values}. Values should be strictly positive and finite but may be * {@link Double#NaN} if this information is unknown for a band.</p> */ public static final String SAMPLE_RESOLUTIONS_KEY = "org.apache.sis.SampleResolutions"; /** * Key of property providing statistics on sample values in each band. Providing a value for this key * is recommended when those statistics are known in advance (for example if they are provided in some * metadata of a raster format). Statistics are useful for stretching a color palette over the values * actually used in an image. * * <p>Values should be instances of <code>{@linkplain org.apache.sis.math.Statistics}[]</code>. * The array length should be the number of bands. Some array elements may be {@code null} * if the statistics are not available for all bands.</p> * * <p>Statistics are only indicative. They may be computed on a subset of the sample values. * If this property is not provided, some image rendering or exportation processes may have * to {@linkplain ImageProcessor#statistics compute statistics themselves} by iterating over * pixel values, which can be costly.</p> * * @see ImageProcessor#statistics(RenderedImage, Shape, DoubleUnaryOperator...) */ public static final String STATISTICS_KEY = "org.apache.sis.Statistics"; /** * Key of property providing a mask for missing values. Values should be instances of {@link RenderedImage} * with a single band, binary sample values and a color model of {@link java.awt.Transparency#BITMASK} type. * The binary values 0 and 1 are alpha values: 0 for fully transparent pixels and 1 for fully opaque pixels. * For every pixel (<var>x</var>,<var>y</var>) in this image, the pixel at the same coordinates in the mask * is either fully transparent (sample value 0) if the sample value in this image is valid, or fully opaque * (sample value 1) if the sample value in this image is invalid ({@link Float#NaN}). * * <p>If this {@code PlanarImage} has more than one band, then the value for this property is the overlay of * masks of each band: pixels are 0 when sample values are valid in all bands, and 1 when sample value is * invalid in at least one band.</p> * * <p>Note that it is usually not necessary to use masks explicitly in Apache SIS because missing values * are represented by {@link Float#NaN}. This property is provided for algorithms that cannot work with * NaN values.</p> */ public static final String MASK_KEY = "org.apache.sis.Mask"; /** * Creates a new rendered image. */ protected PlanarImage() { } /** * Returns the immediate sources of image data for this image. * This method returns {@code null} if the image has no information about its immediate sources. * It returns an empty vector if the image object has no immediate sources. * * <p>The default implementation returns {@code null}. * Note that this is not equivalent to an empty vector.</p> * * @return the immediate sources, or {@code null} if unknown. */ @Override @SuppressWarnings("UseOfObsoleteCollectionType") public Vector<RenderedImage> getSources() { return null; } /** * Gets a property from this image. The property to get is identified by the specified key. * The set of available keys is given by {@link #getPropertyNames()} and depends on the image instance. * The following table gives examples of keys recognized by some Apache SIS {@link RenderedImage} instances: * * <table class="sis"> * <caption>Examples of property keys</caption> * <tr> * <th>Keys</th> * <th>Values</th> * </tr><tr> * <td>{@value #XY_DIMENSIONS_KEY}</td> * <td>Indexes of the dimensions of the source grid which are represented as a rendered image.</td> * </tr><tr> * <td>{@value #GRID_GEOMETRY_KEY}</td> * <td>Conversion from pixel coordinates to "real world" coordinates.</td> * </tr><tr> * <td>{@value #POSITIONAL_ACCURACY_KEY}</td> * <td>Estimation of positional accuracy, typically in metres or pixel units.</td> * </tr><tr> * <td>{@value #SAMPLE_DIMENSIONS_KEY}</td> * <td>Conversions from pixel values to the units of measurement for each band.</td> * </tr><tr> * <td>{@value #SAMPLE_RESOLUTIONS_KEY}</td> * <td>Resolutions of sample values in each band.</td> * </tr><tr> * <td>{@value #STATISTICS_KEY}</td> * <td>Minimum, maximum and mean values for each band.</td> * </tr><tr> * <td>{@value #MASK_KEY}</td> * <td>Image with transparent pixels at locations of valid values and opaque pixels elsewhere.</td> * </tr><tr> * <td>{@value ResampledImage#POSITIONAL_CONSISTENCY_KEY}</td> * <td>Estimation of positional error for each pixel as a consistency check.</td> * </tr><tr> * <td>{@value ComputedImage#SOURCE_PADDING_KEY}</td> * <td>Amount of additional source pixels needed on each side of a destination pixel for computing its value.</td> * </tr> * </table> * * This method shall return {@link Image#UndefinedProperty} if the specified property is not defined. * The default implementation returns {@link Image#UndefinedProperty} in all cases. * * @param key the name of the property to get. * @return the property value, or {@link Image#UndefinedProperty} if none. */ @Override public Object getProperty(String key) { Objects.requireNonNull(key); return Image.UndefinedProperty; } /** * Returns the names of all recognized properties, * or {@code null} if this image has no properties. * This method may conservatively return the names of properties that <em>may</em> exist, * when checking if they actually exist would cause a potentially costly computation. * * <p>The default implementation returns {@code null}.</p> * * @return names of all recognized properties, or {@code null} if none. */ @Override public String[] getPropertyNames() { return null; } /** * Returns a shape containing all pixels that are valid in this image. * The returned shape may conservatively contain more than the minimal set of valid pixels. * It should be relatively quick to compute. In particular, invoking this method should not * cause the calculation of tiles (e.g. for searching NaN sample values). * The shape should be fully contained inside the image {@linkplain #getBounds() bounds}. * * <h4>Default implementation</h4> * The default implementation returns {@link #getBounds()}. * * @return a shape containing all pixels that are valid. Not necessarily the smallest shape * containing those pixels, but shall be fully contained inside the image bounds. * * @since 1.5 */ public Shape getValidArea() { return getBounds(); } /** * Returns the image location (<var>x</var>, <var>y</var>) and image size (<var>width</var>, <var>height</var>). * This is a convenience method encapsulating the results of 4 method calls in a single object. * * @return the image location and image size as a new rectangle. * * @see #getMinX() * @see #getMinY() * @see #getWidth() * @see #getHeight() */ public Rectangle getBounds() { return ImageUtilities.getBounds(this); } /** * Returns the minimum <var>x</var> coordinate (inclusive) of this image. * * <p>Default implementation returns zero. * Subclasses shall override this method if the image starts at another coordinate.</p> * * @return the minimum <var>x</var> coordinate (column) of this image. */ @Override public int getMinX() { return 0; } /** * Returns the minimum <var>y</var> coordinate (inclusive) of this image. * * <p>The default implementation returns zero. * Subclasses shall override this method if the image starts at another coordinate.</p> * * @return the minimum <var>y</var> coordinate (row) of this image. */ @Override public int getMinY() { return 0; } /** * Returns the minimum tile index in the <var>x</var> direction. * * <p>The default implementation returns zero. * Subclasses shall override this method if the tile grid starts at another index.</p> * * @return the minimum tile index in the <var>x</var> direction. */ @Override public int getMinTileX() { return 0; } /** * Returns the minimum tile index in the <var>y</var> direction. * * <p>The default implementation returns zero. * Subclasses shall override this method if the tile grid starts at another index.</p> * * @return the minimum tile index in the <var>y</var> direction. */ @Override public int getMinTileY() { return 0; } /** * Returns the number of tiles in the <var>x</var> direction. * * <p>The default implementation computes this value from {@link #getWidth()} and {@link #getTileWidth()} * on the assumption that {@link #getMinX()} is the coordinate of the leftmost pixels of tiles located at * {@link #getMinTileX()} index. This assumption can be verified by {@link #verify()}.</p> * * @return returns the number of tiles in the <var>x</var> direction. */ @Override public int getNumXTiles() { /* * If assumption documented in javadoc does not hold, the calculation performed here would need to be * more complicated: compute tile index of minX, compute tile index of maxX, return difference plus 1. */ return JDK18.ceilDiv(getWidth(), getTileWidth()); } /** * Returns the number of tiles in the <var>y</var> direction. * * <p>The default implementation computes this value from {@link #getHeight()} and {@link #getTileHeight()} * on the assumption that {@link #getMinY()} is the coordinate of the uppermost pixels of tiles located at * {@link #getMinTileY()} index. This assumption can be verified by {@link #verify()}.</p> * * @return returns the number of tiles in the <var>y</var> direction. */ @Override public int getNumYTiles() { return JDK18.ceilDiv(getHeight(), getTileHeight()); } /** * Returns the <var>x</var> coordinate of the upper-left pixel of tile (0, 0). * That tile (0, 0) may not actually exist. * * <p>The default implementation computes this value from {@link #getMinX()}, * {@link #getMinTileX()} and {@link #getTileWidth()}.</p> * * @return the <var>x</var> offset of the tile grid relative to the origin. */ @Override public int getTileGridXOffset() { // We may have temporary `int` overflow after multiplication but exact result after addition. return Math.toIntExact(getMinX() - multiplyFull(getMinTileX(), getTileWidth())); } /** * Returns the <var>y</var> coordinate of the upper-left pixel of tile (0, 0). * That tile (0, 0) may not actually exist. * * <p>The default implementation computes this value from {@link #getMinY()}, * {@link #getMinTileY()} and {@link #getTileHeight()}.</p> * * @return the <var>y</var> offset of the tile grid relative to the origin. */ @Override public int getTileGridYOffset() { return Math.toIntExact(getMinY() - multiplyFull(getMinTileY(), getTileHeight())); } /** * Creates a raster with the same sample model as this image and with the given size and location. * This method does not verify argument validity. */ private WritableRaster createWritableRaster(final Rectangle aoi) { SampleModel sm = getSampleModel(); if (sm.getWidth() != aoi.width || sm.getHeight() != aoi.height) { sm = sm.createCompatibleSampleModel(aoi.width, aoi.height); } return Raster.createWritableRaster(sm, aoi.getLocation()); } /** * Returns a copy of this image as one large tile. * The returned raster will not be updated if this image is changed. * * @return a copy of this image as one large tile. */ @Override public Raster getData() { final Rectangle aoi = getBounds(); final WritableRaster raster = createWritableRaster(aoi); copyData(aoi, this, raster); return raster; } /** * Returns a copy of an arbitrary region of this image. * The returned raster will not be updated if this image is changed. * * @param aoi the region of this image to copy. * @return a copy of this image in the given area of interest. * @throws IllegalArgumentException if the given rectangle is not contained in this image bounds. */ @Override public Raster getData(final Rectangle aoi) { if (!getBounds().contains(aoi)) { throw new IllegalArgumentException(Errors.format(Errors.Keys.OutsideDomainOfValidity)); } final WritableRaster raster = createWritableRaster(aoi); copyData(aoi, this, raster); return raster; } /** * Copies an arbitrary rectangular region of this image to the supplied writable raster. * The region to be copied is determined from the bounds of the supplied raster. * The supplied raster must have a {@link SampleModel} that is compatible with this image. * If the given raster is {@code null}, a new raster is created by this method. * * @param raster the raster to hold a copy of this image, or {@code null}. * @return the given raster if it was not-null, or a new raster otherwise. */ @Override public WritableRaster copyData(WritableRaster raster) { final Rectangle aoi; if (raster != null) { aoi = raster.getBounds(); ImageUtilities.clipBounds(this, aoi); } else { aoi = getBounds(); raster = createWritableRaster(aoi); } if (!aoi.isEmpty()) { copyData(aoi, this, raster); } return raster; } /** * Implementation of {@link #getData()}, {@link #getData(Rectangle)} and {@link #copyData(WritableRaster)}. * It is caller responsibility to ensure that all arguments are non-null and that the rectangle is contained * inside both this image and the given raster. * * @param aoi the region of the {@code source} image to copy. * @param source the source of pixel data. * @param target the raster to hold a copy of the source image. */ static void copyData(final Rectangle aoi, final RenderedImage source, final WritableRaster target) { /* * Iterate over all tiles that interesect the specified area of interest (AOI). * For each tile, delegate to `WritableRaster.setRect(…)` because that method is * overridden with optimized implementations in various Sun's raster subclasses. * Note that `t` rectangle should never be empty because we restrict iteration * to the tiles that intersect the given area of interest. */ final TileOpExecutor executor = new TileOpExecutor(source, aoi) { /** Invoked for each tile to copy to target raster. */ @Override protected void readFrom(Raster tile) { final Rectangle bounds = tile.getBounds(); final Rectangle t = aoi.intersection(bounds); if (!t.equals(bounds)) { tile = tile.createChild(t.x, t.y, t.width, t.height, t.x, t.y, null); } target.setRect(tile); } }; executor.readFrom(source); } /** * Notifies this image that tiles will be computed soon in the given region. * The method contract is given by {@link ComputedImage#prefetch(Rectangle)}. * * @param tiles indices of the tiles which will be prefetched. * @return handler on which to invoke {@code dispose()} after the prefetch operation * completed (successfully or not), or {@code null} if none. */ Disposable prefetch(Rectangle tiles) { return null; } /** * Ensures that a user supplied color model is compatible with the sample model. * This is a helper method for argument validation in sub-classes constructors. * * @param sampleModel the sample model of this image. * @param colors the color model to validate. Can be {@code null}. * @throws IllegalArgumentException if the color model is incompatible. */ static void ensureCompatible(final SampleModel sampleModel, final ColorModel colors) { final String erroneous = verifyCompatibility(sampleModel, colors); if (erroneous != null) { String message = Resources.format(Resources.Keys.IncompatibleColorModel); if (!erroneous.isEmpty()) { String complement = Classes.getShortClassName(colors); complement = Errors.format(Errors.Keys.IllegalPropertyValue_2, complement, erroneous); message = Resources.concatenate(message, complement); } throw new IllegalArgumentException(message); } } /** * Verifies if the color model is compatible with the sample model. * If the color model is incompatible, then this method returns the name of the mismatched property. * If the returned property is an empty string, then the mismatched property is unidentified. * * @param sm the sample model. Shall not be null. * @param cm the color model, or {@code null} if unspecified. * @return name of mismatched property (an empty string if unidentified), * or {@code null} if the color model is null or is compatible. */ private static String verifyCompatibility(final SampleModel sm, final ColorModel cm) { if (cm == null || cm.isCompatibleSampleModel(sm)) return null; if (cm.getTransferType() != sm.getTransferType()) return "transferType"; if (cm.getNumComponents() != sm.getNumBands()) return "numComponents"; return ""; } /** * Verifies whether image layout information are consistent. This method verifies that the coordinates * of image upper-left corner are equal to the coordinates of the upper-left corner of the tile in the * upper-left corner, and that image size is equal to the sum of the sizes of all tiles. Compatibility * of sample model and color model is also verified. * * <p>The default implementation may return the following identifiers, in that order * (i.e. this method returns the identifier of the first test that fail):</p> * * <table class="sis"> * <caption>Identifiers of inconsistent values</caption> * <tr><th>Identifier</th> <th>Meaning</th></tr> * <tr><td>{@code "colorModel"}</td> <td>Color model is incompatible with sample model.</td></tr> * <tr><td>{@code "tileWidth"}</td> <td>Tile width is greater than sample model width.</td></tr> * <tr><td>{@code "tileHeight"}</td> <td>Tile height is greater than sample model height.</td></tr> * <tr><td>{@code "numXTiles"}</td> <td>Number of tiles on the X axis is inconsistent with image width.</td></tr> * <tr><td>{@code "numYTiles"}</td> <td>Number of tiles on the Y axis is inconsistent with image height.</td></tr> * <tr><td>{@code "tileX"}</td> <td>{@code minTileX} and/or {@code tileGridXOffset} is inconsistent.</td></tr> * <tr><td>{@code "tileY"}</td> <td>{@code minTileY} and/or {@code tileGridYOffset} is inconsistent.</td></tr> * <tr><td>{@code "width"}</td> <td>image width is not an integer multiple of tile width.</td></tr> * <tr><td>{@code "height"}</td> <td>Image height is not an integer multiple of tile height.</td></tr> * </table> * * Subclasses may perform additional checks. For example, some subclasses have specialized checks * for {@code "minX"}, {@code "minY"}, {@code "tileGridXOffset"} and {@code "tileGridYOffset"} * values before to fallback on the more generic {@code "tileX"} and {@code "tileY"} above checks. * The returned identifiers may also have subcategories. For example {@code "colorModel"} may be * subdivided with {@code "colorModel.numBands"} and {@code "colorModel.transferType"}. * * <h4>Ignorable inconsistency</h4> * Inconsistency in {@code "width"} and {@code "height"} values may be acceptable * if all other verifications pass (in particular the {@code "numXTiles"} and {@code "numYTiles"} checks). * It happens when tiles in the last row or last column have some unused space compared to the image size. * This is legal in TIFF format for example. For this reason, the {@code "width"} and {@code "height"} * values should be checked last, after all other values have been verified consistent. * * @return {@code null} if image layout information are consistent, * or the name of inconsistent attribute if a problem is found. */ public String verify() { final int tileWidth = getTileWidth(); final int tileHeight = getTileHeight(); final SampleModel sm = getSampleModel(); if (sm != null) { final String cm = verifyCompatibility(sm, getColorModel()); if (cm != null) { String p = "colorModel"; if (!cm.isEmpty()) p = p + '.' + cm; return p; } /* * The SampleModel size represents the physical layout of pixels in the data buffer, * while the Raster may be a virtual view over a sub-region of a parent raster. */ if (sm.getWidth() < tileWidth) return "tileWidth"; if (sm.getHeight() < tileHeight) return "tileHeight"; } long remainder = multiplyFull(getNumXTiles(), tileWidth) - getWidth(); if (remainder != 0) { return (remainder >= 0 && remainder < tileWidth) ? "width" : "numXTiles"; } remainder = multiplyFull(getNumYTiles(), tileHeight) - getHeight(); if (remainder != 0) { return (remainder >= 0 && remainder < tileHeight) ? "height" : "numYTiles"; } if (multiplyFull(getMinTileX(), tileWidth) + getTileGridXOffset() != getMinX()) return "tileX"; if (multiplyFull(getMinTileY(), tileHeight) + getTileGridYOffset() != getMinY()) return "tileY"; return null; } /** * Returns a string representation of this image for debugging purpose. * This string representation may change in any future SIS version. * * @return a string representation of this image for debugging purpose only. */ @Override public String toString() { final var buffer = new StringBuilder(100).append(Classes.getShortClassName(this)) .append("[(").append(getWidth()).append(" × ").append(getHeight()).append(") pixels starting at ") .append('(').append(getMinX()).append(", ").append(getMinY()).append(')'); final SampleModel sm = getSampleModel(); if (sm != null) { buffer.append(" in ").append(sm.getNumBands()).append(" bands"); final String type = ImageUtilities.getDataTypeName(sm); if (type != null) { buffer.append(" of type ").append(type); } } /* * Write details about color model only if there is "useful" information for a geospatial raster. * The main category of interest are "color palette" versus "gray scale" versus everything else, * and whether the image may have transparent pixels. */ final ColorModel cm = getColorModel(); colors: if (cm != null) { buffer.append(". Colors: "); if (cm instanceof IndexColorModel) { buffer.append(((IndexColorModel) cm).getMapSize()).append(" indexed colors"); } else { ColorModelFactory.formatDescription(cm.getColorSpace(), buffer); } final String transparency; switch (cm.getTransparency()) { case ColorModel.OPAQUE: transparency = "opaque"; break; case ColorModel.TRANSLUCENT: transparency = "translucent"; break; case ColorModel.BITMASK: transparency = "bitmask transparency"; break; default: break colors; } buffer.append("; ").append(transparency); } /* * Tiling information last because it is usually a secondary aspect compared to above information. * If a warning is emitted, it will usually be a tiling problem so it is useful to keep it close. */ final int tx = getNumXTiles(); final int ty = getNumYTiles(); if (tx != 1 || ty != 1) { buffer.append("; ").append(tx).append(" × ").append(ty).append(" tiles"); } buffer.append(']'); final String error = verify(); if (error != null) { buffer.append(System.lineSeparator()).append("└─") .append(Messages.format(Messages.Keys.PossibleInconsistency_1, error)); } return buffer.toString(); } /* * Note on `equals(Object)` and `hashCode()` methods: * * Do not provide base implementation for those methods, because they can only be incomplete and it is too easy * to forget to override those methods in subclasses. Furthermore, we should override those methods only in final * classes that are read-only images. Base classes of potentially writable images should continue to use identity * comparisons, especially when some tiles have been acquired for writing and not yet released at the time the * `equals(Object)` method is invoked. */ }
googleapis/google-cloud-java
36,904
java-document-ai/proto-google-cloud-document-ai-v1/src/main/java/com/google/cloud/documentai/v1/ListProcessorTypesResponse.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/documentai/v1/document_processor_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.documentai.v1; /** * * * <pre> * Response message for the * [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] * method. * </pre> * * Protobuf type {@code google.cloud.documentai.v1.ListProcessorTypesResponse} */ public final class ListProcessorTypesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.documentai.v1.ListProcessorTypesResponse) ListProcessorTypesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListProcessorTypesResponse.newBuilder() to construct. private ListProcessorTypesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListProcessorTypesResponse() { processorTypes_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListProcessorTypesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.documentai.v1.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1_ListProcessorTypesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.documentai.v1.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1_ListProcessorTypesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.documentai.v1.ListProcessorTypesResponse.class, com.google.cloud.documentai.v1.ListProcessorTypesResponse.Builder.class); } public static final int PROCESSOR_TYPES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.documentai.v1.ProcessorType> processorTypes_; /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.documentai.v1.ProcessorType> getProcessorTypesList() { return processorTypes_; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.documentai.v1.ProcessorTypeOrBuilder> getProcessorTypesOrBuilderList() { return processorTypes_; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ @java.lang.Override public int getProcessorTypesCount() { return processorTypes_.size(); } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ @java.lang.Override public com.google.cloud.documentai.v1.ProcessorType getProcessorTypes(int index) { return processorTypes_.get(index); } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ @java.lang.Override public com.google.cloud.documentai.v1.ProcessorTypeOrBuilder getProcessorTypesOrBuilder( int index) { return processorTypes_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Points to the next page, otherwise empty. * </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> * Points to the next page, otherwise empty. * </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 < processorTypes_.size(); i++) { output.writeMessage(1, processorTypes_.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 < processorTypes_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, processorTypes_.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.documentai.v1.ListProcessorTypesResponse)) { return super.equals(obj); } com.google.cloud.documentai.v1.ListProcessorTypesResponse other = (com.google.cloud.documentai.v1.ListProcessorTypesResponse) obj; if (!getProcessorTypesList().equals(other.getProcessorTypesList())) 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 (getProcessorTypesCount() > 0) { hash = (37 * hash) + PROCESSOR_TYPES_FIELD_NUMBER; hash = (53 * hash) + getProcessorTypesList().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.documentai.v1.ListProcessorTypesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse 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.documentai.v1.ListProcessorTypesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse 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.documentai.v1.ListProcessorTypesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse 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.documentai.v1.ListProcessorTypesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse 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.documentai.v1.ListProcessorTypesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse 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.documentai.v1.ListProcessorTypesResponse 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 * [ListProcessorTypes][google.cloud.documentai.v1.DocumentProcessorService.ListProcessorTypes] * method. * </pre> * * Protobuf type {@code google.cloud.documentai.v1.ListProcessorTypesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.documentai.v1.ListProcessorTypesResponse) com.google.cloud.documentai.v1.ListProcessorTypesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.documentai.v1.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1_ListProcessorTypesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.documentai.v1.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1_ListProcessorTypesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.documentai.v1.ListProcessorTypesResponse.class, com.google.cloud.documentai.v1.ListProcessorTypesResponse.Builder.class); } // Construct using com.google.cloud.documentai.v1.ListProcessorTypesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (processorTypesBuilder_ == null) { processorTypes_ = java.util.Collections.emptyList(); } else { processorTypes_ = null; processorTypesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.documentai.v1.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1_ListProcessorTypesResponse_descriptor; } @java.lang.Override public com.google.cloud.documentai.v1.ListProcessorTypesResponse getDefaultInstanceForType() { return com.google.cloud.documentai.v1.ListProcessorTypesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.documentai.v1.ListProcessorTypesResponse build() { com.google.cloud.documentai.v1.ListProcessorTypesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.documentai.v1.ListProcessorTypesResponse buildPartial() { com.google.cloud.documentai.v1.ListProcessorTypesResponse result = new com.google.cloud.documentai.v1.ListProcessorTypesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.documentai.v1.ListProcessorTypesResponse result) { if (processorTypesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { processorTypes_ = java.util.Collections.unmodifiableList(processorTypes_); bitField0_ = (bitField0_ & ~0x00000001); } result.processorTypes_ = processorTypes_; } else { result.processorTypes_ = processorTypesBuilder_.build(); } } private void buildPartial0(com.google.cloud.documentai.v1.ListProcessorTypesResponse 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.documentai.v1.ListProcessorTypesResponse) { return mergeFrom((com.google.cloud.documentai.v1.ListProcessorTypesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.documentai.v1.ListProcessorTypesResponse other) { if (other == com.google.cloud.documentai.v1.ListProcessorTypesResponse.getDefaultInstance()) return this; if (processorTypesBuilder_ == null) { if (!other.processorTypes_.isEmpty()) { if (processorTypes_.isEmpty()) { processorTypes_ = other.processorTypes_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProcessorTypesIsMutable(); processorTypes_.addAll(other.processorTypes_); } onChanged(); } } else { if (!other.processorTypes_.isEmpty()) { if (processorTypesBuilder_.isEmpty()) { processorTypesBuilder_.dispose(); processorTypesBuilder_ = null; processorTypes_ = other.processorTypes_; bitField0_ = (bitField0_ & ~0x00000001); processorTypesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getProcessorTypesFieldBuilder() : null; } else { processorTypesBuilder_.addAllMessages(other.processorTypes_); } } } 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.documentai.v1.ProcessorType m = input.readMessage( com.google.cloud.documentai.v1.ProcessorType.parser(), extensionRegistry); if (processorTypesBuilder_ == null) { ensureProcessorTypesIsMutable(); processorTypes_.add(m); } else { processorTypesBuilder_.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.documentai.v1.ProcessorType> processorTypes_ = java.util.Collections.emptyList(); private void ensureProcessorTypesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { processorTypes_ = new java.util.ArrayList<com.google.cloud.documentai.v1.ProcessorType>(processorTypes_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.documentai.v1.ProcessorType, com.google.cloud.documentai.v1.ProcessorType.Builder, com.google.cloud.documentai.v1.ProcessorTypeOrBuilder> processorTypesBuilder_; /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public java.util.List<com.google.cloud.documentai.v1.ProcessorType> getProcessorTypesList() { if (processorTypesBuilder_ == null) { return java.util.Collections.unmodifiableList(processorTypes_); } else { return processorTypesBuilder_.getMessageList(); } } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public int getProcessorTypesCount() { if (processorTypesBuilder_ == null) { return processorTypes_.size(); } else { return processorTypesBuilder_.getCount(); } } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public com.google.cloud.documentai.v1.ProcessorType getProcessorTypes(int index) { if (processorTypesBuilder_ == null) { return processorTypes_.get(index); } else { return processorTypesBuilder_.getMessage(index); } } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder setProcessorTypes( int index, com.google.cloud.documentai.v1.ProcessorType value) { if (processorTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProcessorTypesIsMutable(); processorTypes_.set(index, value); onChanged(); } else { processorTypesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder setProcessorTypes( int index, com.google.cloud.documentai.v1.ProcessorType.Builder builderForValue) { if (processorTypesBuilder_ == null) { ensureProcessorTypesIsMutable(); processorTypes_.set(index, builderForValue.build()); onChanged(); } else { processorTypesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder addProcessorTypes(com.google.cloud.documentai.v1.ProcessorType value) { if (processorTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProcessorTypesIsMutable(); processorTypes_.add(value); onChanged(); } else { processorTypesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder addProcessorTypes( int index, com.google.cloud.documentai.v1.ProcessorType value) { if (processorTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProcessorTypesIsMutable(); processorTypes_.add(index, value); onChanged(); } else { processorTypesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder addProcessorTypes( com.google.cloud.documentai.v1.ProcessorType.Builder builderForValue) { if (processorTypesBuilder_ == null) { ensureProcessorTypesIsMutable(); processorTypes_.add(builderForValue.build()); onChanged(); } else { processorTypesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder addProcessorTypes( int index, com.google.cloud.documentai.v1.ProcessorType.Builder builderForValue) { if (processorTypesBuilder_ == null) { ensureProcessorTypesIsMutable(); processorTypes_.add(index, builderForValue.build()); onChanged(); } else { processorTypesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder addAllProcessorTypes( java.lang.Iterable<? extends com.google.cloud.documentai.v1.ProcessorType> values) { if (processorTypesBuilder_ == null) { ensureProcessorTypesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, processorTypes_); onChanged(); } else { processorTypesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder clearProcessorTypes() { if (processorTypesBuilder_ == null) { processorTypes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { processorTypesBuilder_.clear(); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public Builder removeProcessorTypes(int index) { if (processorTypesBuilder_ == null) { ensureProcessorTypesIsMutable(); processorTypes_.remove(index); onChanged(); } else { processorTypesBuilder_.remove(index); } return this; } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public com.google.cloud.documentai.v1.ProcessorType.Builder getProcessorTypesBuilder( int index) { return getProcessorTypesFieldBuilder().getBuilder(index); } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public com.google.cloud.documentai.v1.ProcessorTypeOrBuilder getProcessorTypesOrBuilder( int index) { if (processorTypesBuilder_ == null) { return processorTypes_.get(index); } else { return processorTypesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public java.util.List<? extends com.google.cloud.documentai.v1.ProcessorTypeOrBuilder> getProcessorTypesOrBuilderList() { if (processorTypesBuilder_ != null) { return processorTypesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(processorTypes_); } } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public com.google.cloud.documentai.v1.ProcessorType.Builder addProcessorTypesBuilder() { return getProcessorTypesFieldBuilder() .addBuilder(com.google.cloud.documentai.v1.ProcessorType.getDefaultInstance()); } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public com.google.cloud.documentai.v1.ProcessorType.Builder addProcessorTypesBuilder( int index) { return getProcessorTypesFieldBuilder() .addBuilder(index, com.google.cloud.documentai.v1.ProcessorType.getDefaultInstance()); } /** * * * <pre> * The processor types. * </pre> * * <code>repeated .google.cloud.documentai.v1.ProcessorType processor_types = 1;</code> */ public java.util.List<com.google.cloud.documentai.v1.ProcessorType.Builder> getProcessorTypesBuilderList() { return getProcessorTypesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.documentai.v1.ProcessorType, com.google.cloud.documentai.v1.ProcessorType.Builder, com.google.cloud.documentai.v1.ProcessorTypeOrBuilder> getProcessorTypesFieldBuilder() { if (processorTypesBuilder_ == null) { processorTypesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.documentai.v1.ProcessorType, com.google.cloud.documentai.v1.ProcessorType.Builder, com.google.cloud.documentai.v1.ProcessorTypeOrBuilder>( processorTypes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); processorTypes_ = null; } return processorTypesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Points to the next page, otherwise empty. * </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> * Points to the next page, otherwise empty. * </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> * Points to the next page, otherwise empty. * </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> * Points to the next page, otherwise empty. * </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> * Points to the next page, otherwise empty. * </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.documentai.v1.ListProcessorTypesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.documentai.v1.ListProcessorTypesResponse) private static final com.google.cloud.documentai.v1.ListProcessorTypesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.documentai.v1.ListProcessorTypesResponse(); } public static com.google.cloud.documentai.v1.ListProcessorTypesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListProcessorTypesResponse> PARSER = new com.google.protobuf.AbstractParser<ListProcessorTypesResponse>() { @java.lang.Override public ListProcessorTypesResponse 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<ListProcessorTypesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListProcessorTypesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.documentai.v1.ListProcessorTypesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,906
java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListContextsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/metadata_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1; /** * * * <pre> * Response message for * [MetadataService.ListContexts][google.cloud.aiplatform.v1.MetadataService.ListContexts]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListContextsResponse} */ public final class ListContextsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListContextsResponse) ListContextsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListContextsResponse.newBuilder() to construct. private ListContextsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListContextsResponse() { contexts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListContextsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1_ListContextsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1_ListContextsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListContextsResponse.class, com.google.cloud.aiplatform.v1.ListContextsResponse.Builder.class); } public static final int CONTEXTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1.Context> contexts_; /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1.Context> getContextsList() { return contexts_; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1.ContextOrBuilder> getContextsOrBuilderList() { return contexts_; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ @java.lang.Override public int getContextsCount() { return contexts_.size(); } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.Context getContexts(int index) { return contexts_.get(index); } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.ContextOrBuilder getContextsOrBuilder(int index) { return contexts_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, 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 * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, 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 < contexts_.size(); i++) { output.writeMessage(1, contexts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < contexts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, contexts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1.ListContextsResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.ListContextsResponse other = (com.google.cloud.aiplatform.v1.ListContextsResponse) obj; if (!getContextsList().equals(other.getContextsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getContextsCount() > 0) { hash = (37 * hash) + CONTEXTS_FIELD_NUMBER; hash = (53 * hash) + getContextsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListContextsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.aiplatform.v1.ListContextsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for * [MetadataService.ListContexts][google.cloud.aiplatform.v1.MetadataService.ListContexts]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListContextsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListContextsResponse) com.google.cloud.aiplatform.v1.ListContextsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1_ListContextsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1_ListContextsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListContextsResponse.class, com.google.cloud.aiplatform.v1.ListContextsResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.ListContextsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (contextsBuilder_ == null) { contexts_ = java.util.Collections.emptyList(); } else { contexts_ = null; contextsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1_ListContextsResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListContextsResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.ListContextsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.ListContextsResponse build() { com.google.cloud.aiplatform.v1.ListContextsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListContextsResponse buildPartial() { com.google.cloud.aiplatform.v1.ListContextsResponse result = new com.google.cloud.aiplatform.v1.ListContextsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1.ListContextsResponse result) { if (contextsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { contexts_ = java.util.Collections.unmodifiableList(contexts_); bitField0_ = (bitField0_ & ~0x00000001); } result.contexts_ = contexts_; } else { result.contexts_ = contextsBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1.ListContextsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1.ListContextsResponse) { return mergeFrom((com.google.cloud.aiplatform.v1.ListContextsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListContextsResponse other) { if (other == com.google.cloud.aiplatform.v1.ListContextsResponse.getDefaultInstance()) return this; if (contextsBuilder_ == null) { if (!other.contexts_.isEmpty()) { if (contexts_.isEmpty()) { contexts_ = other.contexts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureContextsIsMutable(); contexts_.addAll(other.contexts_); } onChanged(); } } else { if (!other.contexts_.isEmpty()) { if (contextsBuilder_.isEmpty()) { contextsBuilder_.dispose(); contextsBuilder_ = null; contexts_ = other.contexts_; bitField0_ = (bitField0_ & ~0x00000001); contextsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getContextsFieldBuilder() : null; } else { contextsBuilder_.addAllMessages(other.contexts_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.aiplatform.v1.Context m = input.readMessage( com.google.cloud.aiplatform.v1.Context.parser(), extensionRegistry); if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.add(m); } else { contextsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.aiplatform.v1.Context> contexts_ = java.util.Collections.emptyList(); private void ensureContextsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { contexts_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1.Context>(contexts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.Context, com.google.cloud.aiplatform.v1.Context.Builder, com.google.cloud.aiplatform.v1.ContextOrBuilder> contextsBuilder_; /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.Context> getContextsList() { if (contextsBuilder_ == null) { return java.util.Collections.unmodifiableList(contexts_); } else { return contextsBuilder_.getMessageList(); } } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public int getContextsCount() { if (contextsBuilder_ == null) { return contexts_.size(); } else { return contextsBuilder_.getCount(); } } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public com.google.cloud.aiplatform.v1.Context getContexts(int index) { if (contextsBuilder_ == null) { return contexts_.get(index); } else { return contextsBuilder_.getMessage(index); } } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder setContexts(int index, com.google.cloud.aiplatform.v1.Context value) { if (contextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContextsIsMutable(); contexts_.set(index, value); onChanged(); } else { contextsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder setContexts( int index, com.google.cloud.aiplatform.v1.Context.Builder builderForValue) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.set(index, builderForValue.build()); onChanged(); } else { contextsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder addContexts(com.google.cloud.aiplatform.v1.Context value) { if (contextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContextsIsMutable(); contexts_.add(value); onChanged(); } else { contextsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder addContexts(int index, com.google.cloud.aiplatform.v1.Context value) { if (contextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContextsIsMutable(); contexts_.add(index, value); onChanged(); } else { contextsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder addContexts(com.google.cloud.aiplatform.v1.Context.Builder builderForValue) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.add(builderForValue.build()); onChanged(); } else { contextsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder addContexts( int index, com.google.cloud.aiplatform.v1.Context.Builder builderForValue) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.add(index, builderForValue.build()); onChanged(); } else { contextsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder addAllContexts( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.Context> values) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, contexts_); onChanged(); } else { contextsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder clearContexts() { if (contextsBuilder_ == null) { contexts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { contextsBuilder_.clear(); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public Builder removeContexts(int index) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.remove(index); onChanged(); } else { contextsBuilder_.remove(index); } return this; } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public com.google.cloud.aiplatform.v1.Context.Builder getContextsBuilder(int index) { return getContextsFieldBuilder().getBuilder(index); } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public com.google.cloud.aiplatform.v1.ContextOrBuilder getContextsOrBuilder(int index) { if (contextsBuilder_ == null) { return contexts_.get(index); } else { return contextsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1.ContextOrBuilder> getContextsOrBuilderList() { if (contextsBuilder_ != null) { return contextsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(contexts_); } } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public com.google.cloud.aiplatform.v1.Context.Builder addContextsBuilder() { return getContextsFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1.Context.getDefaultInstance()); } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public com.google.cloud.aiplatform.v1.Context.Builder addContextsBuilder(int index) { return getContextsFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1.Context.getDefaultInstance()); } /** * * * <pre> * The Contexts retrieved from the MetadataStore. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.Context contexts = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.Context.Builder> getContextsBuilderList() { return getContextsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.Context, com.google.cloud.aiplatform.v1.Context.Builder, com.google.cloud.aiplatform.v1.ContextOrBuilder> getContextsFieldBuilder() { if (contextsBuilder_ == null) { contextsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.Context, com.google.cloud.aiplatform.v1.Context.Builder, com.google.cloud.aiplatform.v1.ContextOrBuilder>( contexts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); contexts_ = null; } return contextsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, 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 * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, 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 * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, 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 * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, 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 * [ListContextsRequest.page_token][google.cloud.aiplatform.v1.ListContextsRequest.page_token] * to retrieve the next page. * If this field is not populated, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ListContextsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListContextsResponse) private static final com.google.cloud.aiplatform.v1.ListContextsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListContextsResponse(); } public static com.google.cloud.aiplatform.v1.ListContextsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListContextsResponse> PARSER = new com.google.protobuf.AbstractParser<ListContextsResponse>() { @java.lang.Override public ListContextsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListContextsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListContextsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListContextsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }